Bitcoin Core  24.1.0
P2P Digital Currency
addresses.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <core_io.h>
6 #include <key_io.h>
7 #include <rpc/util.h>
8 #include <util/bip32.h>
9 #include <util/translation.h>
10 #include <wallet/receive.h>
11 #include <wallet/rpc/util.h>
12 #include <wallet/wallet.h>
13 
14 #include <univalue.h>
15 
16 namespace wallet {
18 {
19  return RPCHelpMan{"getnewaddress",
20  "\nReturns a new Bitcoin address for receiving payments.\n"
21  "If 'label' is specified, it is added to the address book \n"
22  "so payments received with the address will be associated with 'label'.\n",
23  {
24  {"label", RPCArg::Type::STR, RPCArg::Default{""}, "The label name for the address to be linked to. It can also be set to the empty string \"\" to represent the default label. The label does not need to exist, it will be created if there is no label by the given name."},
25  {"address_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -addresstype"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."},
26  },
27  RPCResult{
28  RPCResult::Type::STR, "address", "The new bitcoin address"
29  },
31  HelpExampleCli("getnewaddress", "")
32  + HelpExampleRpc("getnewaddress", "")
33  },
34  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
35 {
36  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
37  if (!pwallet) return UniValue::VNULL;
38 
39  LOCK(pwallet->cs_wallet);
40 
41  if (!pwallet->CanGetAddresses()) {
42  throw JSONRPCError(RPC_WALLET_ERROR, "Error: This wallet has no available keys");
43  }
44 
45  // Parse the label first so we don't generate a key if there's an error
46  std::string label;
47  if (!request.params[0].isNull())
48  label = LabelFromValue(request.params[0]);
49 
50  OutputType output_type = pwallet->m_default_address_type;
51  if (!request.params[1].isNull()) {
52  std::optional<OutputType> parsed = ParseOutputType(request.params[1].get_str());
53  if (!parsed) {
54  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[1].get_str()));
55  } else if (parsed.value() == OutputType::BECH32M && pwallet->GetLegacyScriptPubKeyMan()) {
56  throw JSONRPCError(RPC_INVALID_PARAMETER, "Legacy wallets cannot provide bech32m addresses");
57  }
58  output_type = parsed.value();
59  }
60 
61  auto op_dest = pwallet->GetNewDestination(output_type, label);
62  if (!op_dest) {
64  }
65 
66  return EncodeDestination(*op_dest);
67 },
68  };
69 }
70 
72 {
73  return RPCHelpMan{"getrawchangeaddress",
74  "\nReturns a new Bitcoin address, for receiving change.\n"
75  "This is for use with raw transactions, NOT normal use.\n",
76  {
77  {"address_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."},
78  },
79  RPCResult{
80  RPCResult::Type::STR, "address", "The address"
81  },
83  HelpExampleCli("getrawchangeaddress", "")
84  + HelpExampleRpc("getrawchangeaddress", "")
85  },
86  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
87 {
88  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
89  if (!pwallet) return UniValue::VNULL;
90 
91  LOCK(pwallet->cs_wallet);
92 
93  if (!pwallet->CanGetAddresses(true)) {
94  throw JSONRPCError(RPC_WALLET_ERROR, "Error: This wallet has no available keys");
95  }
96 
97  OutputType output_type = pwallet->m_default_change_type.value_or(pwallet->m_default_address_type);
98  if (!request.params[0].isNull()) {
99  std::optional<OutputType> parsed = ParseOutputType(request.params[0].get_str());
100  if (!parsed) {
101  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[0].get_str()));
102  } else if (parsed.value() == OutputType::BECH32M && pwallet->GetLegacyScriptPubKeyMan()) {
103  throw JSONRPCError(RPC_INVALID_PARAMETER, "Legacy wallets cannot provide bech32m addresses");
104  }
105  output_type = parsed.value();
106  }
107 
108  auto op_dest = pwallet->GetNewChangeDestination(output_type);
109  if (!op_dest) {
111  }
112  return EncodeDestination(*op_dest);
113 },
114  };
115 }
116 
117 
119 {
120  return RPCHelpMan{"setlabel",
121  "\nSets the label associated with the given address.\n",
122  {
123  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to be associated with a label."},
124  {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label to assign to the address."},
125  },
127  RPCExamples{
128  HelpExampleCli("setlabel", "\"" + EXAMPLE_ADDRESS[0] + "\" \"tabby\"")
129  + HelpExampleRpc("setlabel", "\"" + EXAMPLE_ADDRESS[0] + "\", \"tabby\"")
130  },
131  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
132 {
133  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
134  if (!pwallet) return UniValue::VNULL;
135 
136  LOCK(pwallet->cs_wallet);
137 
138  CTxDestination dest = DecodeDestination(request.params[0].get_str());
139  if (!IsValidDestination(dest)) {
140  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
141  }
142 
143  std::string label = LabelFromValue(request.params[1]);
144 
145  if (pwallet->IsMine(dest)) {
146  pwallet->SetAddressBook(dest, label, "receive");
147  } else {
148  pwallet->SetAddressBook(dest, label, "send");
149  }
150 
151  return UniValue::VNULL;
152 },
153  };
154 }
155 
157 {
158  return RPCHelpMan{"listaddressgroupings",
159  "\nLists groups of addresses which have had their common ownership\n"
160  "made public by common use as inputs or as the resulting change\n"
161  "in past transactions\n",
162  {},
163  RPCResult{
164  RPCResult::Type::ARR, "", "",
165  {
166  {RPCResult::Type::ARR, "", "",
167  {
169  {
170  {RPCResult::Type::STR, "address", "The bitcoin address"},
171  {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT},
172  {RPCResult::Type::STR, "label", /*optional=*/true, "The label"},
173  }},
174  }},
175  }
176  },
177  RPCExamples{
178  HelpExampleCli("listaddressgroupings", "")
179  + HelpExampleRpc("listaddressgroupings", "")
180  },
181  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
182 {
183  const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
184  if (!pwallet) return UniValue::VNULL;
185 
186  // Make sure the results are valid at least up to the most recent block
187  // the user could have gotten from another RPC command prior to now
188  pwallet->BlockUntilSyncedToCurrentChain();
189 
190  LOCK(pwallet->cs_wallet);
191 
192  UniValue jsonGroupings(UniValue::VARR);
193  std::map<CTxDestination, CAmount> balances = GetAddressBalances(*pwallet);
194  for (const std::set<CTxDestination>& grouping : GetAddressGroupings(*pwallet)) {
195  UniValue jsonGrouping(UniValue::VARR);
196  for (const CTxDestination& address : grouping)
197  {
198  UniValue addressInfo(UniValue::VARR);
199  addressInfo.push_back(EncodeDestination(address));
200  addressInfo.push_back(ValueFromAmount(balances[address]));
201  {
202  const auto* address_book_entry = pwallet->FindAddressBookEntry(address);
203  if (address_book_entry) {
204  addressInfo.push_back(address_book_entry->GetLabel());
205  }
206  }
207  jsonGrouping.push_back(addressInfo);
208  }
209  jsonGroupings.push_back(jsonGrouping);
210  }
211  return jsonGroupings;
212 },
213  };
214 }
215 
217 {
218  return RPCHelpMan{"addmultisigaddress",
219  "\nAdd an nrequired-to-sign multisignature address to the wallet. Requires a new wallet backup.\n"
220  "Each key is a Bitcoin address or hex-encoded public key.\n"
221  "This functionality is only intended for use with non-watchonly addresses.\n"
222  "See `importaddress` for watchonly p2sh address support.\n"
223  "If 'label' is specified, assign address to that label.\n",
224  {
225  {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys or addresses."},
226  {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The bitcoin addresses or hex-encoded public keys",
227  {
228  {"key", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "bitcoin address or hex-encoded public key"},
229  },
230  },
231  {"label", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A label to assign the addresses to."},
232  {"address_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -addresstype"}, "The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\"."},
233  },
234  RPCResult{
235  RPCResult::Type::OBJ, "", "",
236  {
237  {RPCResult::Type::STR, "address", "The value of the new multisig address"},
238  {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script"},
239  {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig"},
240  {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Any warnings resulting from the creation of this multisig",
241  {
242  {RPCResult::Type::STR, "", ""},
243  }},
244  }
245  },
246  RPCExamples{
247  "\nAdd a multisig address from 2 addresses\n"
248  + HelpExampleCli("addmultisigaddress", "2 \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") +
249  "\nAs a JSON-RPC call\n"
250  + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"")
251  },
252  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
253 {
254  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
255  if (!pwallet) return UniValue::VNULL;
256 
258 
259  LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);
260 
261  std::string label;
262  if (!request.params[2].isNull())
263  label = LabelFromValue(request.params[2]);
264 
265  int required = request.params[0].getInt<int>();
266 
267  // Get the public keys
268  const UniValue& keys_or_addrs = request.params[1].get_array();
269  std::vector<CPubKey> pubkeys;
270  for (unsigned int i = 0; i < keys_or_addrs.size(); ++i) {
271  if (IsHex(keys_or_addrs[i].get_str()) && (keys_or_addrs[i].get_str().length() == 66 || keys_or_addrs[i].get_str().length() == 130)) {
272  pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str()));
273  } else {
274  pubkeys.push_back(AddrToPubKey(spk_man, keys_or_addrs[i].get_str()));
275  }
276  }
277 
278  OutputType output_type = pwallet->m_default_address_type;
279  if (!request.params[3].isNull()) {
280  std::optional<OutputType> parsed = ParseOutputType(request.params[3].get_str());
281  if (!parsed) {
282  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[3].get_str()));
283  } else if (parsed.value() == OutputType::BECH32M) {
284  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m multisig addresses cannot be created with legacy wallets");
285  }
286  output_type = parsed.value();
287  }
288 
289  // Construct using pay-to-script-hash:
290  CScript inner;
291  CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, output_type, spk_man, inner);
292  pwallet->SetAddressBook(dest, label, "send");
293 
294  // Make the descriptor
295  std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), spk_man);
296 
297  UniValue result(UniValue::VOBJ);
298  result.pushKV("address", EncodeDestination(dest));
299  result.pushKV("redeemScript", HexStr(inner));
300  result.pushKV("descriptor", descriptor->ToString());
301 
302  UniValue warnings(UniValue::VARR);
303  if (descriptor->GetOutputType() != output_type) {
304  // Only warns if the user has explicitly chosen an address type we cannot generate
305  warnings.push_back("Unable to make chosen address type, please ensure no uncompressed public keys are present.");
306  }
307  if (!warnings.empty()) result.pushKV("warnings", warnings);
308 
309  return result;
310 },
311  };
312 }
313 
315 {
316  return RPCHelpMan{"keypoolrefill",
317  "\nFills the keypool."+
319  {
320  {"newsize", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%u, or as set by -keypool", DEFAULT_KEYPOOL_SIZE)}, "The new keypool size"},
321  },
323  RPCExamples{
324  HelpExampleCli("keypoolrefill", "")
325  + HelpExampleRpc("keypoolrefill", "")
326  },
327  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
328 {
329  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
330  if (!pwallet) return UniValue::VNULL;
331 
332  if (pwallet->IsLegacy() && pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
333  throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
334  }
335 
336  LOCK(pwallet->cs_wallet);
337 
338  // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
339  unsigned int kpSize = 0;
340  if (!request.params[0].isNull()) {
341  if (request.params[0].getInt<int>() < 0)
342  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
343  kpSize = (unsigned int)request.params[0].getInt<int>();
344  }
345 
346  EnsureWalletIsUnlocked(*pwallet);
347  pwallet->TopUpKeyPool(kpSize);
348 
349  if (pwallet->GetKeyPoolSize() < kpSize) {
350  throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
351  }
352 
353  return UniValue::VNULL;
354 },
355  };
356 }
357 
359 {
360  return RPCHelpMan{"newkeypool",
361  "\nEntirely clears and refills the keypool.\n"
362  "WARNING: On non-HD wallets, this will require a new backup immediately, to include the new keys.\n"
363  "When restoring a backup of an HD wallet created before the newkeypool command is run, funds received to\n"
364  "new addresses may not appear automatically. They have not been lost, but the wallet may not find them.\n"
365  "This can be fixed by running the newkeypool command on the backup and then rescanning, so the wallet\n"
366  "re-generates the required keys." +
368  {},
370  RPCExamples{
371  HelpExampleCli("newkeypool", "")
372  + HelpExampleRpc("newkeypool", "")
373  },
374  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
375 {
376  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
377  if (!pwallet) return UniValue::VNULL;
378 
379  LOCK(pwallet->cs_wallet);
380 
381  LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet, true);
382  spk_man.NewKeyPool();
383 
384  return UniValue::VNULL;
385 },
386  };
387 }
388 
389 
391 {
392 public:
393  const SigningProvider * const provider;
394 
395  void ProcessSubScript(const CScript& subscript, UniValue& obj) const
396  {
397  // Always present: script type and redeemscript
398  std::vector<std::vector<unsigned char>> solutions_data;
399  TxoutType which_type = Solver(subscript, solutions_data);
400  obj.pushKV("script", GetTxnOutputType(which_type));
401  obj.pushKV("hex", HexStr(subscript));
402 
403  CTxDestination embedded;
404  if (ExtractDestination(subscript, embedded)) {
405  // Only when the script corresponds to an address.
406  UniValue subobj(UniValue::VOBJ);
407  UniValue detail = DescribeAddress(embedded);
408  subobj.pushKVs(detail);
409  UniValue wallet_detail = std::visit(*this, embedded);
410  subobj.pushKVs(wallet_detail);
411  subobj.pushKV("address", EncodeDestination(embedded));
412  subobj.pushKV("scriptPubKey", HexStr(subscript));
413  // Always report the pubkey at the top level, so that `getnewaddress()['pubkey']` always works.
414  if (subobj.exists("pubkey")) obj.pushKV("pubkey", subobj["pubkey"]);
415  obj.pushKV("embedded", std::move(subobj));
416  } else if (which_type == TxoutType::MULTISIG) {
417  // Also report some information on multisig scripts (which do not have a corresponding address).
418  obj.pushKV("sigsrequired", solutions_data[0][0]);
419  UniValue pubkeys(UniValue::VARR);
420  for (size_t i = 1; i < solutions_data.size() - 1; ++i) {
421  CPubKey key(solutions_data[i].begin(), solutions_data[i].end());
422  pubkeys.push_back(HexStr(key));
423  }
424  obj.pushKV("pubkeys", std::move(pubkeys));
425  }
426  }
427 
428  explicit DescribeWalletAddressVisitor(const SigningProvider* _provider) : provider(_provider) {}
429 
430  UniValue operator()(const CNoDestination& dest) const { return UniValue(UniValue::VOBJ); }
431 
432  UniValue operator()(const PKHash& pkhash) const
433  {
434  CKeyID keyID{ToKeyID(pkhash)};
436  CPubKey vchPubKey;
437  if (provider && provider->GetPubKey(keyID, vchPubKey)) {
438  obj.pushKV("pubkey", HexStr(vchPubKey));
439  obj.pushKV("iscompressed", vchPubKey.IsCompressed());
440  }
441  return obj;
442  }
443 
444  UniValue operator()(const ScriptHash& scripthash) const
445  {
446  CScriptID scriptID(scripthash);
448  CScript subscript;
449  if (provider && provider->GetCScript(scriptID, subscript)) {
450  ProcessSubScript(subscript, obj);
451  }
452  return obj;
453  }
454 
456  {
458  CPubKey pubkey;
459  if (provider && provider->GetPubKey(ToKeyID(id), pubkey)) {
460  obj.pushKV("pubkey", HexStr(pubkey));
461  }
462  return obj;
463  }
464 
466  {
468  CScript subscript;
469  CRIPEMD160 hasher;
470  uint160 hash;
471  hasher.Write(id.begin(), 32).Finalize(hash.begin());
472  if (provider && provider->GetCScript(CScriptID(hash), subscript)) {
473  ProcessSubScript(subscript, obj);
474  }
475  return obj;
476  }
477 
480 };
481 
483 {
485  UniValue detail = DescribeAddress(dest);
486  CScript script = GetScriptForDestination(dest);
487  std::unique_ptr<SigningProvider> provider = nullptr;
488  provider = wallet.GetSolvingProvider(script);
489  ret.pushKVs(detail);
490  ret.pushKVs(std::visit(DescribeWalletAddressVisitor(provider.get()), dest));
491  return ret;
492 }
493 
495 {
496  return RPCHelpMan{"getaddressinfo",
497  "\nReturn information about the given bitcoin address.\n"
498  "Some of the information will only be present if the address is in the active wallet.\n",
499  {
500  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address for which to get information."},
501  },
502  RPCResult{
503  RPCResult::Type::OBJ, "", "",
504  {
505  {RPCResult::Type::STR, "address", "The bitcoin address validated."},
506  {RPCResult::Type::STR_HEX, "scriptPubKey", "The hex-encoded scriptPubKey generated by the address."},
507  {RPCResult::Type::BOOL, "ismine", "If the address is yours."},
508  {RPCResult::Type::BOOL, "iswatchonly", "If the address is watchonly."},
509  {RPCResult::Type::BOOL, "solvable", "If we know how to spend coins sent to this address, ignoring the possible lack of private keys."},
510  {RPCResult::Type::STR, "desc", /*optional=*/true, "A descriptor for spending coins sent to this address (only when solvable)."},
511  {RPCResult::Type::STR, "parent_desc", /*optional=*/true, "The descriptor used to derive this address if this is a descriptor wallet"},
512  {RPCResult::Type::BOOL, "isscript", "If the key is a script."},
513  {RPCResult::Type::BOOL, "ischange", "If the address was used for change output."},
514  {RPCResult::Type::BOOL, "iswitness", "If the address is a witness address."},
515  {RPCResult::Type::NUM, "witness_version", /*optional=*/true, "The version number of the witness program."},
516  {RPCResult::Type::STR_HEX, "witness_program", /*optional=*/true, "The hex value of the witness program."},
517  {RPCResult::Type::STR, "script", /*optional=*/true, "The output script type. Only if isscript is true and the redeemscript is known. Possible\n"
518  "types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash,\n"
519  "witness_v0_scripthash, witness_unknown."},
520  {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The redeemscript for the p2sh address."},
521  {RPCResult::Type::ARR, "pubkeys", /*optional=*/true, "Array of pubkeys associated with the known redeemscript (only if script is multisig).",
522  {
523  {RPCResult::Type::STR, "pubkey", ""},
524  }},
525  {RPCResult::Type::NUM, "sigsrequired", /*optional=*/true, "The number of signatures required to spend multisig output (only if script is multisig)."},
526  {RPCResult::Type::STR_HEX, "pubkey", /*optional=*/true, "The hex value of the raw public key for single-key addresses (possibly embedded in P2SH or P2WSH)."},
527  {RPCResult::Type::OBJ, "embedded", /*optional=*/true, "Information about the address embedded in P2SH or P2WSH, if relevant and known.",
528  {
529  {RPCResult::Type::ELISION, "", "Includes all getaddressinfo output fields for the embedded address, excluding metadata (timestamp, hdkeypath, hdseedid)\n"
530  "and relation to the wallet (ismine, iswatchonly)."},
531  }},
532  {RPCResult::Type::BOOL, "iscompressed", /*optional=*/true, "If the pubkey is compressed."},
533  {RPCResult::Type::NUM_TIME, "timestamp", /*optional=*/true, "The creation time of the key, if available, expressed in " + UNIX_EPOCH_TIME + "."},
534  {RPCResult::Type::STR, "hdkeypath", /*optional=*/true, "The HD keypath, if the key is HD and available."},
535  {RPCResult::Type::STR_HEX, "hdseedid", /*optional=*/true, "The Hash160 of the HD seed."},
536  {RPCResult::Type::STR_HEX, "hdmasterfingerprint", /*optional=*/true, "The fingerprint of the master key."},
537  {RPCResult::Type::ARR, "labels", "Array of labels associated with the address. Currently limited to one label but returned\n"
538  "as an array to keep the API stable if multiple labels are enabled in the future.",
539  {
540  {RPCResult::Type::STR, "label name", "Label name (defaults to \"\")."},
541  }},
542  }
543  },
544  RPCExamples{
545  HelpExampleCli("getaddressinfo", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
546  HelpExampleRpc("getaddressinfo", "\"" + EXAMPLE_ADDRESS[0] + "\"")
547  },
548  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
549 {
550  const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
551  if (!pwallet) return UniValue::VNULL;
552 
553  LOCK(pwallet->cs_wallet);
554 
555  std::string error_msg;
556  CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg);
557 
558  // Make sure the destination is valid
559  if (!IsValidDestination(dest)) {
560  // Set generic error message in case 'DecodeDestination' didn't set it
561  if (error_msg.empty()) error_msg = "Invalid address";
562 
563  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error_msg);
564  }
565 
567 
568  std::string currentAddress = EncodeDestination(dest);
569  ret.pushKV("address", currentAddress);
570 
571  CScript scriptPubKey = GetScriptForDestination(dest);
572  ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
573 
574  std::unique_ptr<SigningProvider> provider = pwallet->GetSolvingProvider(scriptPubKey);
575 
576  isminetype mine = pwallet->IsMine(dest);
577  ret.pushKV("ismine", bool(mine & ISMINE_SPENDABLE));
578 
579  if (provider) {
580  auto inferred = InferDescriptor(scriptPubKey, *provider);
581  bool solvable = inferred->IsSolvable();
582  ret.pushKV("solvable", solvable);
583  if (solvable) {
584  ret.pushKV("desc", inferred->ToString());
585  }
586  } else {
587  ret.pushKV("solvable", false);
588  }
589 
590  const auto& spk_mans = pwallet->GetScriptPubKeyMans(scriptPubKey);
591  // In most cases there is only one matching ScriptPubKey manager and we can't resolve ambiguity in a better way
592  ScriptPubKeyMan* spk_man{nullptr};
593  if (spk_mans.size()) spk_man = *spk_mans.begin();
594 
595  DescriptorScriptPubKeyMan* desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
596  if (desc_spk_man) {
597  std::string desc_str;
598  if (desc_spk_man->GetDescriptorString(desc_str, /*priv=*/false)) {
599  ret.pushKV("parent_desc", desc_str);
600  }
601  }
602 
603  ret.pushKV("iswatchonly", bool(mine & ISMINE_WATCH_ONLY));
604 
605  UniValue detail = DescribeWalletAddress(*pwallet, dest);
606  ret.pushKVs(detail);
607 
608  ret.pushKV("ischange", ScriptIsChange(*pwallet, scriptPubKey));
609 
610  if (spk_man) {
611  if (const std::unique_ptr<CKeyMetadata> meta = spk_man->GetMetadata(dest)) {
612  ret.pushKV("timestamp", meta->nCreateTime);
613  if (meta->has_key_origin) {
614  ret.pushKV("hdkeypath", WriteHDKeypath(meta->key_origin.path));
615  ret.pushKV("hdseedid", meta->hd_seed_id.GetHex());
616  ret.pushKV("hdmasterfingerprint", HexStr(meta->key_origin.fingerprint));
617  }
618  }
619  }
620 
621  // Return a `labels` array containing the label associated with the address,
622  // equivalent to the `label` field above. Currently only one label can be
623  // associated with an address, but we return an array so the API remains
624  // stable if we allow multiple labels to be associated with an address in
625  // the future.
626  UniValue labels(UniValue::VARR);
627  const auto* address_book_entry = pwallet->FindAddressBookEntry(dest);
628  if (address_book_entry) {
629  labels.push_back(address_book_entry->GetLabel());
630  }
631  ret.pushKV("labels", std::move(labels));
632 
633  return ret;
634 },
635  };
636 }
637 
639 {
640  return RPCHelpMan{"getaddressesbylabel",
641  "\nReturns the list of addresses assigned the specified label.\n",
642  {
643  {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label."},
644  },
645  RPCResult{
646  RPCResult::Type::OBJ_DYN, "", "json object with addresses as keys",
647  {
648  {RPCResult::Type::OBJ, "address", "json object with information about address",
649  {
650  {RPCResult::Type::STR, "purpose", "Purpose of address (\"send\" for sending address, \"receive\" for receiving address)"},
651  }},
652  }
653  },
654  RPCExamples{
655  HelpExampleCli("getaddressesbylabel", "\"tabby\"")
656  + HelpExampleRpc("getaddressesbylabel", "\"tabby\"")
657  },
658  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
659 {
660  const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
661  if (!pwallet) return UniValue::VNULL;
662 
663  LOCK(pwallet->cs_wallet);
664 
665  std::string label = LabelFromValue(request.params[0]);
666 
667  // Find all addresses that have the given label
669  std::set<std::string> addresses;
670  pwallet->ForEachAddrBookEntry([&](const CTxDestination& _dest, const std::string& _label, const std::string& _purpose, bool _is_change) {
671  if (_is_change) return;
672  if (_label == label) {
673  std::string address = EncodeDestination(_dest);
674  // CWallet::m_address_book is not expected to contain duplicate
675  // address strings, but build a separate set as a precaution just in
676  // case it does.
677  bool unique = addresses.emplace(address).second;
678  CHECK_NONFATAL(unique);
679  // UniValue::pushKV checks if the key exists in O(N)
680  // and since duplicate addresses are unexpected (checked with
681  // std::set in O(log(N))), UniValue::__pushKV is used instead,
682  // which currently is O(1).
683  UniValue value(UniValue::VOBJ);
684  value.pushKV("purpose", _purpose);
685  ret.__pushKV(address, value);
686  }
687  });
688 
689  if (ret.empty()) {
690  throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, std::string("No addresses with label " + label));
691  }
692 
693  return ret;
694 },
695  };
696 }
697 
699 {
700  return RPCHelpMan{"listlabels",
701  "\nReturns the list of all labels, or labels that are assigned to addresses with a specific purpose.\n",
702  {
703  {"purpose", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "Address purpose to list labels for ('send','receive'). An empty string is the same as not providing this argument."},
704  },
705  RPCResult{
706  RPCResult::Type::ARR, "", "",
707  {
708  {RPCResult::Type::STR, "label", "Label name"},
709  }
710  },
711  RPCExamples{
712  "\nList all labels\n"
713  + HelpExampleCli("listlabels", "") +
714  "\nList labels that have receiving addresses\n"
715  + HelpExampleCli("listlabels", "receive") +
716  "\nList labels that have sending addresses\n"
717  + HelpExampleCli("listlabels", "send") +
718  "\nAs a JSON-RPC call\n"
719  + HelpExampleRpc("listlabels", "receive")
720  },
721  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
722 {
723  const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
724  if (!pwallet) return UniValue::VNULL;
725 
726  LOCK(pwallet->cs_wallet);
727 
728  std::string purpose;
729  if (!request.params[0].isNull()) {
730  purpose = request.params[0].get_str();
731  }
732 
733  // Add to a set to sort by label name, then insert into Univalue array
734  std::set<std::string> label_set = pwallet->ListAddrBookLabels(purpose);
735 
737  for (const std::string& name : label_set) {
738  ret.push_back(name);
739  }
740 
741  return ret;
742 },
743  };
744 }
745 
746 
747 #ifdef ENABLE_EXTERNAL_SIGNER
749 {
750  return RPCHelpMan{
751  "walletdisplayaddress",
752  "Display address on an external signer for verification.",
753  {
754  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "bitcoin address to display"},
755  },
756  RPCResult{
757  RPCResult::Type::OBJ,"","",
758  {
759  {RPCResult::Type::STR, "address", "The address as confirmed by the signer"},
760  }
761  },
762  RPCExamples{""},
763  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
764  {
765  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
766  if (!wallet) return UniValue::VNULL;
767  CWallet* const pwallet = wallet.get();
768 
769  LOCK(pwallet->cs_wallet);
770 
771  CTxDestination dest = DecodeDestination(request.params[0].get_str());
772 
773  // Make sure the destination is valid
774  if (!IsValidDestination(dest)) {
775  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
776  }
777 
778  if (!pwallet->DisplayAddress(dest)) {
779  throw JSONRPCError(RPC_MISC_ERROR, "Failed to display address");
780  }
781 
782  UniValue result(UniValue::VOBJ);
783  result.pushKV("address", request.params[0].get_str());
784  return result;
785  }
786  };
787 }
788 #endif // ENABLE_EXTERNAL_SIGNER
789 } // namespace wallet
void push_back(UniValue val)
Definition: univalue.cpp:104
int ret
static UniValue DescribeWalletAddress(const CWallet &wallet, const CTxDestination &dest)
Definition: addresses.cpp:482
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:237
Keypool ran out, call keypoolrefill first.
Definition: protocol.h:74
UniValue operator()(const ScriptHash &scripthash) const
Definition: addresses.cpp:444
Required arg.
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
std::map< CTxDestination, CAmount > GetAddressBalances(const CWallet &wallet)
Definition: receive.cpp:322
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
RecursiveMutex cs_KeyStore
void pushKVs(UniValue obj)
Definition: univalue.cpp:137
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:47
bool IsHex(std::string_view str)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:356
static const unsigned int DEFAULT_KEYPOOL_SIZE
Default for -keypool.
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:202
RecursiveMutex cs_wallet
Main wallet lock.
Definition: wallet.h:358
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:335
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:21
const UniValue & get_array() const
RPCHelpMan getaddressinfo()
Definition: addresses.cpp:494
Int getInt() const
Definition: univalue.h:137
unsigned char * begin()
Definition: uint256.h:61
UniValue operator()(const WitnessV1Taproot &id) const
Definition: addresses.cpp:478
OutputType
Definition: outputtype.h:17
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
void ProcessSubScript(const CScript &subscript, UniValue &obj) const
Definition: addresses.cpp:395
RPCHelpMan walletdisplayaddress()
Definition: addresses.cpp:748
bool DisplayAddress(const CTxDestination &dest) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Display address on an external signer.
Definition: wallet.cpp:2514
CTxDestination AddAndGetMultisigDestination(const int required, const std::vector< CPubKey > &pubkeys, OutputType type, FillableSigningProvider &keystore, CScript &script_out)
Definition: util.cpp:236
#define LOCK2(cs1, cs2)
Definition: sync.h:262
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:184
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:56
Special string with only hex chars.
UniValue operator()(const WitnessUnknown &id) const
Definition: addresses.cpp:479
std::string LabelFromValue(const UniValue &value)
Definition: util.cpp:117
RPCHelpMan setlabel()
Definition: addresses.cpp:118
virtual bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string GetTxnOutputType(TxoutType t)
Get the name of a TxoutType as a string.
Definition: standard.cpp:46
const SigningProvider *const provider
Definition: addresses.cpp:393
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:117
#define LOCK(cs)
Definition: sync.h:261
const char * name
Definition: rest.cpp:46
bool exists(const std::string &key) const
Definition: univalue.h:72
TxoutType
Definition: standard.h:51
std::optional< OutputType > ParseOutputType(const std::string &type)
Definition: outputtype.cpp:25
Special array that has a fixed number of entries.
An encapsulated public key.
Definition: pubkey.h:33
isminetype
IsMine() return codes, which depend on ScriptPubKeyMan implementation.
Definition: ismine.h:41
RPCHelpMan newkeypool()
Definition: addresses.cpp:358
bool empty() const
Definition: univalue.h:63
const std::string CURRENCY_UNIT
Definition: feerate.h:17
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:235
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
General application defined errors.
Definition: protocol.h:39
std::string DefaultHint
Definition: util.h:169
Invalid address or key.
Definition: protocol.h:41
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:166
Definition: node.h:39
const std::string HELP_REQUIRING_PASSPHRASE
Definition: util.cpp:17
Special numeric to denote unix epoch time.
std::set< std::set< CTxDestination > > GetAddressGroupings(const CWallet &wallet)
Definition: receive.cpp:360
virtual bool GetCScript(const CScriptID &scriptid, CScript &script) const
Optional arg that is a named argument and has a default value of null.
LegacyScriptPubKeyMan & EnsureLegacyScriptPubKeyMan(CWallet &wallet, bool also_create)
Definition: util.cpp:96
bool ScriptIsChange(const CWallet &wallet, const CScript &script)
Definition: receive.cpp:51
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
Optional argument with default value omitted because they are implicitly clear.
UniValue operator()(const PKHash &pkhash) const
Definition: addresses.cpp:432
RPCHelpMan listlabels()
Definition: addresses.cpp:698
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible...
An interface to be implemented by keystores that support signing.
UniValue operator()(const CNoDestination &dest) const
Definition: addresses.cpp:430
Special string to represent a floating point amount.
DescribeWalletAddressVisitor(const SigningProvider *_provider)
Definition: addresses.cpp:428
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
bool GetDescriptorString(std::string &out, const bool priv) const
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:410
std::string WriteHDKeypath(const std::vector< uint32_t > &keypath)
Write HD keypaths as strings.
Definition: bip32.cpp:64
RPCHelpMan getaddressesbylabel()
Definition: addresses.cpp:638
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:23
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:168
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:26
160-bit opaque blob.
Definition: uint256.h:108
void EnsureWalletIsUnlocked(const CWallet &wallet)
Definition: util.cpp:79
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:78
RPCHelpMan keypoolrefill()
Definition: addresses.cpp:314
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:26
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:276
Wallet errors.
Definition: protocol.h:71
RPCHelpMan listaddressgroupings()
Definition: addresses.cpp:156
UniValue operator()(const WitnessV0KeyHash &id) const
Definition: addresses.cpp:455
Special dictionary with keys that are not literals.
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: ripemd160.cpp:273
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:281
RPCHelpMan getnewaddress()
Definition: addresses.cpp:17
UniValue operator()(const WitnessV0ScriptHash &id) const
Definition: addresses.cpp:465
CPubKey AddrToPubKey(const FillableSigningProvider &keystore, const std::string &addr_in)
Definition: util.cpp:215
Invalid label name.
Definition: protocol.h:73
RPCHelpMan getrawchangeaddress()
Definition: addresses.cpp:71
std::shared_ptr< CWallet > GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: util.cpp:55
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency...
Definition: util.cpp:20
RPCHelpMan addmultisigaddress()
Definition: addresses.cpp:216
A hasher class for RIPEMD-160.
Definition: ripemd160.h:12
CKeyID ToKeyID(const PKHash &key_hash)
Definition: standard.cpp:31
Special type to denote elision (...)
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:198