Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/wallet/rpc/coins.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 <core_io.h>
6
#include <hash.h>
7
#include <key_io.h>
8
#include <rpc/util.h>
9
#include <script/script.h>
10
#include <util/moneystr.h>
11
#include <wallet/coincontrol.h>
12
#include <wallet/receive.h>
13
#include <wallet/rpc/util.h>
14
#include <wallet/spend.h>
15
#include <wallet/wallet.h>
16
17
#include <univalue.h>
18
19
20
namespace wallet {
21
static CAmount GetReceived(const CWallet& wallet, const UniValue& params, bool by_label) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
22
44
{
23
44
    std::vector<CTxDestination> addresses;
24
44
    if (by_label) {
25
        // Get the set of addresses assigned to label
26
25
        addresses = wallet.ListAddrBookAddresses(CWallet::AddrBookFilter{LabelFromValue(params[0])});
27
25
        if (addresses.empty()) throw JSONRPCError(RPC_WALLET_ERROR, "Label not found in wallet");
28
25
    } else {
29
        // Get the address
30
19
        CTxDestination dest = DecodeDestination(params[0].get_str());
31
19
        if (!IsValidDestination(dest)) {
32
1
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
33
1
        }
34
18
        addresses.emplace_back(dest);
35
18
    }
36
37
    // Filter by own scripts only
38
42
    std::set<CScript> output_scripts;
39
61
    for (const auto& address : addresses) {
40
61
        auto output_script{GetScriptForDestination(address)};
41
61
        if (wallet.IsMine(output_script)) {
42
60
            output_scripts.insert(output_script);
43
60
        }
44
61
    }
45
46
42
    if (output_scripts.empty()) {
47
1
        throw JSONRPCError(RPC_WALLET_ERROR, "Address not found in wallet");
48
1
    }
49
50
    // Minimum confirmations
51
41
    int min_depth = 1;
52
41
    if (!params[1].isNull())
53
3
        min_depth = params[1].getInt<int>();
54
55
41
    const bool include_immature_coinbase{params[2].isNull() ? false : params[2].get_bool()};
56
57
    // Tally
58
41
    CAmount amount = 0;
59
3.39k
    for (const auto& [_, wtx] : wallet.mapWallet) {
60
3.39k
        int depth{wallet.GetTxDepthInMainChain(wtx)};
61
3.39k
        if (depth < min_depth
62
            // Coinbase with less than 1 confirmation is no longer in the main chain
63
3.39k
            || (wtx.IsCoinBase() && (depth < 1))
64
3.39k
            || (wallet.IsTxImmatureCoinBase(wtx) && !include_immature_coinbase))
65
2.36k
        {
66
2.36k
            continue;
67
2.36k
        }
68
69
2.03k
        for (const CTxOut& txout : wtx.GetTx()->vout) {
70
2.03k
            if (output_scripts.contains(txout.scriptPubKey)) {
71
50
                amount += txout.nValue;
72
50
            }
73
2.03k
        }
74
1.02k
    }
75
76
41
    return amount;
77
42
}
78
79
80
RPCMethod getreceivedbyaddress()
81
904
{
82
904
    return RPCMethod{
83
904
        "getreceivedbyaddress",
84
904
        "Returns the total amount received by the given address in transactions with at least minconf confirmations.\n",
85
904
                {
86
904
                    {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address for transactions."},
87
904
                    {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "Only include transactions confirmed at least this many times."},
88
904
                    {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase transactions."},
89
904
                },
90
904
                RPCResult{
91
904
                    RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received at this address."
92
904
                },
93
904
                RPCExamples{
94
904
            "\nThe amount from transactions with at least 1 confirmation\n"
95
904
            + HelpExampleCli("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\"") +
96
904
            "\nThe amount including unconfirmed transactions, zero confirmations\n"
97
904
            + HelpExampleCli("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0") +
98
904
            "\nThe amount with at least 6 confirmations\n"
99
904
            + HelpExampleCli("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 6") +
100
904
            "\nThe amount with at least 6 confirmations including immature coinbase outputs\n"
101
904
            + HelpExampleCli("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 6 true") +
102
904
            "\nAs a JSON-RPC call\n"
103
904
            + HelpExampleRpc("getreceivedbyaddress", "\"" + EXAMPLE_ADDRESS[0] + "\", 6")
104
904
                },
105
904
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
106
904
{
107
19
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
108
19
    if (!pwallet) return UniValue::VNULL;
109
110
    // Make sure the results are valid at least up to the most recent block
111
    // the user could have gotten from another RPC command prior to now
112
19
    pwallet->BlockUntilSyncedToCurrentChain();
113
114
19
    LOCK(pwallet->cs_wallet);
115
116
19
    return ValueFromAmount(GetReceived(*pwallet, request.params, /*by_label=*/false));
117
19
},
118
904
    };
119
904
}
120
121
122
RPCMethod getreceivedbylabel()
123
910
{
124
910
    return RPCMethod{
125
910
        "getreceivedbylabel",
126
910
        "Returns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.\n",
127
910
                {
128
910
                    {"label", RPCArg::Type::STR, RPCArg::Optional::NO, "The selected label, may be the default label using \"\"."},
129
910
                    {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "Only include transactions confirmed at least this many times."},
130
910
                    {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase transactions."},
131
910
                },
132
910
                RPCResult{
133
910
                    RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received for this label."
134
910
                },
135
910
                RPCExamples{
136
910
            "\nAmount received by the default label with at least 1 confirmation\n"
137
910
            + HelpExampleCli("getreceivedbylabel", "\"\"") +
138
910
            "\nAmount received at the tabby label including unconfirmed amounts with zero confirmations\n"
139
910
            + HelpExampleCli("getreceivedbylabel", "\"tabby\" 0") +
140
910
            "\nThe amount with at least 6 confirmations\n"
141
910
            + HelpExampleCli("getreceivedbylabel", "\"tabby\" 6") +
142
910
            "\nThe amount with at least 6 confirmations including immature coinbase outputs\n"
143
910
            + HelpExampleCli("getreceivedbylabel", "\"tabby\" 6 true") +
144
910
            "\nAs a JSON-RPC call\n"
145
910
            + HelpExampleRpc("getreceivedbylabel", "\"tabby\", 6, true")
146
910
                },
147
910
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
148
910
{
149
25
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
150
25
    if (!pwallet) return UniValue::VNULL;
151
152
    // Make sure the results are valid at least up to the most recent block
153
    // the user could have gotten from another RPC command prior to now
154
25
    pwallet->BlockUntilSyncedToCurrentChain();
155
156
25
    LOCK(pwallet->cs_wallet);
157
158
25
    return ValueFromAmount(GetReceived(*pwallet, request.params, /*by_label=*/true));
159
25
},
160
910
    };
161
910
}
162
163
164
RPCMethod getbalance()
165
1.39k
{
166
1.39k
    return RPCMethod{
167
1.39k
        "getbalance",
168
1.39k
        "Returns the total available balance.\n"
169
1.39k
                "The available balance is what the wallet considers currently spendable, and is\n"
170
1.39k
                "thus affected by options which limit spendability such as -spendzeroconfchange.\n",
171
1.39k
                {
172
1.39k
                    {"dummy", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Remains for backward compatibility. Must be excluded or set to \"*\".",
173
1.39k
                        RPCArgOptions{.placeholder = true}},
174
1.39k
                    {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "Only include transactions confirmed at least this many times."},
175
1.39k
                    {"include_watchonly", RPCArg::Type::BOOL, RPCArg::Default{false}, "No longer used"},
176
1.39k
                    {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{true}, "(only available if avoid_reuse wallet flag is set) Do not include balance in dirty outputs; addresses are considered dirty if they have previously been used in a transaction."},
177
1.39k
                },
178
1.39k
                RPCResult{
179
1.39k
                    RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received for this wallet."
180
1.39k
                },
181
1.39k
                RPCExamples{
182
1.39k
            "\nThe total amount in the wallet with 0 or more confirmations\n"
183
1.39k
            + HelpExampleCli("getbalance", "") +
184
1.39k
            "\nThe total amount in the wallet with at least 6 confirmations\n"
185
1.39k
            + HelpExampleCli("getbalance", "\"*\" 6") +
186
1.39k
            "\nAs a JSON-RPC call\n"
187
1.39k
            + HelpExampleRpc("getbalance", "\"*\", 6")
188
1.39k
                },
189
1.39k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
190
1.39k
{
191
505
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
192
505
    if (!pwallet) return UniValue::VNULL;
193
194
    // Make sure the results are valid at least up to the most recent block
195
    // the user could have gotten from another RPC command prior to now
196
505
    pwallet->BlockUntilSyncedToCurrentChain();
197
198
505
    LOCK(pwallet->cs_wallet);
199
200
505
    if (self.MaybeArg<std::string_view>("dummy").value_or("*") != "*") {
201
1
        throw JSONRPCError(RPC_METHOD_DEPRECATED, "dummy first argument must be excluded or set to \"*\".");
202
1
    }
203
204
504
    const auto min_depth{self.Arg<int>("minconf")};
205
206
504
    bool avoid_reuse = GetAvoidReuseFlag(*pwallet, request.params[3]);
207
208
504
    const auto bal = GetBalance(*pwallet, min_depth, avoid_reuse);
209
210
504
    return ValueFromAmount(bal.m_mine_trusted);
211
505
},
212
1.39k
    };
213
1.39k
}
214
215
RPCMethod lockunspent()
216
922
{
217
922
    return RPCMethod{
218
922
        "lockunspent",
219
922
        "Updates list of temporarily unspendable outputs.\n"
220
922
                "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
221
922
                "If no transaction outputs are specified when unlocking then all current locked transaction outputs are unlocked.\n"
222
922
                "A locked transaction output will not be chosen by automatic coin selection, when spending bitcoins.\n"
223
922
                "Manually selected coins are automatically unlocked.\n"
224
922
                "Locks are stored in memory only, unless persistent=true, in which case they will be written to the\n"
225
922
                "wallet database and loaded on node start. Unwritten (persistent=false) locks are always cleared\n"
226
922
                "(by virtue of process exit) when a node stops or fails. Unlocking will clear both persistent and not.\n"
227
922
                "Also see the listunspent call\n",
228
922
                {
229
922
                    {"unlock", RPCArg::Type::BOOL, RPCArg::Optional::NO, "Whether to unlock (true) or lock (false) the specified transactions"},
230
922
                    {"transactions", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The transaction outputs and within each, the txid (string) vout (numeric).",
231
922
                        {
232
922
                            {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
233
922
                                {
234
922
                                    {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
235
922
                                    {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
236
922
                                },
237
922
                            },
238
922
                        },
239
922
                    },
240
922
                    {"persistent", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to write/erase this lock in the wallet database, or keep the change in memory only. Ignored for unlocking."},
241
922
                },
242
922
                RPCResult{
243
922
                    RPCResult::Type::BOOL, "", "Whether the command was successful or not"
244
922
                },
245
922
                RPCExamples{
246
922
            "\nList the unspent transactions\n"
247
922
            + HelpExampleCli("listunspent", "") +
248
922
            "\nLock an unspent transaction\n"
249
922
            + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
250
922
            "\nList the locked transactions\n"
251
922
            + HelpExampleCli("listlockunspent", "") +
252
922
            "\nUnlock the transaction again\n"
253
922
            + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
254
922
            "\nLock the transaction persistently in the wallet database\n"
255
922
            + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\" true") +
256
922
            "\nAs a JSON-RPC call\n"
257
922
            + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
258
922
                },
259
922
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
260
922
{
261
37
    std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
262
37
    if (!pwallet) return UniValue::VNULL;
263
264
    // Make sure the results are valid at least up to the most recent block
265
    // the user could have gotten from another RPC command prior to now
266
37
    pwallet->BlockUntilSyncedToCurrentChain();
267
268
37
    LOCK(pwallet->cs_wallet);
269
270
37
    bool fUnlock = request.params[0].get_bool();
271
272
37
    const bool persistent{self.Arg<bool>("persistent")};
273
274
37
    if (request.params[1].isNull()) {
275
4
        if (fUnlock) {
276
4
            if (!pwallet->UnlockAllCoins())
277
0
                throw JSONRPCError(RPC_WALLET_ERROR, "Unlocking coins failed");
278
4
        }
279
4
        return true;
280
4
    }
281
282
33
    const UniValue& output_params = request.params[1].get_array();
283
284
    // Create and validate the COutPoints first.
285
286
33
    std::vector<COutPoint> outputs;
287
33
    outputs.reserve(output_params.size());
288
289
103
    for (unsigned int idx = 0; idx < output_params.size(); idx++) {
290
77
        const UniValue& o = output_params[idx].get_obj();
291
292
77
        RPCTypeCheckObj(o,
293
77
            {
294
77
                {"txid", UniValueType(UniValue::VSTR)},
295
77
                {"vout", UniValueType(UniValue::VNUM)},
296
77
            });
297
298
77
        const Txid txid = Txid::FromUint256(ParseHashO(o, "txid"));
299
77
        const int nOutput = o.find_value("vout").getInt<int>();
300
77
        if (nOutput < 0) {
301
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
302
0
        }
303
304
77
        const COutPoint outpt(txid, nOutput);
305
306
77
        const auto it = pwallet->mapWallet.find(outpt.hash);
307
77
        if (it == pwallet->mapWallet.end()) {
308
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, unknown transaction");
309
1
        }
310
311
76
        const CWalletTx& trans = it->second;
312
313
76
        if (outpt.n >= trans.GetTx()->vout.size()) {
314
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout index out of bounds");
315
1
        }
316
317
75
        if (pwallet->IsSpent(outpt)) {
318
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected unspent output");
319
1
        }
320
321
74
        const bool is_locked = pwallet->IsLockedCoin(outpt);
322
323
74
        if (fUnlock && !is_locked) {
324
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected locked output");
325
1
        }
326
327
73
        if (!fUnlock && is_locked && !persistent) {
328
3
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output already locked");
329
3
        }
330
331
70
        outputs.push_back(outpt);
332
70
    }
333
334
    // Atomically set (un)locked status for the outputs.
335
68
    for (const COutPoint& outpt : outputs) {
336
68
        if (fUnlock) {
337
2
            if (!pwallet->UnlockCoin(outpt)) throw JSONRPCError(RPC_WALLET_ERROR, "Unlocking coin failed");
338
66
        } else {
339
66
            if (!pwallet->LockCoin(outpt, persistent)) throw JSONRPCError(RPC_WALLET_ERROR, "Locking coin failed");
340
66
        }
341
68
    }
342
343
26
    return true;
344
26
},
345
922
    };
346
922
}
347
348
RPCMethod listlockunspent()
349
896
{
350
896
    return RPCMethod{
351
896
        "listlockunspent",
352
896
        "Returns list of temporarily unspendable outputs.\n"
353
896
                "See the lockunspent call to lock and unlock transactions for spending.\n",
354
896
                {},
355
896
                RPCResult{
356
896
                    RPCResult::Type::ARR, "", "",
357
896
                    {
358
896
                        {RPCResult::Type::OBJ, "", "",
359
896
                        {
360
896
                            {RPCResult::Type::STR_HEX, "txid", "The transaction id locked"},
361
896
                            {RPCResult::Type::NUM, "vout", "The vout value"},
362
896
                        }},
363
896
                    }
364
896
                },
365
896
                RPCExamples{
366
896
            "\nList the unspent transactions\n"
367
896
            + HelpExampleCli("listunspent", "") +
368
896
            "\nLock an unspent transaction\n"
369
896
            + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
370
896
            "\nList the locked transactions\n"
371
896
            + HelpExampleCli("listlockunspent", "") +
372
896
            "\nUnlock the transaction again\n"
373
896
            + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
374
896
            "\nAs a JSON-RPC call\n"
375
896
            + HelpExampleRpc("listlockunspent", "")
376
896
                },
377
896
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
378
896
{
379
11
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
380
11
    if (!pwallet) return UniValue::VNULL;
381
382
11
    LOCK(pwallet->cs_wallet);
383
384
11
    std::vector<COutPoint> vOutpts;
385
11
    pwallet->ListLockedCoins(vOutpts);
386
387
11
    UniValue ret(UniValue::VARR);
388
389
11
    for (const COutPoint& outpt : vOutpts) {
390
7
        UniValue o(UniValue::VOBJ);
391
392
7
        o.pushKV("txid", outpt.hash.GetHex());
393
7
        o.pushKV("vout", outpt.n);
394
7
        ret.push_back(std::move(o));
395
7
    }
396
397
11
    return ret;
398
11
},
399
896
    };
400
896
}
401
402
RPCMethod getbalances()
403
1.55k
{
404
1.55k
    return RPCMethod{
405
1.55k
        "getbalances",
406
1.55k
        "Returns an object with all balances in " + CURRENCY_UNIT + ".\n",
407
1.55k
        {},
408
1.55k
        RPCResult{
409
1.55k
            RPCResult::Type::OBJ, "", "",
410
1.55k
            {
411
1.55k
                {RPCResult::Type::OBJ, "mine", "balances from outputs that the wallet can sign",
412
1.55k
                {
413
1.55k
                    {RPCResult::Type::STR_AMOUNT, "trusted", "trusted balance (outputs created by the wallet or confirmed outputs)"},
414
1.55k
                    {RPCResult::Type::STR_AMOUNT, "untrusted_pending", "untrusted pending balance (outputs created by others that are in the mempool)"},
415
1.55k
                    {RPCResult::Type::STR_AMOUNT, "immature", "balance from immature coinbase outputs"},
416
1.55k
                    {RPCResult::Type::STR_AMOUNT, "nonmempool", "sum of coins that are spent by transactions not in the mempool (usually an over-estimate due to not accounting for change or spends that conflict with each other)"},
417
1.55k
                    {RPCResult::Type::STR_AMOUNT, "used", /*optional=*/true, "(only present if avoid_reuse is set) balance from coins sent to addresses that were previously spent from (potentially privacy violating)"},
418
1.55k
                }},
419
1.55k
                RESULT_LAST_PROCESSED_BLOCK,
420
1.55k
            }
421
1.55k
            },
422
1.55k
        RPCExamples{
423
1.55k
            HelpExampleCli("getbalances", "") +
424
1.55k
            HelpExampleRpc("getbalances", "")},
425
1.55k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
426
1.55k
{
427
674
    const std::shared_ptr<const CWallet> rpc_wallet = GetWalletForJSONRPCRequest(request);
428
674
    if (!rpc_wallet) return UniValue::VNULL;
429
674
    const CWallet& wallet = *rpc_wallet;
430
431
    // Make sure the results are valid at least up to the most recent block
432
    // the user could have gotten from another RPC command prior to now
433
674
    wallet.BlockUntilSyncedToCurrentChain();
434
435
674
    LOCK(wallet.cs_wallet);
436
437
674
    const auto bal = GetBalance(wallet, /*min_depth=*/0, /*avoid_reuse=*/true, /*include_nonmempool=*/true);
438
439
674
    UniValue balances{UniValue::VOBJ};
440
674
    {
441
674
        UniValue balances_mine{UniValue::VOBJ};
442
674
        balances_mine.pushKV("trusted", ValueFromAmount(bal.m_mine_trusted));
443
674
        balances_mine.pushKV("untrusted_pending", ValueFromAmount(bal.m_mine_untrusted_pending));
444
674
        balances_mine.pushKV("immature", ValueFromAmount(bal.m_mine_immature));
445
674
        balances_mine.pushKV("nonmempool", ValueFromAmount(bal.m_mine_nonmempool));
446
674
        if (wallet.IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE)) {
447
11
            balances_mine.pushKV("used", ValueFromAmount(bal.m_mine_used));
448
11
        }
449
674
        balances.pushKV("mine", std::move(balances_mine));
450
674
    }
451
674
    AppendLastProcessedBlock(balances, wallet);
452
674
    return balances;
453
674
},
454
1.55k
    };
455
1.55k
}
456
457
const UniValue* GetOptionWithAlias(
458
    const UniValue& options,
459
    const std::string& canonical_name,
460
    const std::string& deprecated_name)
461
2.95k
{
462
2.95k
    if (options.exists(canonical_name) && options.exists(deprecated_name)) {
463
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Use " + canonical_name + " (" + deprecated_name + " is deprecated). Do not set both.");
464
1
    }
465
2.95k
    if (options.exists(deprecated_name)) {
466
249
        return &options[deprecated_name];
467
249
    }
468
2.70k
    if (options.exists(canonical_name)) {
469
45
        return &options[canonical_name];
470
45
    }
471
2.65k
    return nullptr;
472
2.70k
}
473
474
RPCMethod listunspent()
475
1.35k
{
476
1.35k
    return RPCMethod{
477
1.35k
        "listunspent",
478
1.35k
        "Returns array of unspent transaction outputs\n"
479
1.35k
                "with between minconf and maxconf (inclusive) confirmations.\n"
480
1.35k
                "Optionally filter to only include txouts paid to specified addresses.\n",
481
1.35k
                {
482
1.35k
                    {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "The minimum confirmations to filter"},
483
1.35k
                    {"maxconf", RPCArg::Type::NUM, RPCArg::Default{9999999}, "The maximum confirmations to filter"},
484
1.35k
                    {"addresses", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The bitcoin addresses to filter",
485
1.35k
                        {
486
1.35k
                            {"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "bitcoin address"},
487
1.35k
                        },
488
1.35k
                    },
489
1.35k
                    {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include outputs that are not safe to spend\n"
490
1.35k
                              "See description of \"safe\" attribute below."},
491
1.35k
                    {"query_options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
492
1.35k
                        {
493
1.35k
                            {"minimum_amount|minimumAmount", RPCArg::Type::AMOUNT, RPCArg::Default{FormatMoney(0)}, "Minimum value of each UTXO in " + CURRENCY_UNIT + ""},
494
1.35k
                            {"maximum_amount|maximumAmount", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"unlimited"}, "Maximum value of each UTXO in " + CURRENCY_UNIT + ""},
495
1.35k
                            {"maximum_count|maximumCount", RPCArg::Type::NUM, RPCArg::DefaultHint{"unlimited"}, "Maximum number of UTXOs"},
496
1.35k
                            {"minimum_sum_amount|minimumSumAmount", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"unlimited"}, "Minimum sum value of all UTXOs in " + CURRENCY_UNIT + ""},
497
1.35k
                            {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase UTXOs"}
498
1.35k
                        },
499
1.35k
                        RPCArgOptions{.oneline_description="query_options"}},
500
1.35k
                },
501
1.35k
                RPCResult{
502
1.35k
                    RPCResult::Type::ARR, "", "",
503
1.35k
                    {
504
1.35k
                        {RPCResult::Type::OBJ, "", "",
505
1.35k
                        {
506
1.35k
                            {RPCResult::Type::STR_HEX, "txid", "the transaction id"},
507
1.35k
                            {RPCResult::Type::NUM, "vout", "the vout value"},
508
1.35k
                            {RPCResult::Type::STR, "address", /*optional=*/true, "the bitcoin address"},
509
1.35k
                            {RPCResult::Type::STR, "label", /*optional=*/true, "The associated label, or \"\" for the default label"},
510
1.35k
                            {RPCResult::Type::STR_HEX, "scriptPubKey", "the output script"},
511
1.35k
                            {RPCResult::Type::STR_AMOUNT, "amount", "the transaction output amount in " + CURRENCY_UNIT},
512
1.35k
                            {RPCResult::Type::NUM, "confirmations", "The number of confirmations"},
513
1.35k
                            {RPCResult::Type::NUM, "ancestorcount", /*optional=*/true, "The number of in-mempool ancestor transactions, including this one (if transaction is in the mempool)"},
514
1.35k
                            {RPCResult::Type::NUM, "ancestorsize", /*optional=*/true, "The virtual transaction size of in-mempool ancestors, including this one (if transaction is in the mempool)"},
515
1.35k
                            {RPCResult::Type::NUM, "ancestorfees", /*optional=*/true, "The total fees of in-mempool ancestors (including this one) with fee deltas used for mining priority in " + CURRENCY_ATOM + " (if transaction is in the mempool)"},
516
1.35k
                            {RPCResult::Type::STR_HEX, "redeemScript", /*optional=*/true, "The redeem script if the output script is P2SH"},
517
1.35k
                            {RPCResult::Type::STR, "witnessScript", /*optional=*/true, "witness script if the output script is P2WSH or P2SH-P2WSH"},
518
1.35k
                            {RPCResult::Type::BOOL, "spendable", "(DEPRECATED) Always true"},
519
1.35k
                            {RPCResult::Type::BOOL, "solvable", "Whether we know how to spend this output, ignoring the lack of keys"},
520
1.35k
                            {RPCResult::Type::BOOL, "reused", /*optional=*/true, "(only present if avoid_reuse is set) Whether this output is reused/dirty (sent to an address that was previously spent from)"},
521
1.35k
                            {RPCResult::Type::STR, "desc", /*optional=*/true, "(only when solvable) A descriptor for spending this output"},
522
1.35k
                            {RPCResult::Type::ARR, "parent_descs", /*optional=*/false, "List of parent descriptors for the output script of this coin.", {
523
1.35k
                                {RPCResult::Type::STR, "desc", "The descriptor string."},
524
1.35k
                            }},
525
1.35k
                            {RPCResult::Type::BOOL, "safe", "Whether this output is considered safe to spend. Unconfirmed transactions\n"
526
1.35k
                                                            "from outside keys and unconfirmed replacement transactions are considered unsafe\n"
527
1.35k
                                                            "and are not eligible for spending by fundrawtransaction and sendtoaddress."},
528
1.35k
                        }},
529
1.35k
                    }
530
1.35k
                },
531
1.35k
                RPCExamples{
532
1.35k
                    HelpExampleCli("listunspent", "")
533
1.35k
            + HelpExampleCli("listunspent", "6 9999999 \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"")
534
1.35k
            + HelpExampleRpc("listunspent", strprintf(R"(6, 9999999, ["%s","%s"])", EXAMPLE_ADDRESS[0], EXAMPLE_ADDRESS[1]))
535
1.35k
            + HelpExampleCli("listunspent", "6 9999999 '[]' true '{ \"minimum_amount\": 0.005 }'")
536
1.35k
            + HelpExampleRpc("listunspent", "6, 9999999, [] , true, { \"minimum_amount\": 0.005 } ")
537
1.35k
                },
538
1.35k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
539
1.35k
{
540
467
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
541
467
    if (!pwallet) return UniValue::VNULL;
542
543
467
    const int nMinDepth{self.Arg<int>("minconf")};
544
467
    const int nMaxDepth{self.Arg<int>("maxconf")};
545
546
467
    std::set<CTxDestination> destinations;
547
467
    if (!request.params[2].isNull()) {
548
54
        UniValue inputs = request.params[2].get_array();
549
111
        for (unsigned int idx = 0; idx < inputs.size(); idx++) {
550
57
            const UniValue& input = inputs[idx];
551
57
            CTxDestination dest = DecodeDestination(input.get_str());
552
57
            if (!IsValidDestination(dest)) {
553
0
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + input.get_str());
554
0
            }
555
57
            if (!destinations.insert(dest).second) {
556
0
                throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + input.get_str());
557
0
            }
558
57
        }
559
54
    }
560
561
467
    const bool include_unsafe{self.Arg<bool>("include_unsafe")};
562
563
467
    CoinFilterParams filter_coins;
564
467
    filter_coins.min_amount = 0;
565
566
467
    if (!request.params[4].isNull()) {
567
132
        const UniValue& options = request.params[4].get_obj();
568
569
132
        RPCTypeCheckObj(options,
570
132
            {
571
132
                {"minimum_amount", UniValueType()},
572
132
                {"minimumAmount", UniValueType()},
573
132
                {"maximum_amount", UniValueType()},
574
132
                {"maximumAmount", UniValueType()},
575
132
                {"minimum_sum_amount", UniValueType()},
576
132
                {"minimumSumAmount", UniValueType()},
577
132
                {"maximum_count", UniValueType(UniValue::VNUM)},
578
132
                {"maximumCount", UniValueType(UniValue::VNUM)},
579
132
                {"include_immature_coinbase", UniValueType(UniValue::VBOOL)}
580
132
            },
581
132
            true, true);
582
583
132
        if (const UniValue* value = GetOptionWithAlias(options, "minimum_amount", "minimumAmount"))
584
128
            filter_coins.min_amount = AmountFromValue(*value);
585
586
132
        if (const UniValue* value = GetOptionWithAlias(options, "maximum_amount", "maximumAmount"))
587
0
            filter_coins.max_amount = AmountFromValue(*value);
588
589
132
        if (const UniValue* value = GetOptionWithAlias(options, "minimum_sum_amount", "minimumSumAmount"))
590
0
            filter_coins.min_sum_amount = AmountFromValue(*value);
591
592
132
        if (const UniValue* value = GetOptionWithAlias(options, "maximum_count", "maximumCount"))
593
0
            filter_coins.max_count = value->getInt<int64_t>();
594
595
132
        if (options.exists("include_immature_coinbase")) {
596
4
            filter_coins.include_immature_coinbase = options["include_immature_coinbase"].get_bool();
597
4
        }
598
132
    }
599
600
    // Make sure the results are valid at least up to the most recent block
601
    // the user could have gotten from another RPC command prior to now
602
467
    pwallet->BlockUntilSyncedToCurrentChain();
603
604
467
    UniValue results(UniValue::VARR);
605
467
    std::vector<COutput> vecOutputs;
606
467
    {
607
467
        CCoinControl cctl;
608
467
        cctl.m_avoid_address_reuse = false;
609
467
        cctl.m_min_depth = nMinDepth;
610
467
        cctl.m_max_depth = nMaxDepth;
611
467
        cctl.m_include_unsafe_inputs = include_unsafe;
612
467
        filter_coins.check_version_trucness = false;
613
467
        LOCK(pwallet->cs_wallet);
614
467
        vecOutputs = AvailableCoins(*pwallet, &cctl, /*feerate=*/std::nullopt, filter_coins).All();
615
467
    }
616
617
467
    LOCK(pwallet->cs_wallet);
618
619
467
    const bool avoid_reuse = pwallet->IsWalletFlagSet(WALLET_FLAG_AVOID_REUSE);
620
621
8.07k
    for (const COutput& out : vecOutputs) {
622
8.07k
        CTxDestination address;
623
8.07k
        const CScript& scriptPubKey = out.txout.scriptPubKey;
624
8.07k
        bool fValidAddress = ExtractDestination(scriptPubKey, address);
625
8.07k
        bool reused = avoid_reuse && pwallet->IsSpentKey(scriptPubKey);
626
627
8.07k
        if (destinations.size() && (!fValidAddress || !destinations.contains(address)))
628
348
            continue;
629
630
7.73k
        UniValue entry(UniValue::VOBJ);
631
7.73k
        entry.pushKV("txid", out.outpoint.hash.GetHex());
632
7.73k
        entry.pushKV("vout", out.outpoint.n);
633
634
7.73k
        if (fValidAddress) {
635
7.73k
            entry.pushKV("address", EncodeDestination(address));
636
637
7.73k
            const auto* address_book_entry = pwallet->FindAddressBookEntry(address);
638
7.73k
            if (address_book_entry) {
639
7.33k
                entry.pushKV("label", address_book_entry->GetLabel());
640
7.33k
            }
641
642
7.73k
            std::unique_ptr<SigningProvider> provider = pwallet->GetSolvingProvider(scriptPubKey);
643
7.73k
            if (provider) {
644
7.73k
                if (scriptPubKey.IsPayToScriptHash()) {
645
44
                    const CScriptID hash = ToScriptID(std::get<ScriptHash>(address));
646
44
                    CScript redeemScript;
647
44
                    if (provider->GetCScript(hash, redeemScript)) {
648
44
                        entry.pushKV("redeemScript", HexStr(redeemScript));
649
                        // Now check if the redeemScript is actually a P2WSH script
650
44
                        CTxDestination witness_destination;
651
44
                        if (redeemScript.IsPayToWitnessScriptHash()) {
652
2
                            bool extracted = ExtractDestination(redeemScript, witness_destination);
653
2
                            CHECK_NONFATAL(extracted);
654
                            // Also return the witness script
655
2
                            const WitnessV0ScriptHash& whash = std::get<WitnessV0ScriptHash>(witness_destination);
656
2
                            CScriptID id{RIPEMD160(whash)};
657
2
                            CScript witnessScript;
658
2
                            if (provider->GetCScript(id, witnessScript)) {
659
2
                                entry.pushKV("witnessScript", HexStr(witnessScript));
660
2
                            }
661
2
                        }
662
44
                    }
663
7.68k
                } else if (scriptPubKey.IsPayToWitnessScriptHash()) {
664
30
                    const WitnessV0ScriptHash& whash = std::get<WitnessV0ScriptHash>(address);
665
30
                    CScriptID id{RIPEMD160(whash)};
666
30
                    CScript witnessScript;
667
30
                    if (provider->GetCScript(id, witnessScript)) {
668
30
                        entry.pushKV("witnessScript", HexStr(witnessScript));
669
30
                    }
670
30
                }
671
7.73k
            }
672
7.73k
        }
673
674
7.73k
        entry.pushKV("scriptPubKey", HexStr(scriptPubKey));
675
7.73k
        entry.pushKV("amount", ValueFromAmount(out.txout.nValue));
676
7.73k
        entry.pushKV("confirmations", out.depth);
677
7.73k
        if (!out.depth) {
678
76
            size_t ancestor_count, unused_cluster_count, ancestor_size;
679
76
            CAmount ancestor_fees;
680
76
            pwallet->chain().getTransactionAncestry(out.outpoint.hash, ancestor_count, unused_cluster_count, &ancestor_size, &ancestor_fees);
681
76
            if (ancestor_count) {
682
76
                entry.pushKV("ancestorcount", ancestor_count);
683
76
                entry.pushKV("ancestorsize", ancestor_size);
684
76
                entry.pushKV("ancestorfees", ancestor_fees);
685
76
            }
686
76
        }
687
7.73k
        entry.pushKV("spendable", true); // Any coins we list are always spendable
688
7.73k
        entry.pushKV("solvable", out.solvable);
689
7.73k
        if (out.solvable) {
690
7.72k
            std::unique_ptr<SigningProvider> provider = pwallet->GetSolvingProvider(scriptPubKey);
691
7.72k
            if (provider) {
692
7.72k
                auto descriptor = InferDescriptor(scriptPubKey, *provider);
693
7.72k
                entry.pushKV("desc", descriptor->ToString());
694
7.72k
            }
695
7.72k
        }
696
7.73k
        PushParentDescriptors(*pwallet, scriptPubKey, entry);
697
7.73k
        if (avoid_reuse) entry.pushKV("reused", reused);
698
7.73k
        entry.pushKV("safe", out.safe);
699
7.73k
        results.push_back(std::move(entry));
700
7.73k
    }
701
702
467
    return results;
703
467
},
704
1.35k
    };
705
1.35k
}
706
} // namespace wallet