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