fuzz coverage

Coverage Report

Created: 2025-06-01 19:34

/Users/eugenesiegel/btc/bitcoin/src/wallet/rpc/transactions.cpp
Line
Count
Source (jump to first uncovered line)
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 <key_io.h>
7
#include <policy/rbf.h>
8
#include <rpc/util.h>
9
#include <rpc/blockchain.h>
10
#include <util/vector.h>
11
#include <wallet/receive.h>
12
#include <wallet/rpc/util.h>
13
#include <wallet/wallet.h>
14
15
using interfaces::FoundBlock;
16
17
namespace wallet {
18
static void WalletTxToJSON(const CWallet& wallet, const CWalletTx& wtx, UniValue& entry)
19
    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
20
0
{
21
0
    interfaces::Chain& chain = wallet.chain();
22
0
    int confirms = wallet.GetTxDepthInMainChain(wtx);
23
0
    entry.pushKV("confirmations", confirms);
24
0
    if (wtx.IsCoinBase())
25
0
        entry.pushKV("generated", true);
26
0
    if (auto* conf = wtx.state<TxStateConfirmed>())
27
0
    {
28
0
        entry.pushKV("blockhash", conf->confirmed_block_hash.GetHex());
29
0
        entry.pushKV("blockheight", conf->confirmed_block_height);
30
0
        entry.pushKV("blockindex", conf->position_in_block);
31
0
        int64_t block_time;
32
0
        CHECK_NONFATAL(chain.findBlock(conf->confirmed_block_hash, FoundBlock().time(block_time)));
Line
Count
Source
103
0
    inline_check_non_fatal(condition, __FILE__, __LINE__, __func__, #condition)
33
0
        entry.pushKV("blocktime", block_time);
34
0
    } else {
35
0
        entry.pushKV("trusted", CachedTxIsTrusted(wallet, wtx));
36
0
    }
37
0
    uint256 hash = wtx.GetHash();
38
0
    entry.pushKV("txid", hash.GetHex());
39
0
    entry.pushKV("wtxid", wtx.GetWitnessHash().GetHex());
40
0
    UniValue conflicts(UniValue::VARR);
41
0
    for (const uint256& conflict : wallet.GetTxConflicts(wtx))
42
0
        conflicts.push_back(conflict.GetHex());
43
0
    entry.pushKV("walletconflicts", std::move(conflicts));
44
0
    UniValue mempool_conflicts(UniValue::VARR);
45
0
    for (const Txid& mempool_conflict : wtx.mempool_conflicts)
46
0
        mempool_conflicts.push_back(mempool_conflict.GetHex());
47
0
    entry.pushKV("mempoolconflicts", std::move(mempool_conflicts));
48
0
    entry.pushKV("time", wtx.GetTxTime());
49
0
    entry.pushKV("timereceived", int64_t{wtx.nTimeReceived});
50
51
    // Add opt-in RBF status
52
0
    std::string rbfStatus = "no";
53
0
    if (confirms <= 0) {
54
0
        RBFTransactionState rbfState = chain.isRBFOptIn(*wtx.tx);
55
0
        if (rbfState == RBFTransactionState::UNKNOWN)
56
0
            rbfStatus = "unknown";
57
0
        else if (rbfState == RBFTransactionState::REPLACEABLE_BIP125)
58
0
            rbfStatus = "yes";
59
0
    }
60
0
    entry.pushKV("bip125-replaceable", rbfStatus);
61
62
0
    for (const std::pair<const std::string, std::string>& item : wtx.mapValue)
63
0
        entry.pushKV(item.first, item.second);
64
0
}
65
66
struct tallyitem
67
{
68
    CAmount nAmount{0};
69
    int nConf{std::numeric_limits<int>::max()};
70
    std::vector<uint256> txids;
71
    bool fIsWatchonly{false};
72
0
    tallyitem() = default;
73
};
74
75
static UniValue ListReceived(const CWallet& wallet, const UniValue& params, const bool by_label, const bool include_immature_coinbase) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
76
0
{
77
    // Minimum confirmations
78
0
    int nMinDepth = 1;
79
0
    if (!params[0].isNull())
80
0
        nMinDepth = params[0].getInt<int>();
81
82
    // Whether to include empty labels
83
0
    bool fIncludeEmpty = false;
84
0
    if (!params[1].isNull())
85
0
        fIncludeEmpty = params[1].get_bool();
86
87
0
    isminefilter filter = ISMINE_SPENDABLE;
88
89
0
    if (ParseIncludeWatchonly(params[2], wallet)) {
90
0
        filter |= ISMINE_WATCH_ONLY;
91
0
    }
92
93
0
    std::optional<CTxDestination> filtered_address{std::nullopt};
94
0
    if (!by_label && !params[3].isNull() && !params[3].get_str().empty()) {
95
0
        if (!IsValidDestinationString(params[3].get_str())) {
96
0
            throw JSONRPCError(RPC_WALLET_ERROR, "address_filter parameter was invalid");
97
0
        }
98
0
        filtered_address = DecodeDestination(params[3].get_str());
99
0
    }
100
101
    // Tally
102
0
    std::map<CTxDestination, tallyitem> mapTally;
103
0
    for (const std::pair<const uint256, CWalletTx>& pairWtx : wallet.mapWallet) {
104
0
        const CWalletTx& wtx = pairWtx.second;
105
106
0
        int nDepth = wallet.GetTxDepthInMainChain(wtx);
107
0
        if (nDepth < nMinDepth)
108
0
            continue;
109
110
        // Coinbase with less than 1 confirmation is no longer in the main chain
111
0
        if ((wtx.IsCoinBase() && (nDepth < 1))
112
0
            || (wallet.IsTxImmatureCoinBase(wtx) && !include_immature_coinbase)) {
113
0
            continue;
114
0
        }
115
116
0
        for (const CTxOut& txout : wtx.tx->vout) {
117
0
            CTxDestination address;
118
0
            if (!ExtractDestination(txout.scriptPubKey, address))
119
0
                continue;
120
121
0
            if (filtered_address && !(filtered_address == address)) {
122
0
                continue;
123
0
            }
124
125
0
            isminefilter mine = wallet.IsMine(address);
126
0
            if (!(mine & filter))
127
0
                continue;
128
129
0
            tallyitem& item = mapTally[address];
130
0
            item.nAmount += txout.nValue;
131
0
            item.nConf = std::min(item.nConf, nDepth);
132
0
            item.txids.push_back(wtx.GetHash());
133
0
            if (mine & ISMINE_WATCH_ONLY)
134
0
                item.fIsWatchonly = true;
135
0
        }
136
0
    }
137
138
    // Reply
139
0
    UniValue ret(UniValue::VARR);
140
0
    std::map<std::string, tallyitem> label_tally;
141
142
0
    const auto& func = [&](const CTxDestination& address, const std::string& label, bool is_change, const std::optional<AddressPurpose>& purpose) {
143
0
        if (is_change) return; // no change addresses
144
145
0
        auto it = mapTally.find(address);
146
0
        if (it == mapTally.end() && !fIncludeEmpty)
147
0
            return;
148
149
0
        CAmount nAmount = 0;
150
0
        int nConf = std::numeric_limits<int>::max();
151
0
        bool fIsWatchonly = false;
152
0
        if (it != mapTally.end()) {
153
0
            nAmount = (*it).second.nAmount;
154
0
            nConf = (*it).second.nConf;
155
0
            fIsWatchonly = (*it).second.fIsWatchonly;
156
0
        }
157
158
0
        if (by_label) {
159
0
            tallyitem& _item = label_tally[label];
160
0
            _item.nAmount += nAmount;
161
0
            _item.nConf = std::min(_item.nConf, nConf);
162
0
            _item.fIsWatchonly = fIsWatchonly;
163
0
        } else {
164
0
            UniValue obj(UniValue::VOBJ);
165
0
            if (fIsWatchonly) obj.pushKV("involvesWatchonly", true);
166
0
            obj.pushKV("address",       EncodeDestination(address));
167
0
            obj.pushKV("amount",        ValueFromAmount(nAmount));
168
0
            obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
169
0
            obj.pushKV("label", label);
170
0
            UniValue transactions(UniValue::VARR);
171
0
            if (it != mapTally.end()) {
172
0
                for (const uint256& _item : (*it).second.txids) {
173
0
                    transactions.push_back(_item.GetHex());
174
0
                }
175
0
            }
176
0
            obj.pushKV("txids", std::move(transactions));
177
0
            ret.push_back(std::move(obj));
178
0
        }
179
0
    };
180
181
0
    if (filtered_address) {
182
0
        const auto& entry = wallet.FindAddressBookEntry(*filtered_address, /*allow_change=*/false);
183
0
        if (entry) func(*filtered_address, entry->GetLabel(), entry->IsChange(), entry->purpose);
184
0
    } else {
185
        // No filtered addr, walk-through the addressbook entry
186
0
        wallet.ForEachAddrBookEntry(func);
187
0
    }
188
189
0
    if (by_label) {
190
0
        for (const auto& entry : label_tally) {
191
0
            CAmount nAmount = entry.second.nAmount;
192
0
            int nConf = entry.second.nConf;
193
0
            UniValue obj(UniValue::VOBJ);
194
0
            if (entry.second.fIsWatchonly)
195
0
                obj.pushKV("involvesWatchonly", true);
196
0
            obj.pushKV("amount",        ValueFromAmount(nAmount));
197
0
            obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
198
0
            obj.pushKV("label",         entry.first);
199
0
            ret.push_back(std::move(obj));
200
0
        }
201
0
    }
202
203
0
    return ret;
204
0
}
205
206
RPCHelpMan listreceivedbyaddress()
207
0
{
208
0
    return RPCHelpMan{"listreceivedbyaddress",
209
0
                "\nList balances by receiving address.\n",
210
0
                {
211
0
                    {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "The minimum number of confirmations before payments are included."},
212
0
                    {"include_empty", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to include addresses that haven't received any payments."},
213
0
                    {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Whether to include watch-only addresses (see 'importaddress')"},
214
0
                    {"address_filter", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "If present and non-empty, only return information on this address."},
215
0
                    {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase transactions."},
216
0
                },
217
0
                RPCResult{
218
0
                    RPCResult::Type::ARR, "", "",
219
0
                    {
220
0
                        {RPCResult::Type::OBJ, "", "",
221
0
                        {
222
0
                            {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction"},
223
0
                            {RPCResult::Type::STR, "address", "The receiving address"},
224
0
                            {RPCResult::Type::STR_AMOUNT, "amount", "The total amount in " + CURRENCY_UNIT + " received by the address"},
225
0
                            {RPCResult::Type::NUM, "confirmations", "The number of confirmations of the most recent transaction included"},
226
0
                            {RPCResult::Type::STR, "label", "The label of the receiving address. The default label is \"\""},
227
0
                            {RPCResult::Type::ARR, "txids", "",
228
0
                            {
229
0
                                {RPCResult::Type::STR_HEX, "txid", "The ids of transactions received with the address"},
230
0
                            }},
231
0
                        }},
232
0
                    }
233
0
                },
234
0
                RPCExamples{
235
0
                    HelpExampleCli("listreceivedbyaddress", "")
236
0
            + HelpExampleCli("listreceivedbyaddress", "6 true")
237
0
            + HelpExampleCli("listreceivedbyaddress", "6 true true \"\" true")
238
0
            + HelpExampleRpc("listreceivedbyaddress", "6, true, true")
239
0
            + HelpExampleRpc("listreceivedbyaddress", "6, true, true, \"" + EXAMPLE_ADDRESS[0] + "\", true")
240
0
                },
241
0
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
242
0
{
243
0
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
244
0
    if (!pwallet) return UniValue::VNULL;
245
246
    // Make sure the results are valid at least up to the most recent block
247
    // the user could have gotten from another RPC command prior to now
248
0
    pwallet->BlockUntilSyncedToCurrentChain();
249
250
0
    const bool include_immature_coinbase{request.params[4].isNull() ? false : request.params[4].get_bool()};
251
252
0
    LOCK(pwallet->cs_wallet);
Line
Count
Source
257
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
253
254
0
    return ListReceived(*pwallet, request.params, false, include_immature_coinbase);
255
0
},
256
0
    };
257
0
}
258
259
RPCHelpMan listreceivedbylabel()
260
0
{
261
0
    return RPCHelpMan{"listreceivedbylabel",
262
0
                "\nList received transactions by label.\n",
263
0
                {
264
0
                    {"minconf", RPCArg::Type::NUM, RPCArg::Default{1}, "The minimum number of confirmations before payments are included."},
265
0
                    {"include_empty", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether to include labels that haven't received any payments."},
266
0
                    {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Whether to include watch-only addresses (see 'importaddress')"},
267
0
                    {"include_immature_coinbase", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include immature coinbase transactions."},
268
0
                },
269
0
                RPCResult{
270
0
                    RPCResult::Type::ARR, "", "",
271
0
                    {
272
0
                        {RPCResult::Type::OBJ, "", "",
273
0
                        {
274
0
                            {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction"},
275
0
                            {RPCResult::Type::STR_AMOUNT, "amount", "The total amount received by addresses with this label"},
276
0
                            {RPCResult::Type::NUM, "confirmations", "The number of confirmations of the most recent transaction included"},
277
0
                            {RPCResult::Type::STR, "label", "The label of the receiving address. The default label is \"\""},
278
0
                        }},
279
0
                    }
280
0
                },
281
0
                RPCExamples{
282
0
                    HelpExampleCli("listreceivedbylabel", "")
283
0
            + HelpExampleCli("listreceivedbylabel", "6 true")
284
0
            + HelpExampleRpc("listreceivedbylabel", "6, true, true, true")
285
0
                },
286
0
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
287
0
{
288
0
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
289
0
    if (!pwallet) return UniValue::VNULL;
290
291
    // Make sure the results are valid at least up to the most recent block
292
    // the user could have gotten from another RPC command prior to now
293
0
    pwallet->BlockUntilSyncedToCurrentChain();
294
295
0
    const bool include_immature_coinbase{request.params[3].isNull() ? false : request.params[3].get_bool()};
296
297
0
    LOCK(pwallet->cs_wallet);
Line
Count
Source
257
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
298
299
0
    return ListReceived(*pwallet, request.params, true, include_immature_coinbase);
300
0
},
301
0
    };
302
0
}
303
304
static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
305
0
{
306
0
    if (IsValidDestination(dest)) {
307
0
        entry.pushKV("address", EncodeDestination(dest));
308
0
    }
309
0
}
310
311
/**
312
 * List transactions based on the given criteria.
313
 *
314
 * @param  wallet         The wallet.
315
 * @param  wtx            The wallet transaction.
316
 * @param  nMinDepth      The minimum confirmation depth.
317
 * @param  fLong          Whether to include the JSON version of the transaction.
318
 * @param  ret            The vector into which the result is stored.
319
 * @param  filter_ismine  The "is mine" filter flags.
320
 * @param  filter_label   Optional label string to filter incoming transactions.
321
 */
322
template <class Vec>
323
static void ListTransactions(const CWallet& wallet, const CWalletTx& wtx, int nMinDepth, bool fLong,
324
                             Vec& ret, const isminefilter& filter_ismine, const std::optional<std::string>& filter_label,
325
                             bool include_change = false)
326
    EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
327
0
{
328
0
    CAmount nFee;
329
0
    std::list<COutputEntry> listReceived;
330
0
    std::list<COutputEntry> listSent;
331
332
0
    CachedTxGetAmounts(wallet, wtx, listReceived, listSent, nFee, filter_ismine, include_change);
333
334
0
    bool involvesWatchonly = CachedTxIsFromMe(wallet, wtx, ISMINE_WATCH_ONLY);
335
336
    // Sent
337
0
    if (!filter_label.has_value())
338
0
    {
339
0
        for (const COutputEntry& s : listSent)
340
0
        {
341
0
            UniValue entry(UniValue::VOBJ);
342
0
            if (involvesWatchonly || (wallet.IsMine(s.destination) & ISMINE_WATCH_ONLY)) {
343
0
                entry.pushKV("involvesWatchonly", true);
344
0
            }
345
0
            MaybePushAddress(entry, s.destination);
346
0
            entry.pushKV("category", "send");
347
0
            entry.pushKV("amount", ValueFromAmount(-s.amount));
348
0
            const auto* address_book_entry = wallet.FindAddressBookEntry(s.destination);
349
0
            if (address_book_entry) {
350
0
                entry.pushKV("label", address_book_entry->GetLabel());
351
0
            }
352
0
            entry.pushKV("vout", s.vout);
353
0
            entry.pushKV("fee", ValueFromAmount(-nFee));
354
0
            if (fLong)
355
0
                WalletTxToJSON(wallet, wtx, entry);
356
0
            entry.pushKV("abandoned", wtx.isAbandoned());
357
0
            ret.push_back(std::move(entry));
358
0
        }
359
0
    }
360
361
    // Received
362
0
    if (listReceived.size() > 0 && wallet.GetTxDepthInMainChain(wtx) >= nMinDepth) {
363
0
        for (const COutputEntry& r : listReceived)
364
0
        {
365
0
            std::string label;
366
0
            const auto* address_book_entry = wallet.FindAddressBookEntry(r.destination);
367
0
            if (address_book_entry) {
368
0
                label = address_book_entry->GetLabel();
369
0
            }
370
0
            if (filter_label.has_value() && label != filter_label.value()) {
371
0
                continue;
372
0
            }
373
0
            UniValue entry(UniValue::VOBJ);
374
0
            if (involvesWatchonly || (wallet.IsMine(r.destination) & ISMINE_WATCH_ONLY)) {
375
0
                entry.pushKV("involvesWatchonly", true);
376
0
            }
377
0
            MaybePushAddress(entry, r.destination);
378
0
            PushParentDescriptors(wallet, wtx.tx->vout.at(r.vout).scriptPubKey, entry);
379
0
            if (wtx.IsCoinBase())
380
0
            {
381
0
                if (wallet.GetTxDepthInMainChain(wtx) < 1)
382
0
                    entry.pushKV("category", "orphan");
383
0
                else if (wallet.IsTxImmatureCoinBase(wtx))
384
0
                    entry.pushKV("category", "immature");
385
0
                else
386
0
                    entry.pushKV("category", "generate");
387
0
            }
388
0
            else
389
0
            {
390
0
                entry.pushKV("category", "receive");
391
0
            }
392
0
            entry.pushKV("amount", ValueFromAmount(r.amount));
393
0
            if (address_book_entry) {
394
0
                entry.pushKV("label", label);
395
0
            }
396
0
            entry.pushKV("vout", r.vout);
397
0
            entry.pushKV("abandoned", wtx.isAbandoned());
398
0
            if (fLong)
399
0
                WalletTxToJSON(wallet, wtx, entry);
400
0
            ret.push_back(std::move(entry));
401
0
        }
402
0
    }
403
0
}
Unexecuted instantiation: transactions.cpp:_ZN6walletL16ListTransactionsINSt3__16vectorI8UniValueNS1_9allocatorIS3_EEEEEEvRKNS_7CWalletERKNS_9CWalletTxEibRT_RKjRKNS1_8optionalINS1_12basic_stringIcNS1_11char_traitsIcEENS4_IcEEEEEEb
Unexecuted instantiation: transactions.cpp:_ZN6walletL16ListTransactionsI8UniValueEEvRKNS_7CWalletERKNS_9CWalletTxEibRT_RKjRKNSt3__18optionalINSC_12basic_stringIcNSC_11char_traitsIcEENSC_9allocatorIcEEEEEEb
404
405
406
static std::vector<RPCResult> TransactionDescriptionString()
407
0
{
408
0
    return{{RPCResult::Type::NUM, "confirmations", "The number of confirmations for the transaction. Negative confirmations means the\n"
409
0
               "transaction conflicted that many blocks ago."},
410
0
           {RPCResult::Type::BOOL, "generated", /*optional=*/true, "Only present if the transaction's only input is a coinbase one."},
411
0
           {RPCResult::Type::BOOL, "trusted", /*optional=*/true, "Whether we consider the transaction to be trusted and safe to spend from.\n"
412
0
                "Only present when the transaction has 0 confirmations (or negative confirmations, if conflicted)."},
413
0
           {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "The block hash containing the transaction."},
414
0
           {RPCResult::Type::NUM, "blockheight", /*optional=*/true, "The block height containing the transaction."},
415
0
           {RPCResult::Type::NUM, "blockindex", /*optional=*/true, "The index of the transaction in the block that includes it."},
416
0
           {RPCResult::Type::NUM_TIME, "blocktime", /*optional=*/true, "The block time expressed in " + UNIX_EPOCH_TIME + "."},
417
0
           {RPCResult::Type::STR_HEX, "txid", "The transaction id."},
418
0
           {RPCResult::Type::STR_HEX, "wtxid", "The hash of serialized transaction, including witness data."},
419
0
           {RPCResult::Type::ARR, "walletconflicts", "Confirmed transactions that have been detected by the wallet to conflict with this transaction.",
420
0
           {
421
0
               {RPCResult::Type::STR_HEX, "txid", "The transaction id."},
422
0
           }},
423
0
           {RPCResult::Type::STR_HEX, "replaced_by_txid", /*optional=*/true, "Only if 'category' is 'send'. The txid if this tx was replaced."},
424
0
           {RPCResult::Type::STR_HEX, "replaces_txid", /*optional=*/true, "Only if 'category' is 'send'. The txid if this tx replaces another."},
425
0
           {RPCResult::Type::ARR, "mempoolconflicts", "Transactions in the mempool that directly conflict with either this transaction or an ancestor transaction",
426
0
           {
427
0
               {RPCResult::Type::STR_HEX, "txid", "The transaction id."},
428
0
           }},
429
0
           {RPCResult::Type::STR, "to", /*optional=*/true, "If a comment to is associated with the transaction."},
430
0
           {RPCResult::Type::NUM_TIME, "time", "The transaction time expressed in " + UNIX_EPOCH_TIME + "."},
431
0
           {RPCResult::Type::NUM_TIME, "timereceived", "The time received expressed in " + UNIX_EPOCH_TIME + "."},
432
0
           {RPCResult::Type::STR, "comment", /*optional=*/true, "If a comment is associated with the transaction, only present if not empty."},
433
0
           {RPCResult::Type::STR, "bip125-replaceable", "(\"yes|no|unknown\") Whether this transaction signals BIP125 replaceability or has an unconfirmed ancestor signaling BIP125 replaceability.\n"
434
0
               "May be unknown for unconfirmed transactions not in the mempool because their unconfirmed ancestors are unknown."},
435
0
           {RPCResult::Type::ARR, "parent_descs", /*optional=*/true, "Only if 'category' is 'received'. List of parent descriptors for the output script of this coin.", {
436
0
               {RPCResult::Type::STR, "desc", "The descriptor string."},
437
0
           }},
438
0
           };
439
0
}
440
441
RPCHelpMan listtransactions()
442
0
{
443
0
    return RPCHelpMan{"listtransactions",
444
0
                "\nIf a label name is provided, this will return only incoming transactions paying to addresses with the specified label.\n"
445
0
                "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions.\n",
446
0
                {
447
0
                    {"label", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "If set, should be a valid label name to return only incoming transactions\n"
448
0
                          "with the specified label, or \"*\" to disable filtering and return all transactions."},
449
0
                    {"count", RPCArg::Type::NUM, RPCArg::Default{10}, "The number of transactions to return"},
450
0
                    {"skip", RPCArg::Type::NUM, RPCArg::Default{0}, "The number of transactions to skip"},
451
0
                    {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Include transactions to watch-only addresses (see 'importaddress')"},
452
0
                },
453
0
                RPCResult{
454
0
                    RPCResult::Type::ARR, "", "",
455
0
                    {
456
0
                        {RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>(
457
0
                        {
458
0
                            {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction."},
459
0
                            {RPCResult::Type::STR, "address",  /*optional=*/true, "The bitcoin address of the transaction (not returned if the output does not have an address, e.g. OP_RETURN null data)."},
460
0
                            {RPCResult::Type::STR, "category", "The transaction category.\n"
461
0
                                "\"send\"                  Transactions sent.\n"
462
0
                                "\"receive\"               Non-coinbase transactions received.\n"
463
0
                                "\"generate\"              Coinbase transactions received with more than 100 confirmations.\n"
464
0
                                "\"immature\"              Coinbase transactions received with 100 or fewer confirmations.\n"
465
0
                                "\"orphan\"                Orphaned coinbase transactions received."},
466
0
                            {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n"
467
0
                                "for all other categories"},
468
0
                            {RPCResult::Type::STR, "label", /*optional=*/true, "A comment for the address/transaction, if any"},
469
0
                            {RPCResult::Type::NUM, "vout", "the vout value"},
470
0
                            {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
471
0
                                 "'send' category of transactions."},
472
0
                        },
473
0
                        TransactionDescriptionString()),
474
0
                        {
475
0
                            {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable)."},
476
0
                        })},
477
0
                    }
478
0
                },
479
0
                RPCExamples{
480
0
            "\nList the most recent 10 transactions in the systems\n"
481
0
            + HelpExampleCli("listtransactions", "") +
482
0
            "\nList transactions 100 to 120\n"
483
0
            + HelpExampleCli("listtransactions", "\"*\" 20 100") +
484
0
            "\nAs a JSON-RPC call\n"
485
0
            + HelpExampleRpc("listtransactions", "\"*\", 20, 100")
486
0
                },
487
0
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
488
0
{
489
0
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
490
0
    if (!pwallet) return UniValue::VNULL;
491
492
    // Make sure the results are valid at least up to the most recent block
493
    // the user could have gotten from another RPC command prior to now
494
0
    pwallet->BlockUntilSyncedToCurrentChain();
495
496
0
    std::optional<std::string> filter_label;
497
0
    if (!request.params[0].isNull() && request.params[0].get_str() != "*") {
498
0
        filter_label.emplace(LabelFromValue(request.params[0]));
499
0
        if (filter_label.value().empty()) {
500
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Label argument must be a valid label name or \"*\".");
501
0
        }
502
0
    }
503
0
    int nCount = 10;
504
0
    if (!request.params[1].isNull())
505
0
        nCount = request.params[1].getInt<int>();
506
0
    int nFrom = 0;
507
0
    if (!request.params[2].isNull())
508
0
        nFrom = request.params[2].getInt<int>();
509
0
    isminefilter filter = ISMINE_SPENDABLE;
510
511
0
    if (ParseIncludeWatchonly(request.params[3], *pwallet)) {
512
0
        filter |= ISMINE_WATCH_ONLY;
513
0
    }
514
515
0
    if (nCount < 0)
516
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
517
0
    if (nFrom < 0)
518
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
519
520
0
    std::vector<UniValue> ret;
521
0
    {
522
0
        LOCK(pwallet->cs_wallet);
Line
Count
Source
257
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
523
524
0
        const CWallet::TxItems & txOrdered = pwallet->wtxOrdered;
525
526
        // iterate backwards until we have nCount items to return:
527
0
        for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
528
0
        {
529
0
            CWalletTx *const pwtx = (*it).second;
530
0
            ListTransactions(*pwallet, *pwtx, 0, true, ret, filter, filter_label);
531
0
            if ((int)ret.size() >= (nCount+nFrom)) break;
532
0
        }
533
0
    }
534
535
    // ret is newest to oldest
536
537
0
    if (nFrom > (int)ret.size())
538
0
        nFrom = ret.size();
539
0
    if ((nFrom + nCount) > (int)ret.size())
540
0
        nCount = ret.size() - nFrom;
541
542
0
    auto txs_rev_it{std::make_move_iterator(ret.rend())};
543
0
    UniValue result{UniValue::VARR};
544
0
    result.push_backV(txs_rev_it - nFrom - nCount, txs_rev_it - nFrom); // Return oldest to newest
545
0
    return result;
546
0
},
547
0
    };
548
0
}
549
550
RPCHelpMan listsinceblock()
551
0
{
552
0
    return RPCHelpMan{"listsinceblock",
553
0
                "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted.\n"
554
0
                "If \"blockhash\" is no longer a part of the main chain, transactions from the fork point onward are included.\n"
555
0
                "Additionally, if include_removed is set, transactions affecting the wallet which were removed are returned in the \"removed\" array.\n",
556
0
                {
557
0
                    {"blockhash", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "If set, the block hash to list transactions since, otherwise list all transactions."},
558
0
                    {"target_confirmations", RPCArg::Type::NUM, RPCArg::Default{1}, "Return the nth block hash from the main chain. e.g. 1 would mean the best block hash. Note: this is not used as a filter, but only affects [lastblock] in the return value"},
559
0
                    {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Include transactions to watch-only addresses (see 'importaddress')"},
560
0
                    {"include_removed", RPCArg::Type::BOOL, RPCArg::Default{true}, "Show transactions that were removed due to a reorg in the \"removed\" array\n"
561
0
                                                                       "(not guaranteed to work on pruned nodes)"},
562
0
                    {"include_change", RPCArg::Type::BOOL, RPCArg::Default{false}, "Also add entries for change outputs.\n"},
563
0
                    {"label", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Return only incoming transactions paying to addresses with the specified label.\n"},
564
0
                },
565
0
                RPCResult{
566
0
                    RPCResult::Type::OBJ, "", "",
567
0
                    {
568
0
                        {RPCResult::Type::ARR, "transactions", "",
569
0
                        {
570
0
                            {RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>(
571
0
                            {
572
0
                                {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction."},
573
0
                                {RPCResult::Type::STR, "address",  /*optional=*/true, "The bitcoin address of the transaction (not returned if the output does not have an address, e.g. OP_RETURN null data)."},
574
0
                                {RPCResult::Type::STR, "category", "The transaction category.\n"
575
0
                                    "\"send\"                  Transactions sent.\n"
576
0
                                    "\"receive\"               Non-coinbase transactions received.\n"
577
0
                                    "\"generate\"              Coinbase transactions received with more than 100 confirmations.\n"
578
0
                                    "\"immature\"              Coinbase transactions received with 100 or fewer confirmations.\n"
579
0
                                    "\"orphan\"                Orphaned coinbase transactions received."},
580
0
                                {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n"
581
0
                                    "for all other categories"},
582
0
                                {RPCResult::Type::NUM, "vout", "the vout value"},
583
0
                                {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
584
0
                                     "'send' category of transactions."},
585
0
                            },
586
0
                            TransactionDescriptionString()),
587
0
                            {
588
0
                                {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable)."},
589
0
                                {RPCResult::Type::STR, "label", /*optional=*/true, "A comment for the address/transaction, if any"},
590
0
                            })},
591
0
                        }},
592
0
                        {RPCResult::Type::ARR, "removed", /*optional=*/true, "<structure is the same as \"transactions\" above, only present if include_removed=true>\n"
593
0
                            "Note: transactions that were re-added in the active chain will appear as-is in this array, and may thus have a positive confirmation count."
594
0
                        , {{RPCResult::Type::ELISION, "", ""},}},
595
0
                        {RPCResult::Type::STR_HEX, "lastblock", "The hash of the block (target_confirmations-1) from the best block on the main chain, or the genesis hash if the referenced block does not exist yet. This is typically used to feed back into listsinceblock the next time you call it. So you would generally use a target_confirmations of say 6, so you will be continually re-notified of transactions until they've reached 6 confirmations plus any new ones"},
596
0
                    }
597
0
                },
598
0
                RPCExamples{
599
0
                    HelpExampleCli("listsinceblock", "")
600
0
            + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
601
0
            + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
602
0
                },
603
0
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
604
0
{
605
0
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
606
0
    if (!pwallet) return UniValue::VNULL;
607
608
0
    const CWallet& wallet = *pwallet;
609
    // Make sure the results are valid at least up to the most recent block
610
    // the user could have gotten from another RPC command prior to now
611
0
    wallet.BlockUntilSyncedToCurrentChain();
612
613
0
    LOCK(wallet.cs_wallet);
Line
Count
Source
257
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
614
615
0
    std::optional<int> height;    // Height of the specified block or the common ancestor, if the block provided was in a deactivated chain.
616
0
    std::optional<int> altheight; // Height of the specified block, even if it's in a deactivated chain.
617
0
    int target_confirms = 1;
618
0
    isminefilter filter = ISMINE_SPENDABLE;
619
620
0
    uint256 blockId;
621
0
    if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
622
0
        blockId = ParseHashV(request.params[0], "blockhash");
623
0
        height = int{};
624
0
        altheight = int{};
625
0
        if (!wallet.chain().findCommonAncestor(blockId, wallet.GetLastBlockHash(), /*ancestor_out=*/FoundBlock().height(*height), /*block1_out=*/FoundBlock().height(*altheight))) {
626
0
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
627
0
        }
628
0
    }
629
630
0
    if (!request.params[1].isNull()) {
631
0
        target_confirms = request.params[1].getInt<int>();
632
633
0
        if (target_confirms < 1) {
634
0
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
635
0
        }
636
0
    }
637
638
0
    if (ParseIncludeWatchonly(request.params[2], wallet)) {
639
0
        filter |= ISMINE_WATCH_ONLY;
640
0
    }
641
642
0
    bool include_removed = (request.params[3].isNull() || request.params[3].get_bool());
643
0
    bool include_change = (!request.params[4].isNull() && request.params[4].get_bool());
644
645
    // Only set it if 'label' was provided.
646
0
    std::optional<std::string> filter_label;
647
0
    if (!request.params[5].isNull()) filter_label.emplace(LabelFromValue(request.params[5]));
648
649
0
    int depth = height ? wallet.GetLastBlockHeight() + 1 - *height : -1;
650
651
0
    UniValue transactions(UniValue::VARR);
652
653
0
    for (const std::pair<const uint256, CWalletTx>& pairWtx : wallet.mapWallet) {
654
0
        const CWalletTx& tx = pairWtx.second;
655
656
0
        if (depth == -1 || abs(wallet.GetTxDepthInMainChain(tx)) < depth) {
657
0
            ListTransactions(wallet, tx, 0, true, transactions, filter, filter_label, include_change);
658
0
        }
659
0
    }
660
661
    // when a reorg'd block is requested, we also list any relevant transactions
662
    // in the blocks of the chain that was detached
663
0
    UniValue removed(UniValue::VARR);
664
0
    while (include_removed && altheight && *altheight > *height) {
665
0
        CBlock block;
666
0
        if (!wallet.chain().findBlock(blockId, FoundBlock().data(block)) || block.IsNull()) {
667
0
            throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
668
0
        }
669
0
        for (const CTransactionRef& tx : block.vtx) {
670
0
            auto it = wallet.mapWallet.find(tx->GetHash());
671
0
            if (it != wallet.mapWallet.end()) {
672
                // We want all transactions regardless of confirmation count to appear here,
673
                // even negative confirmation ones, hence the big negative.
674
0
                ListTransactions(wallet, it->second, -100000000, true, removed, filter, filter_label, include_change);
675
0
            }
676
0
        }
677
0
        blockId = block.hashPrevBlock;
678
0
        --*altheight;
679
0
    }
680
681
0
    uint256 lastblock;
682
0
    target_confirms = std::min(target_confirms, wallet.GetLastBlockHeight() + 1);
683
0
    CHECK_NONFATAL(wallet.chain().findAncestorByHeight(wallet.GetLastBlockHash(), wallet.GetLastBlockHeight() + 1 - target_confirms, FoundBlock().hash(lastblock)));
Line
Count
Source
103
0
    inline_check_non_fatal(condition, __FILE__, __LINE__, __func__, #condition)
684
685
0
    UniValue ret(UniValue::VOBJ);
686
0
    ret.pushKV("transactions", std::move(transactions));
687
0
    if (include_removed) ret.pushKV("removed", std::move(removed));
688
0
    ret.pushKV("lastblock", lastblock.GetHex());
689
690
0
    return ret;
691
0
},
692
0
    };
693
0
}
694
695
RPCHelpMan gettransaction()
696
0
{
697
0
    return RPCHelpMan{"gettransaction",
698
0
                "\nGet detailed information about in-wallet transaction <txid>\n",
699
0
                {
700
0
                    {"txid", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction id"},
701
0
                    {"include_watchonly", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"},
702
0
                            "Whether to include watch-only addresses in balance calculation and details[]"},
703
0
                    {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false},
704
0
                            "Whether to include a `decoded` field containing the decoded transaction (equivalent to RPC decoderawtransaction)"},
705
0
                },
706
0
                RPCResult{
707
0
                    RPCResult::Type::OBJ, "", "", Cat(Cat<std::vector<RPCResult>>(
708
0
                    {
709
0
                        {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT},
710
0
                        {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the\n"
711
0
                                     "'send' category of transactions."},
712
0
                    },
713
0
                    TransactionDescriptionString()),
714
0
                    {
715
0
                        {RPCResult::Type::ARR, "details", "",
716
0
                        {
717
0
                            {RPCResult::Type::OBJ, "", "",
718
0
                            {
719
0
                                {RPCResult::Type::BOOL, "involvesWatchonly", /*optional=*/true, "Only returns true if imported addresses were involved in transaction."},
720
0
                                {RPCResult::Type::STR, "address", /*optional=*/true, "The bitcoin address involved in the transaction."},
721
0
                                {RPCResult::Type::STR, "category", "The transaction category.\n"
722
0
                                    "\"send\"                  Transactions sent.\n"
723
0
                                    "\"receive\"               Non-coinbase transactions received.\n"
724
0
                                    "\"generate\"              Coinbase transactions received with more than 100 confirmations.\n"
725
0
                                    "\"immature\"              Coinbase transactions received with 100 or fewer confirmations.\n"
726
0
                                    "\"orphan\"                Orphaned coinbase transactions received."},
727
0
                                {RPCResult::Type::STR_AMOUNT, "amount", "The amount in " + CURRENCY_UNIT},
728
0
                                {RPCResult::Type::STR, "label", /*optional=*/true, "A comment for the address/transaction, if any"},
729
0
                                {RPCResult::Type::NUM, "vout", "the vout value"},
730
0
                                {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
731
0
                                    "'send' category of transactions."},
732
0
                                {RPCResult::Type::BOOL, "abandoned", "'true' if the transaction has been abandoned (inputs are respendable)."},
733
0
                                {RPCResult::Type::ARR, "parent_descs", /*optional=*/true, "Only if 'category' is 'received'. List of parent descriptors for the output script of this coin.", {
734
0
                                    {RPCResult::Type::STR, "desc", "The descriptor string."},
735
0
                                }},
736
0
                            }},
737
0
                        }},
738
0
                        {RPCResult::Type::STR_HEX, "hex", "Raw data for transaction"},
739
0
                        {RPCResult::Type::OBJ, "decoded", /*optional=*/true, "The decoded transaction (only present when `verbose` is passed)",
740
0
                        {
741
0
                            {RPCResult::Type::ELISION, "", "Equivalent to the RPC decoderawtransaction method, or the RPC getrawtransaction method when `verbose` is passed."},
742
0
                        }},
743
0
                        RESULT_LAST_PROCESSED_BLOCK,
744
0
                    })
745
0
                },
746
0
                RPCExamples{
747
0
                    HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
748
0
            + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
749
0
            + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" false true")
750
0
            + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
751
0
                },
752
0
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
753
0
{
754
0
    const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
755
0
    if (!pwallet) return UniValue::VNULL;
756
757
    // Make sure the results are valid at least up to the most recent block
758
    // the user could have gotten from another RPC command prior to now
759
0
    pwallet->BlockUntilSyncedToCurrentChain();
760
761
0
    LOCK(pwallet->cs_wallet);
Line
Count
Source
257
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
762
763
0
    uint256 hash(ParseHashV(request.params[0], "txid"));
764
765
0
    isminefilter filter = ISMINE_SPENDABLE;
766
767
0
    if (ParseIncludeWatchonly(request.params[1], *pwallet)) {
768
0
        filter |= ISMINE_WATCH_ONLY;
769
0
    }
770
771
0
    bool verbose = request.params[2].isNull() ? false : request.params[2].get_bool();
772
773
0
    UniValue entry(UniValue::VOBJ);
774
0
    auto it = pwallet->mapWallet.find(hash);
775
0
    if (it == pwallet->mapWallet.end()) {
776
0
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
777
0
    }
778
0
    const CWalletTx& wtx = it->second;
779
780
0
    CAmount nCredit = CachedTxGetCredit(*pwallet, wtx, filter);
781
0
    CAmount nDebit = CachedTxGetDebit(*pwallet, wtx, filter);
782
0
    CAmount nNet = nCredit - nDebit;
783
0
    CAmount nFee = (CachedTxIsFromMe(*pwallet, wtx, filter) ? wtx.tx->GetValueOut() - nDebit : 0);
784
785
0
    entry.pushKV("amount", ValueFromAmount(nNet - nFee));
786
0
    if (CachedTxIsFromMe(*pwallet, wtx, filter))
787
0
        entry.pushKV("fee", ValueFromAmount(nFee));
788
789
0
    WalletTxToJSON(*pwallet, wtx, entry);
790
791
0
    UniValue details(UniValue::VARR);
792
0
    ListTransactions(*pwallet, wtx, 0, false, details, filter, /*filter_label=*/std::nullopt);
793
0
    entry.pushKV("details", std::move(details));
794
795
0
    entry.pushKV("hex", EncodeHexTx(*wtx.tx));
796
797
0
    if (verbose) {
798
0
        UniValue decoded(UniValue::VOBJ);
799
0
        TxToUniv(*wtx.tx, /*block_hash=*/uint256(), /*entry=*/decoded, /*include_hex=*/false);
800
0
        entry.pushKV("decoded", std::move(decoded));
801
0
    }
802
803
0
    AppendLastProcessedBlock(entry, *pwallet);
804
0
    return entry;
805
0
},
806
0
    };
807
0
}
808
809
RPCHelpMan abandontransaction()
810
0
{
811
0
    return RPCHelpMan{"abandontransaction",
812
0
                "\nMark in-wallet transaction <txid> as abandoned\n"
813
0
                "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
814
0
                "for their inputs to be respent.  It can be used to replace \"stuck\" or evicted transactions.\n"
815
0
                "It only works on transactions which are not included in a block and are not currently in the mempool.\n"
816
0
                "It has no effect on transactions which are already abandoned.\n",
817
0
                {
818
0
                    {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
819
0
                },
820
0
                RPCResult{RPCResult::Type::NONE, "", ""},
821
0
                RPCExamples{
822
0
                    HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
823
0
            + HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
824
0
                },
825
0
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
826
0
{
827
0
    std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
828
0
    if (!pwallet) return UniValue::VNULL;
829
830
    // Make sure the results are valid at least up to the most recent block
831
    // the user could have gotten from another RPC command prior to now
832
0
    pwallet->BlockUntilSyncedToCurrentChain();
833
834
0
    LOCK(pwallet->cs_wallet);
Line
Count
Source
257
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
835
836
0
    uint256 hash(ParseHashV(request.params[0], "txid"));
837
838
0
    if (!pwallet->mapWallet.count(hash)) {
839
0
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
840
0
    }
841
0
    if (!pwallet->AbandonTransaction(hash)) {
842
0
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment");
843
0
    }
844
845
0
    return UniValue::VNULL;
846
0
},
847
0
    };
848
0
}
849
850
RPCHelpMan rescanblockchain()
851
0
{
852
0
    return RPCHelpMan{"rescanblockchain",
853
0
                "\nRescan the local blockchain for wallet related transactions.\n"
854
0
                "Note: Use \"getwalletinfo\" to query the scanning progress.\n"
855
0
                "The rescan is significantly faster when used on a descriptor wallet\n"
856
0
                "and block filters are available (using startup option \"-blockfilterindex=1\").\n",
857
0
                {
858
0
                    {"start_height", RPCArg::Type::NUM, RPCArg::Default{0}, "block height where the rescan should start"},
859
0
                    {"stop_height", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "the last block height that should be scanned. If none is provided it will rescan up to the tip at return time of this call."},
860
0
                },
861
0
                RPCResult{
862
0
                    RPCResult::Type::OBJ, "", "",
863
0
                    {
864
0
                        {RPCResult::Type::NUM, "start_height", "The block height where the rescan started (the requested height or 0)"},
865
0
                        {RPCResult::Type::NUM, "stop_height", "The height of the last rescanned block. May be null in rare cases if there was a reorg and the call didn't scan any blocks because they were already scanned in the background."},
866
0
                    }
867
0
                },
868
0
                RPCExamples{
869
0
                    HelpExampleCli("rescanblockchain", "100000 120000")
870
0
            + HelpExampleRpc("rescanblockchain", "100000, 120000")
871
0
                },
872
0
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
873
0
{
874
0
    std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
875
0
    if (!pwallet) return UniValue::VNULL;
876
0
    CWallet& wallet{*pwallet};
877
878
    // Make sure the results are valid at least up to the most recent block
879
    // the user could have gotten from another RPC command prior to now
880
0
    wallet.BlockUntilSyncedToCurrentChain();
881
882
0
    WalletRescanReserver reserver(*pwallet);
883
0
    if (!reserver.reserve(/*with_passphrase=*/true)) {
884
0
        throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
885
0
    }
886
887
0
    int start_height = 0;
888
0
    std::optional<int> stop_height;
889
0
    uint256 start_block;
890
891
0
    LOCK(pwallet->m_relock_mutex);
Line
Count
Source
257
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
892
0
    {
893
0
        LOCK(pwallet->cs_wallet);
Line
Count
Source
257
0
#define LOCK(cs) UniqueLock UNIQUE_NAME(criticalblock)(MaybeCheckNotHeld(cs), #cs, __FILE__, __LINE__)
Line
Count
Source
11
0
#define UNIQUE_NAME(name) PASTE2(name, __COUNTER__)
Line
Count
Source
9
0
#define PASTE2(x, y) PASTE(x, y)
Line
Count
Source
8
0
#define PASTE(x, y) x ## y
894
0
        EnsureWalletIsUnlocked(*pwallet);
895
0
        int tip_height = pwallet->GetLastBlockHeight();
896
897
0
        if (!request.params[0].isNull()) {
898
0
            start_height = request.params[0].getInt<int>();
899
0
            if (start_height < 0 || start_height > tip_height) {
900
0
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid start_height");
901
0
            }
902
0
        }
903
904
0
        if (!request.params[1].isNull()) {
905
0
            stop_height = request.params[1].getInt<int>();
906
0
            if (*stop_height < 0 || *stop_height > tip_height) {
907
0
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid stop_height");
908
0
            } else if (*stop_height < start_height) {
909
0
                throw JSONRPCError(RPC_INVALID_PARAMETER, "stop_height must be greater than start_height");
910
0
            }
911
0
        }
912
913
        // We can't rescan unavailable blocks, stop and throw an error
914
0
        if (!pwallet->chain().hasBlocks(pwallet->GetLastBlockHash(), start_height, stop_height)) {
915
0
            if (pwallet->chain().havePruned() && pwallet->chain().getPruneHeight() >= start_height) {
916
0
                throw JSONRPCError(RPC_MISC_ERROR, "Can't rescan beyond pruned data. Use RPC call getblockchaininfo to determine your pruned height.");
917
0
            }
918
0
            if (pwallet->chain().hasAssumedValidChain()) {
919
0
                throw JSONRPCError(RPC_MISC_ERROR, "Failed to rescan unavailable blocks likely due to an in-progress assumeutxo background sync. Check logs or getchainstates RPC for assumeutxo background sync progress and try again later.");
920
0
            }
921
0
            throw JSONRPCError(RPC_MISC_ERROR, "Failed to rescan unavailable blocks, potentially caused by data corruption. If the issue persists you may want to reindex (see -reindex option).");
922
0
        }
923
924
0
        CHECK_NONFATAL(pwallet->chain().findAncestorByHeight(pwallet->GetLastBlockHash(), start_height, FoundBlock().hash(start_block)));
Line
Count
Source
103
0
    inline_check_non_fatal(condition, __FILE__, __LINE__, __func__, #condition)
925
0
    }
926
927
0
    CWallet::ScanResult result =
928
0
        pwallet->ScanForWalletTransactions(start_block, start_height, stop_height, reserver, /*fUpdate=*/true, /*save_progress=*/false);
929
0
    switch (result.status) {
930
0
    case CWallet::ScanResult::SUCCESS:
931
0
        break;
932
0
    case CWallet::ScanResult::FAILURE:
933
0
        throw JSONRPCError(RPC_MISC_ERROR, "Rescan failed. Potentially corrupted data files.");
934
0
    case CWallet::ScanResult::USER_ABORT:
935
0
        throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted.");
936
        // no default case, so the compiler can warn about missing cases
937
0
    }
938
0
    UniValue response(UniValue::VOBJ);
939
0
    response.pushKV("start_height", start_height);
940
0
    response.pushKV("stop_height", result.last_scanned_height ? *result.last_scanned_height : UniValue());
941
0
    return response;
942
0
},
943
0
    };
944
0
}
945
946
RPCHelpMan abortrescan()
947
0
{
948
0
    return RPCHelpMan{"abortrescan",
949
0
                "\nStops current wallet rescan triggered by an RPC call, e.g. by an rescanblockchain call.\n"
950
0
                "Note: Use \"getwalletinfo\" to query the scanning progress.\n",
951
0
                {},
952
0
                RPCResult{RPCResult::Type::BOOL, "", "Whether the abort was successful"},
953
0
                RPCExamples{
954
0
            "\nImport a private key\n"
955
0
            + HelpExampleCli("rescanblockchain", "") +
956
0
            "\nAbort the running wallet rescan\n"
957
0
            + HelpExampleCli("abortrescan", "") +
958
0
            "\nAs a JSON-RPC call\n"
959
0
            + HelpExampleRpc("abortrescan", "")
960
0
                },
961
0
        [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
962
0
{
963
0
    std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
964
0
    if (!pwallet) return UniValue::VNULL;
965
966
0
    if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false;
967
0
    pwallet->AbortRescan();
968
0
    return true;
969
0
},
970
0
    };
971
0
}
972
} // namespace wallet