Coverage Report

Created: 2025-05-14 12:32

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