LCOV - code coverage report
Current view: top level - src/wallet/rpc - addresses.cpp (source / functions) Hit Total Coverage
Test: test_dash_coverage.info Lines: 312 458 68.1 %
Date: 2026-06-25 07:23:51 Functions: 24 33 72.7 %

          Line data    Source code
       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 {
      17        6196 : RPCHelpMan getnewaddress()
      18             : {
      19       12392 :     return RPCHelpMan{"getnewaddress",
      20        6196 :                 "\nReturns a new Dash 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       12392 :                 {
      24        6196 :                     {"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             :                 },
      26        6196 :                 RPCResult{
      27        6196 :                     RPCResult::Type::STR, "address", "The new Dash address"
      28             :                 },
      29        6196 :                 RPCExamples{
      30        6196 :                     HelpExampleCli("getnewaddress", "")
      31        6196 :             + HelpExampleRpc("getnewaddress", "")
      32             :                 },
      33       12384 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
      34             : {
      35        6188 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
      36        6188 :     if (!pwallet) return UniValue::VNULL;
      37             : 
      38        6188 :     LOCK(pwallet->cs_wallet);
      39             : 
      40        6188 :     if (!pwallet->CanGetAddresses()) {
      41           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error: This wallet has no available keys");
      42             :     }
      43             : 
      44             :     // Parse the label first so we don't generate a key if there's an error
      45        6188 :     std::string label;
      46        6188 :     if (!request.params[0].isNull())
      47           2 :         label = LabelFromValue(request.params[0]);
      48             : 
      49        6188 :     auto op_dest = pwallet->GetNewDestination(label);
      50        6188 :     if (!op_dest) {
      51           0 :         throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, util::ErrorString(op_dest).original);
      52             :     }
      53        6188 :     return EncodeDestination(*op_dest);
      54        6188 : },
      55             :     };
      56           0 : }
      57             : 
      58           9 : RPCHelpMan getrawchangeaddress()
      59             : {
      60          18 :     return RPCHelpMan{"getrawchangeaddress",
      61           9 :                 "\nReturns a new Dash address, for receiving change.\n"
      62             :                 "This is for use with raw transactions, NOT normal use.\n",
      63           9 :                 {},
      64           9 :                 RPCResult{
      65           9 :                     RPCResult::Type::STR, "address", "The address"
      66             :                 },
      67           9 :                 RPCExamples{
      68           9 :                     HelpExampleCli("getrawchangeaddress", "")
      69           9 :             + HelpExampleRpc("getrawchangeaddress", "")
      70             :                 },
      71          10 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
      72             : {
      73           1 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
      74           1 :     if (!pwallet) return UniValue::VNULL;
      75             : 
      76           1 :     LOCK(pwallet->cs_wallet);
      77             : 
      78           1 :     if (!pwallet->CanGetAddresses(true)) {
      79           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error: This wallet has no available keys");
      80             :     }
      81             : 
      82           1 :     auto op_dest = pwallet->GetNewChangeDestination();
      83           1 :     if (!op_dest) {
      84           0 :         throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, util::ErrorString(op_dest).original);
      85             :     }
      86           1 :     return EncodeDestination(*op_dest);
      87           1 : },
      88             :     };
      89           0 : }
      90             : 
      91           8 : RPCHelpMan setlabel()
      92             : {
      93          16 :     return RPCHelpMan{"setlabel",
      94           8 :                 "\nSets the label associated with the given address.\n",
      95          24 :                 {
      96           8 :                     {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The Dash address to be associated with a label."},
      97           8 :                     {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label to assign to the address."},
      98             :                 },
      99           8 :                 RPCResult{RPCResult::Type::NONE, "", ""},
     100           8 :                 RPCExamples{
     101           8 :                     HelpExampleCli("setlabel", "\"" + EXAMPLE_ADDRESS[0] + "\" \"tabby\"")
     102           8 :             + HelpExampleRpc("setlabel", "\"" + EXAMPLE_ADDRESS[0] + "\", \"tabby\"")
     103             :                 },
     104           8 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     105             : {
     106           0 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     107           0 :     if (!pwallet) return UniValue::VNULL;
     108             : 
     109           0 :     LOCK(pwallet->cs_wallet);
     110             : 
     111           0 :     CTxDestination dest = DecodeDestination(request.params[0].get_str());
     112           0 :     if (!IsValidDestination(dest)) {
     113           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Dash address");
     114             :     }
     115             : 
     116           0 :     std::string label = LabelFromValue(request.params[1]);
     117             : 
     118           0 :     if (pwallet->IsMine(dest)) {
     119           0 :         pwallet->SetAddressBook(dest, label, "receive");
     120           0 :     } else {
     121           0 :         pwallet->SetAddressBook(dest, label, "send");
     122             :     }
     123             : 
     124           0 :     return UniValue::VNULL;
     125           0 : },
     126             :     };
     127           0 : }
     128             : 
     129           8 : RPCHelpMan listaddressgroupings()
     130             : {
     131          16 :     return RPCHelpMan{"listaddressgroupings",
     132           8 :                 "\nLists groups of addresses which have had their common ownership\n"
     133             :                 "made public by common use as inputs or as the resulting change\n"
     134             :                 "in past transactions\n",
     135           8 :                 {},
     136           8 :                 RPCResult{
     137           8 :                     RPCResult::Type::ARR, "", "",
     138          16 :                     {
     139          16 :                         {RPCResult::Type::ARR, "", "",
     140          16 :                         {
     141          16 :                             {RPCResult::Type::ARR_FIXED, "", "",
     142          32 :                             {
     143           8 :                                 {RPCResult::Type::STR, "address", "The Dash address"},
     144           8 :                                 {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT},
     145           8 :                                 {RPCResult::Type::STR, "label", /*optional=*/true, "The label"},
     146             :                             }},
     147             :                         }},
     148             :                     }
     149             :                 },
     150           8 :                 RPCExamples{
     151           8 :                     HelpExampleCli("listaddressgroupings", "")
     152           8 :             + HelpExampleRpc("listaddressgroupings", "")
     153             :                 },
     154           8 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     155             : {
     156           0 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
     157           0 :     if (!pwallet) return UniValue::VNULL;
     158             : 
     159             :     // Make sure the results are valid at least up to the most recent block
     160             :     // the user could have gotten from another RPC command prior to now
     161           0 :     pwallet->BlockUntilSyncedToCurrentChain();
     162             : 
     163           0 :     LOCK(pwallet->cs_wallet);
     164             : 
     165           0 :     UniValue jsonGroupings(UniValue::VARR);
     166           0 :     std::map<CTxDestination, CAmount> balances = GetAddressBalances(*pwallet);
     167           0 :     for (const std::set<CTxDestination>& grouping : GetAddressGroupings(*pwallet)) {
     168           0 :         UniValue jsonGrouping(UniValue::VARR);
     169           0 :         for (const CTxDestination& address : grouping)
     170             :         {
     171           0 :             UniValue addressInfo(UniValue::VARR);
     172           0 :             addressInfo.push_back(EncodeDestination(address));
     173           0 :             addressInfo.push_back(ValueFromAmount(balances[address]));
     174             :             {
     175           0 :                 const auto* address_book_entry = pwallet->FindAddressBookEntry(address);
     176           0 :                 if (address_book_entry) {
     177           0 :                     addressInfo.push_back(address_book_entry->GetLabel());
     178           0 :                 }
     179             :             }
     180           0 :             jsonGrouping.push_back(addressInfo);
     181           0 :         }
     182           0 :         jsonGroupings.push_back(jsonGrouping);
     183           0 :     }
     184           0 :     return jsonGroupings;
     185           0 : },
     186             :     };
     187           0 : }
     188             : 
     189           9 : RPCHelpMan addmultisigaddress()
     190             : {
     191          18 :     return RPCHelpMan{"addmultisigaddress",
     192           9 :                 "\nAdd an nrequired-to-sign multisignature address to the wallet. Requires a new wallet backup.\n"
     193             :                 "Each key is a Dash address or hex-encoded public key.\n"
     194             :                 "This functionality is only intended for use with non-watchonly addresses.\n"
     195             :                 "See `importaddress` for watchonly p2sh address support.\n"
     196             :                 "If 'label' is specified, assign address to that label.\n"
     197             :                 "Note: This command is only compatible with legacy wallets.\n",
     198          36 :                 {
     199           9 :                     {"nrequired", RPCArg::Type::NUM, RPCArg::Optional::NO, "The number of required signatures out of the n keys or addresses."},
     200          18 :                     {"keys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The Dash addresses or hex-encoded public keys",
     201          18 :                         {
     202           9 :                             {"key", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Dash address or hex-encoded public key"},
     203             :                         },
     204             :                         },
     205           9 :                     {"label", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A label to assign the addresses to."},
     206             :                 },
     207           9 :                 RPCResult{
     208           9 :                     RPCResult::Type::OBJ, "", "",
     209          36 :                     {
     210           9 :                         {RPCResult::Type::STR, "address", "The value of the new multisig address"},
     211           9 :                         {RPCResult::Type::STR_HEX, "redeemScript", "The string value of the hex-encoded redemption script"},
     212           9 :                         {RPCResult::Type::STR, "descriptor", "The descriptor for this multisig."},
     213             :                     }
     214             :                 },
     215           9 :                 RPCExamples{
     216             :             "\nAdd a multisig address from 2 addresses\n"
     217           9 :             + HelpExampleCli("addmultisigaddress", "2 \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") +
     218             :             "\nAs a JSON-RPC call\n"
     219           9 :             + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"")
     220             :                 },
     221          10 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     222             : {
     223           1 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     224           1 :     if (!pwallet) return UniValue::VNULL;
     225             : 
     226           1 :     LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet);
     227             : 
     228           1 :     LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore);
     229             : 
     230           1 :     std::string label;
     231           1 :     if (!request.params[2].isNull())
     232           0 :         label = LabelFromValue(request.params[2]);
     233             : 
     234           1 :     int required = request.params[0].getInt<int>();
     235             : 
     236             :     // Get the public keys
     237           1 :     const UniValue& keys_or_addrs = request.params[1].get_array();
     238           1 :     std::vector<CPubKey> pubkeys;
     239           3 :     for (unsigned int i = 0; i < keys_or_addrs.size(); ++i) {
     240           2 :         if (IsHex(keys_or_addrs[i].get_str()) && (keys_or_addrs[i].get_str().length() == 66 || keys_or_addrs[i].get_str().length() == 130)) {
     241           0 :             pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str()));
     242           0 :         } else {
     243           2 :             pubkeys.push_back(AddrToPubKey(spk_man, keys_or_addrs[i].get_str()));
     244             :         }
     245           2 :     }
     246             : 
     247             :     // Construct using pay-to-script-hash:
     248           1 :     CScript inner;
     249           1 :     CTxDestination dest = AddAndGetMultisigDestination(required, pubkeys, spk_man, inner);
     250           1 :     pwallet->SetAddressBook(dest, label, "send");
     251             : 
     252             :     // Make the descriptor
     253           1 :     std::unique_ptr<Descriptor> descriptor = InferDescriptor(GetScriptForDestination(dest), spk_man);
     254             : 
     255           1 :     UniValue result(UniValue::VOBJ);
     256           1 :     result.pushKV("address", EncodeDestination(dest));
     257           1 :     result.pushKV("redeemScript", HexStr(inner));
     258           1 :     result.pushKV("descriptor", descriptor->ToString());
     259           1 :     return result;
     260           1 : },
     261             :     };
     262           0 : }
     263             : 
     264           8 : RPCHelpMan keypoolrefill()
     265             : {
     266          16 :     return RPCHelpMan{"keypoolrefill",
     267           8 :         "\nFills the keypool."+
     268             :                 HELP_REQUIRING_PASSPHRASE,
     269          16 :         {
     270           8 :             {"newsize", RPCArg::Type::NUM, RPCArg::DefaultHint{strprintf("%u, or as set by -keypool", DEFAULT_KEYPOOL_SIZE)}, "The new keypool size"},
     271             :         },
     272           8 :         RPCResult{RPCResult::Type::NONE, "", ""},
     273           8 :         RPCExamples{
     274           8 :             HelpExampleCli("keypoolrefill", "")
     275           8 :     + HelpExampleRpc("keypoolrefill", "")
     276             :         },
     277           8 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     278             : {
     279           0 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     280           0 :     if (!pwallet) return UniValue::VNULL;
     281             : 
     282           0 :     if (pwallet->IsLegacy() && pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
     283           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
     284             :     }
     285             : 
     286           0 :     LOCK(pwallet->cs_wallet);
     287             : 
     288             :     // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
     289           0 :     unsigned int kpSize = 0;
     290           0 :     if (!request.params[0].isNull()) {
     291           0 :         if (request.params[0].getInt<int>() < 0)
     292           0 :             throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
     293           0 :         kpSize = (unsigned int)request.params[0].getInt<int>();
     294           0 :     }
     295             : 
     296           0 :     EnsureWalletIsUnlocked(*pwallet);
     297           0 :     pwallet->TopUpKeyPool(kpSize);
     298             : 
     299           0 :     if (pwallet->GetKeyPoolSize() < (pwallet->IsHDEnabled() ? kpSize * 2 : kpSize)) {
     300           0 :         throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
     301             :     }
     302             : 
     303           0 :     return UniValue::VNULL;
     304           0 : },
     305             :     };
     306           0 : }
     307             : 
     308           8 : RPCHelpMan newkeypool()
     309             : {
     310          16 :     return RPCHelpMan{"newkeypool",
     311             :                 "\nEntirely clears and refills the keypool.\n"
     312             :                 "WARNING: On non-HD wallets, this will require a new backup immediately, to include the new keys.\n"
     313             :                 "When restoring a backup of an HD wallet created before the newkeypool command is run, funds received to\n"
     314             :                 "new addresses may not appear automatically. They have not been lost, but the wallet may not find them.\n"
     315             :                 "This can be fixed by running the newkeypool command on the backup and then rescanning, so the wallet\n"
     316             :                 "re-generates the required keys.\n"
     317           8 :                 "Note: This command is only compatible with legacy wallets.\n" +
     318             :             HELP_REQUIRING_PASSPHRASE,
     319           8 :                 {},
     320           8 :                 RPCResult{RPCResult::Type::NONE, "", ""},
     321           8 :                 RPCExamples{
     322           8 :             HelpExampleCli("newkeypool", "")
     323           8 :             + HelpExampleRpc("newkeypool", "")
     324             :                 },
     325           8 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     326             : {
     327           0 :     std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
     328           0 :     if (!pwallet) return UniValue::VNULL;
     329             : 
     330           0 :     LOCK(pwallet->cs_wallet);
     331             : 
     332           0 :     LegacyScriptPubKeyMan& spk_man = EnsureLegacyScriptPubKeyMan(*pwallet, true);
     333           0 :     spk_man.NewKeyPool();
     334             : 
     335           0 :     return UniValue::VNULL;
     336           0 : },
     337             :     };
     338           0 : }
     339             : 
     340             : class DescribeWalletAddressVisitor
     341             : {
     342             : public:
     343             :     const SigningProvider * const provider;
     344             : 
     345           1 :     void ProcessSubScript(const CScript& subscript, UniValue& obj) const
     346             :     {
     347             :         // Always present: script type and redeemscript
     348           1 :         std::vector<std::vector<unsigned char>> solutions_data;
     349           1 :         TxoutType whichType = Solver(subscript, solutions_data);
     350           1 :         obj.pushKV("script", GetTxnOutputType(whichType));
     351           1 :         obj.pushKV("hex", HexStr(subscript));
     352             : 
     353           1 :         CTxDestination embedded;
     354           1 :         if (ExtractDestination(subscript, embedded)) {
     355             :             // Only when the script corresponds to an address.
     356           0 :             UniValue subobj(UniValue::VOBJ);
     357           0 :             UniValue detail = DescribeAddress(embedded);
     358           0 :             subobj.pushKVs(detail);
     359           0 :             UniValue wallet_detail = std::visit(*this, embedded);
     360           0 :             subobj.pushKVs(wallet_detail);
     361           0 :             subobj.pushKV("address", EncodeDestination(embedded));
     362           0 :             subobj.pushKV("scriptPubKey", HexStr(subscript));
     363             :             // Always report the pubkey at the top level, so that `getnewaddress()['pubkey']` always works.
     364           0 :             if (subobj.exists("pubkey")) obj.pushKV("pubkey", subobj["pubkey"]);
     365           0 :             obj.pushKV("embedded", std::move(subobj));
     366           1 :         } else if (whichType == TxoutType::MULTISIG) {
     367             :             // Also report some information on multisig scripts (which do not have a corresponding address).
     368           1 :             UniValue pubkeys(UniValue::VARR);
     369           1 :             UniValue addresses(UniValue::VARR);
     370           3 :             for (size_t i = 1; i < solutions_data.size() - 1; ++i) {
     371           2 :                 CPubKey pubkey(solutions_data[i]);
     372           2 :                 pubkeys.push_back(HexStr(pubkey));
     373           2 :                 addresses.push_back(EncodeDestination(PKHash(pubkey)));
     374           2 :             }
     375           1 :             obj.pushKV("pubkeys", std::move(pubkeys));
     376           1 :             obj.pushKV("addresses", std::move(addresses));
     377           1 :             obj.pushKV("sigsrequired", solutions_data[0][0]);
     378           1 :         }
     379           1 :     }
     380             : 
     381           4 :     explicit DescribeWalletAddressVisitor(const SigningProvider * const _provider) : provider(_provider) {}
     382             : 
     383           0 :     UniValue operator()(const CNoDestination &dest) const { return UniValue(UniValue::VOBJ); }
     384             : 
     385           1 :     UniValue operator()(const PKHash& pkhash) const {
     386           1 :         CKeyID keyID{ToKeyID(pkhash)};
     387           1 :         UniValue obj(UniValue::VOBJ);
     388           1 :         CPubKey vchPubKey;
     389           1 :         if (provider && provider->GetPubKey(keyID, vchPubKey)) {
     390           1 :             obj.pushKV("pubkey", HexStr(vchPubKey));
     391           1 :             obj.pushKV("iscompressed", vchPubKey.IsCompressed());
     392           1 :         }
     393           1 :         return obj;
     394           1 :     }
     395             : 
     396           1 :     UniValue operator()(const ScriptHash& scriptHash) const {
     397           1 :         CScriptID scriptID(scriptHash);
     398           1 :         UniValue obj(UniValue::VOBJ);
     399           1 :         CScript subscript;
     400           1 :         if (provider && provider->GetCScript(scriptID, subscript)) {
     401           1 :             ProcessSubScript(subscript, obj);
     402           1 :         }
     403           1 :         return obj;
     404           1 :     }
     405             : };
     406             : 
     407           2 : static UniValue DescribeWalletAddress(const CWallet& wallet, const CTxDestination& dest)
     408             : {
     409           2 :     UniValue ret(UniValue::VOBJ);
     410           2 :     UniValue detail = DescribeAddress(dest);
     411           2 :     CScript script = GetScriptForDestination(dest);
     412           2 :     std::unique_ptr<SigningProvider> provider = nullptr;
     413           2 :     provider = wallet.GetSolvingProvider(script);
     414           2 :     ret.pushKVs(detail);
     415           2 :     ret.pushKVs(std::visit(DescribeWalletAddressVisitor(provider.get()), dest));
     416           2 :     return ret;
     417           2 : }
     418             : 
     419          10 : RPCHelpMan getaddressinfo()
     420             : {
     421          20 :     return RPCHelpMan{"getaddressinfo",
     422          10 :                 "\nReturn information about the given Dash address.\n"
     423             :                 "Some of the information will only be present if the address is in the active wallet.\n",
     424          20 :                 {
     425          10 :                     {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The Dash address for which to get information."},
     426             :                 },
     427          10 :                 RPCResult{
     428          10 :                     RPCResult::Type::OBJ, "", "",
     429         240 :                     {
     430          10 :                         {RPCResult::Type::STR, "address", "The Dash address validated."},
     431          10 :                         {RPCResult::Type::STR_HEX, "scriptPubKey", "The hex-encoded scriptPubKey generated by the address."},
     432          10 :                         {RPCResult::Type::BOOL, "ismine", "If the address is yours."},
     433          10 :                         {RPCResult::Type::BOOL, "iswatchonly", "If the address is watchonly."},
     434          10 :                         {RPCResult::Type::BOOL, "solvable", "If we know how to spend coins sent to this address, ignoring the possible lack of private keys."},
     435          10 :                         {RPCResult::Type::STR, "desc", /*optional=*/true, "A descriptor for spending coins sent to this address (only when solvable)."},
     436          10 :                         {RPCResult::Type::STR, "parent_desc", /*optional=*/true, "The descriptor used to derive this address if this is a descriptor wallet"},
     437          10 :                         {RPCResult::Type::BOOL, "isscript", "If the key is a script."},
     438          10 :                         {RPCResult::Type::BOOL, "ischange", "If the address was used for change output."},
     439          10 :                         {RPCResult::Type::STR, "script", /*optional=*/true, "The output script type. Only if isscript is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata"},
     440          10 :                         {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The redeemscript for the p2sh address."},
     441          20 :                         {RPCResult::Type::ARR, "pubkeys", /*optional=*/true, "Array of pubkeys associated with the known redeemscript (only if script is multisig).",
     442          20 :                         {
     443          10 :                             {RPCResult::Type::STR, "pubkey", ""},
     444             :                         }},
     445          20 :                         {RPCResult::Type::ARR, "addresses", /*optional=*/true, "Array of addresses associated with the known redeemscript (only if script is multisig).",
     446          20 :                         {
     447          10 :                             {RPCResult::Type::STR, "address", ""},
     448             :                         }},
     449          10 :                         {RPCResult::Type::NUM, "sigsrequired", /*optional=*/true, "The number of signatures required to spend multisig output (only if script is multisig)."},
     450          10 :                         {RPCResult::Type::STR_HEX, "pubkey", /*optional=*/true, "The hex value of the raw public key, for single-key addresses."},
     451          20 :                         {RPCResult::Type::OBJ, "embedded", /*optional=*/true, "Information about the address embedded in P2SH, if relevant and known.",
     452          20 :                         {
     453          10 :                             {RPCResult::Type::ELISION, "", "Includes all getaddressinfo output fields for the embedded address, excluding metadata (timestamp, hdkeypath, hdseedid)\n"
     454             :                             "and relation to the wallet (ismine, iswatchonly)."},
     455             :                         }},
     456          10 :                         {RPCResult::Type::BOOL, "iscompressed", /*optional=*/true, "If the pubkey is compressed."},
     457          10 :                         {RPCResult::Type::NUM_TIME, "timestamp", /*optional=*/true, "The creation time of the key, if available, expressed in " + UNIX_EPOCH_TIME + "."},
     458          10 :                         {RPCResult::Type::STR_HEX, "hdchainid", /*optional=*/true, "The ID of the HD chain."},
     459          10 :                         {RPCResult::Type::STR, "hdkeypath", /*optional=*/true, "The HD keypath, if the key is HD and available."},
     460          10 :                         {RPCResult::Type::STR_HEX, "hdseedid", /*optional=*/true, "The Hash160 of the HD seed."},
     461          10 :                         {RPCResult::Type::STR_HEX, "hdmasterfingerprint", /*optional=*/true, "The fingerprint of the master key."},
     462          20 :                         {RPCResult::Type::ARR, "labels", "An array of labels associated with the address. Currently limited to one label but returned as an array to keep the API stable if multiple labels are enabled in the future.",
     463          20 :                         {
     464          10 :                             {RPCResult::Type::STR, "label name", "Label name (defaults to \"\")."},
     465             :                         }},
     466             :                     }
     467             :                 },
     468          10 :                 RPCExamples{
     469          20 :                     HelpExampleCli("getaddressinfo", EXAMPLE_ADDRESS[0]) +
     470          10 :                     HelpExampleRpc("getaddressinfo", EXAMPLE_ADDRESS[0])
     471             :                 },
     472          12 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     473             : {
     474           2 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
     475           2 :     if (!pwallet) return UniValue::VNULL;
     476             : 
     477           2 :     LOCK(pwallet->cs_wallet);
     478             : 
     479           2 :     std::string error_msg;
     480           2 :     CTxDestination dest = DecodeDestination(request.params[0].get_str(), error_msg);
     481             : 
     482             :     // Make sure the destination is valid
     483           2 :     if (!IsValidDestination(dest)) {
     484             :         // Set generic error message in case 'DecodeDestination' didn't set it
     485           0 :         if (error_msg.empty()) error_msg = "Invalid address";
     486             : 
     487           0 :         throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error_msg);
     488             :     }
     489             : 
     490           2 :     UniValue ret(UniValue::VOBJ);
     491             : 
     492           2 :     std::string currentAddress = EncodeDestination(dest);
     493           2 :     ret.pushKV("address", currentAddress);
     494             : 
     495           2 :     CScript scriptPubKey = GetScriptForDestination(dest);
     496           2 :     ret.pushKV("scriptPubKey", HexStr(scriptPubKey));
     497             : 
     498           2 :     std::unique_ptr<SigningProvider> provider = pwallet->GetSolvingProvider(scriptPubKey);
     499             : 
     500           2 :     isminetype mine = pwallet->IsMine(dest);
     501           2 :     ret.pushKV("ismine", bool(mine & ISMINE_SPENDABLE));
     502             : 
     503           4 :     bool solvable = provider && IsSolvable(*provider, scriptPubKey);
     504           2 :     ret.pushKV("solvable", solvable);
     505             : 
     506           2 :     if (solvable) {
     507           2 :         ret.pushKV("desc", InferDescriptor(scriptPubKey, *provider)->ToString());
     508           2 :     }
     509             : 
     510           2 :     const auto& spk_mans = pwallet->GetScriptPubKeyMans(scriptPubKey);
     511             :     // In most cases there is only one matching ScriptPubKey manager and we can't resolve ambiguity in a better way
     512           2 :     ScriptPubKeyMan* spk_man{nullptr};
     513           2 :     if (spk_mans.size()) spk_man = *spk_mans.begin();
     514             : 
     515           2 :     DescriptorScriptPubKeyMan* desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
     516           2 :     if (desc_spk_man) {
     517           0 :         std::string desc_str;
     518           0 :         if (desc_spk_man->GetDescriptorString(desc_str, /*priv=*/false)) {
     519           0 :             ret.pushKV("parent_desc", desc_str);
     520           0 :         }
     521           0 :     }
     522             : 
     523           2 :     ret.pushKV("iswatchonly", bool(mine & ISMINE_WATCH_ONLY));
     524             : 
     525           2 :     UniValue detail = DescribeWalletAddress(*pwallet, dest);
     526           2 :     ret.pushKVs(detail);
     527             : 
     528           2 :     ret.pushKV("ischange", ScriptIsChange(*pwallet, scriptPubKey));
     529             : 
     530           2 :     if (spk_man) {
     531           3 :         if (const std::unique_ptr<CKeyMetadata> meta = spk_man->GetMetadata(dest)) {
     532           1 :             ret.pushKV("timestamp", meta->nCreateTime);
     533           1 :             CHDChain hdChainCurrent;
     534           1 :             LegacyScriptPubKeyMan* legacy_spk_man = pwallet->GetLegacyScriptPubKeyMan();
     535           1 :             if (legacy_spk_man != nullptr) {
     536           1 :                 const PKHash *pkhash = std::get_if<PKHash>(&dest);
     537             :                 // TODO: refactor to use hd_seed_id from `meta`
     538           2 :                 if (pkhash && legacy_spk_man->HaveHDKey(ToKeyID(*pkhash), hdChainCurrent)) {
     539           0 :                     ret.pushKV("hdchainid", hdChainCurrent.GetID().GetHex());
     540           0 :                 }
     541           1 :             }
     542           1 :             if (meta->has_key_origin) {
     543             :                 // In legacy wallets hdkeypath has always used an apostrophe for
     544             :                 // hardened derivation. Perhaps some external tool depends on that.
     545           0 :                 ret.pushKV("hdkeypath", WriteHDKeypath(meta->key_origin.path, /*apostrophe=*/!desc_spk_man));
     546           0 :                 ret.pushKV("hdmasterfingerprint", HexStr(meta->key_origin.fingerprint));
     547           0 :             }
     548           1 :         }
     549           2 :     }
     550             : 
     551             :     // Return a `labels` array containing the label associated with the address,
     552             :     // equivalent to the `label` field above. Currently only one label can be
     553             :     // associated with an address, but we return an array so the API remains
     554             :     // stable if we allow multiple labels to be associated with an address in
     555             :     // the future.
     556           2 :     UniValue labels(UniValue::VARR);
     557           2 :     const auto* address_book_entry = pwallet->FindAddressBookEntry(dest);
     558           2 :     if (address_book_entry) {
     559           1 :         labels.push_back(address_book_entry->GetLabel());
     560           1 :     }
     561           2 :     ret.pushKV("labels", std::move(labels));
     562             : 
     563           2 :     return ret;
     564           2 : },
     565             :     };
     566           0 : }
     567             : 
     568           8 : RPCHelpMan getaddressesbylabel()
     569             : {
     570          16 :     return RPCHelpMan{"getaddressesbylabel",
     571           8 :                 "\nReturns the list of addresses assigned the specified label.\n",
     572          16 :                 {
     573           8 :                     {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The label."},
     574             :                 },
     575           8 :                 RPCResult{
     576           8 :                     RPCResult::Type::OBJ_DYN, "", "json object with addresses as keys",
     577          16 :                     {
     578          16 :                         {RPCResult::Type::OBJ, "address", "json object with information about address",
     579          16 :                         {
     580           8 :                             {RPCResult::Type::STR, "purpose", "Purpose of address (\"send\" for sending address, \"receive\" for receiving address)"},
     581             :                         }},
     582             :                     }
     583             :                 },
     584           8 :                 RPCExamples{
     585           8 :                     HelpExampleCli("getaddressesbylabel", "\"tabby\"")
     586           8 :             + HelpExampleRpc("getaddressesbylabel", "\"tabby\"")
     587             :                 },
     588           8 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     589             : {
     590           0 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
     591           0 :     if (!pwallet) return UniValue::VNULL;
     592             : 
     593           0 :     LOCK(pwallet->cs_wallet);
     594             : 
     595           0 :     std::string label = LabelFromValue(request.params[0]);
     596             : 
     597             :     // Find all addresses that have the given label
     598           0 :     UniValue ret(UniValue::VOBJ);
     599           0 :     std::set<std::string> addresses;
     600           0 :     pwallet->ForEachAddrBookEntry([&](const CTxDestination& _dest, const std::string& _label, const std::string& _purpose, bool _is_change) {
     601           0 :         if (_is_change) return;
     602           0 :         if (_label == label) {
     603           0 :             std::string address = EncodeDestination(_dest);
     604             :             // CWallet::m_address_book is not expected to contain duplicate
     605             :             // address strings, but build a separate set as a precaution just in
     606             :             // case it does.
     607           0 :             bool unique = addresses.emplace(address).second;
     608           0 :             CHECK_NONFATAL(unique);
     609             :             // UniValue::pushKV checks if the key exists in O(N)
     610             :             // and since duplicate addresses are unexpected (checked with
     611             :             // std::set in O(log(N))), UniValue::__pushKV is used instead,
     612             :             // which currently is O(1).
     613           0 :             UniValue value(UniValue::VOBJ);
     614           0 :             value.pushKV("purpose", _purpose);
     615           0 :             ret.__pushKV(address, value);
     616           0 :         }
     617           0 :     });
     618             : 
     619           0 :     if (ret.empty()) {
     620           0 :         throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, std::string("No addresses with label " + label));
     621             :     }
     622             : 
     623           0 :     return ret;
     624           0 : },
     625             :     };
     626           0 : }
     627             : 
     628           8 : RPCHelpMan listlabels()
     629             : {
     630          16 :     return RPCHelpMan{"listlabels",
     631           8 :                 "\nReturns the list of all labels, or labels that are assigned to addresses with a specific purpose.\n",
     632          16 :                 {
     633           8 :                     {"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."},
     634             :                 },
     635           8 :                 RPCResult{
     636           8 :                     RPCResult::Type::ARR, "", "",
     637          16 :                     {
     638           8 :                         {RPCResult::Type::STR, "label", "Label name"},
     639             :                     }
     640             :                 },
     641           8 :                 RPCExamples{
     642             :             "\nList all labels\n"
     643           8 :             + HelpExampleCli("listlabels", "") +
     644             :             "\nList labels that have receiving addresses\n"
     645           8 :             + HelpExampleCli("listlabels", "receive") +
     646             :             "\nList labels that have sending addresses\n"
     647           8 :             + HelpExampleCli("listlabels", "send") +
     648             :             "\nAs a JSON-RPC call\n"
     649           8 :             + HelpExampleRpc("listlabels", "receive")
     650             :                 },
     651           8 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     652             : {
     653           0 :     const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
     654           0 :     if (!pwallet) return UniValue::VNULL;
     655             : 
     656           0 :     LOCK(pwallet->cs_wallet);
     657             : 
     658           0 :     std::string purpose;
     659           0 :     if (!request.params[0].isNull()) {
     660           0 :         purpose = request.params[0].get_str();
     661           0 :     }
     662             : 
     663             :     // Add to a set to sort by label name, then insert into Univalue array
     664           0 :     std::set<std::string> label_set = pwallet->ListAddrBookLabels(purpose);
     665             : 
     666           0 :     UniValue ret(UniValue::VARR);
     667           0 :     for (const std::string& name : label_set) {
     668           0 :         ret.push_back(name);
     669             :     }
     670             : 
     671           0 :     return ret;
     672           0 : },
     673             :     };
     674           0 : }
     675             : 
     676             : #ifdef ENABLE_EXTERNAL_SIGNER
     677           8 : RPCHelpMan walletdisplayaddress()
     678             : {
     679          16 :     return RPCHelpMan{"walletdisplayaddress",
     680           8 :         "Display address on an external signer for verification.",
     681          16 :         {
     682           8 :             {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "dash address to display"},
     683             :         },
     684           8 :         RPCResult{
     685           8 :             RPCResult::Type::OBJ,"","",
     686          16 :             {
     687           8 :                 {RPCResult::Type::STR, "address", "The address as confirmed by the signer"},
     688             :             }
     689             :         },
     690           8 :         RPCExamples{""},
     691           8 :         [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
     692             :         {
     693           0 :             std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
     694           0 :             if (!wallet) return NullUniValue;
     695           0 :             CWallet* const pwallet = wallet.get();
     696             : 
     697           0 :             LOCK(pwallet->cs_wallet);
     698             : 
     699           0 :             CTxDestination dest = DecodeDestination(request.params[0].get_str());
     700             : 
     701             :             // Make sure the destination is valid
     702           0 :             if (!IsValidDestination(dest)) {
     703           0 :                 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
     704             :             }
     705             : 
     706           0 :             if (!pwallet->DisplayAddress(dest)) {
     707           0 :                 throw JSONRPCError(RPC_MISC_ERROR, "Failed to display address");
     708             :             }
     709             : 
     710           0 :             UniValue result(UniValue::VOBJ);
     711           0 :             result.pushKV("address", request.params[0].get_str());
     712           0 :             return result;
     713           0 :         }
     714             :     };
     715           0 : }
     716             : #endif // ENABLE_EXTERNAL_SIGNER
     717             : 
     718             : } // namespace wallet

Generated by: LCOV version 1.16