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