Bitcoin Core 29.99.0
P2P Digital Currency
backup.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-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 <chain.h>
6#include <clientversion.h>
7#include <core_io.h>
8#include <hash.h>
9#include <interfaces/chain.h>
10#include <key_io.h>
11#include <merkleblock.h>
12#include <rpc/util.h>
13#include <script/descriptor.h>
14#include <script/script.h>
15#include <script/solver.h>
16#include <sync.h>
17#include <uint256.h>
18#include <util/bip32.h>
19#include <util/fs.h>
20#include <util/time.h>
21#include <util/translation.h>
22#include <wallet/rpc/util.h>
23#include <wallet/wallet.h>
24
25#include <cstdint>
26#include <fstream>
27#include <tuple>
28#include <string>
29
30#include <univalue.h>
31
32
33
35
36namespace wallet {
38{
39 return RPCHelpMan{
40 "importprunedfunds",
41 "Imports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n",
42 {
43 {"rawtransaction", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A raw transaction in hex funding an already-existing address in wallet"},
44 {"txoutproof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex output from gettxoutproof that contains the transaction"},
45 },
47 RPCExamples{""},
48 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
49{
50 std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
51 if (!pwallet) return UniValue::VNULL;
52
54 if (!DecodeHexTx(tx, request.params[0].get_str())) {
55 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
56 }
57
58 DataStream ssMB{ParseHexV(request.params[1], "proof")};
59 CMerkleBlock merkleBlock;
60 ssMB >> merkleBlock;
61
62 //Search partial merkle tree in proof for our transaction and index in valid block
63 std::vector<uint256> vMatch;
64 std::vector<unsigned int> vIndex;
65 if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) {
66 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
67 }
68
69 LOCK(pwallet->cs_wallet);
70 int height;
71 if (!pwallet->chain().findAncestorByHash(pwallet->GetLastBlockHash(), merkleBlock.header.GetHash(), FoundBlock().height(height))) {
72 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
73 }
74
75 std::vector<uint256>::const_iterator it;
76 if ((it = std::find(vMatch.begin(), vMatch.end(), tx.GetHash())) == vMatch.end()) {
77 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
78 }
79
80 unsigned int txnIndex = vIndex[it - vMatch.begin()];
81
83 if (pwallet->IsMine(*tx_ref)) {
84 pwallet->AddToWallet(std::move(tx_ref), TxStateConfirmed{merkleBlock.header.GetHash(), height, static_cast<int>(txnIndex)});
85 return UniValue::VNULL;
86 }
87
88 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
89},
90 };
91}
92
94{
95 return RPCHelpMan{
96 "removeprunedfunds",
97 "Deletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\n",
98 {
99 {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex-encoded id of the transaction you are deleting"},
100 },
103 HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
104 "\nAs a JSON-RPC call\n"
105 + HelpExampleRpc("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"")
106 },
107 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
108{
109 std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
110 if (!pwallet) return UniValue::VNULL;
111
112 LOCK(pwallet->cs_wallet);
113
114 Txid hash{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
115 std::vector<Txid> vHash;
116 vHash.push_back(hash);
117 if (auto res = pwallet->RemoveTxs(vHash); !res) {
118 throw JSONRPCError(RPC_WALLET_ERROR, util::ErrorString(res).original);
119 }
120
121 return UniValue::VNULL;
122},
123 };
124}
125
126static int64_t GetImportTimestamp(const UniValue& data, int64_t now)
127{
128 if (data.exists("timestamp")) {
129 const UniValue& timestamp = data["timestamp"];
130 if (timestamp.isNum()) {
131 return timestamp.getInt<int64_t>();
132 } else if (timestamp.isStr() && timestamp.get_str() == "now") {
133 return now;
134 }
135 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
136 }
137 throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
138}
139
140static UniValue ProcessDescriptorImport(CWallet& wallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
141{
142 UniValue warnings(UniValue::VARR);
143 UniValue result(UniValue::VOBJ);
144
145 try {
146 if (!data.exists("desc")) {
147 throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor not found.");
148 }
149
150 const std::string& descriptor = data["desc"].get_str();
151 const bool active = data.exists("active") ? data["active"].get_bool() : false;
152 const std::string label{LabelFromValue(data["label"])};
153
154 // Parse descriptor string
156 std::string error;
157 auto parsed_descs = Parse(descriptor, keys, error, /* require_checksum = */ true);
158 if (parsed_descs.empty()) {
160 }
161 std::optional<bool> internal;
162 if (data.exists("internal")) {
163 if (parsed_descs.size() > 1) {
164 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot have multipath descriptor while also specifying \'internal\'");
165 }
166 internal = data["internal"].get_bool();
167 }
168
169 // Range check
170 int64_t range_start = 0, range_end = 1, next_index = 0;
171 if (!parsed_descs.at(0)->IsRange() && data.exists("range")) {
172 throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
173 } else if (parsed_descs.at(0)->IsRange()) {
174 if (data.exists("range")) {
175 auto range = ParseDescriptorRange(data["range"]);
176 range_start = range.first;
177 range_end = range.second + 1; // Specified range end is inclusive, but we need range end as exclusive
178 } else {
179 warnings.push_back("Range not given, using default keypool range");
180 range_start = 0;
181 range_end = wallet.m_keypool_size;
182 }
183 next_index = range_start;
184
185 if (data.exists("next_index")) {
186 next_index = data["next_index"].getInt<int64_t>();
187 // bound checks
188 if (next_index < range_start || next_index >= range_end) {
189 throw JSONRPCError(RPC_INVALID_PARAMETER, "next_index is out of range");
190 }
191 }
192 }
193
194 // Active descriptors must be ranged
195 if (active && !parsed_descs.at(0)->IsRange()) {
196 throw JSONRPCError(RPC_INVALID_PARAMETER, "Active descriptors must be ranged");
197 }
198
199 // Multipath descriptors should not have a label
200 if (parsed_descs.size() > 1 && data.exists("label")) {
201 throw JSONRPCError(RPC_INVALID_PARAMETER, "Multipath descriptors should not have a label");
202 }
203
204 // Ranged descriptors should not have a label
205 if (data.exists("range") && data.exists("label")) {
206 throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptors should not have a label");
207 }
208
209 // Internal addresses should not have a label either
210 if (internal && data.exists("label")) {
211 throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal addresses should not have a label");
212 }
213
214 // Combo descriptor check
215 if (active && !parsed_descs.at(0)->IsSingleType()) {
216 throw JSONRPCError(RPC_WALLET_ERROR, "Combo descriptors cannot be set to active");
217 }
218
219 // If the wallet disabled private keys, abort if private keys exist
220 if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !keys.keys.empty()) {
221 throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled");
222 }
223
224 for (size_t j = 0; j < parsed_descs.size(); ++j) {
225 auto parsed_desc = std::move(parsed_descs[j]);
226 bool desc_internal = internal.has_value() && internal.value();
227 if (parsed_descs.size() == 2) {
228 desc_internal = j == 1;
229 } else if (parsed_descs.size() > 2) {
230 CHECK_NONFATAL(!desc_internal);
231 }
232 // Need to ExpandPrivate to check if private keys are available for all pubkeys
233 FlatSigningProvider expand_keys;
234 std::vector<CScript> scripts;
235 if (!parsed_desc->Expand(0, keys, scripts, expand_keys)) {
236 throw JSONRPCError(RPC_WALLET_ERROR, "Cannot expand descriptor. Probably because of hardened derivations without private keys provided");
237 }
238 parsed_desc->ExpandPrivate(0, keys, expand_keys);
239
240 // Check if all private keys are provided
241 bool have_all_privkeys = !expand_keys.keys.empty();
242 for (const auto& entry : expand_keys.origins) {
243 const CKeyID& key_id = entry.first;
244 CKey key;
245 if (!expand_keys.GetKey(key_id, key)) {
246 have_all_privkeys = false;
247 break;
248 }
249 }
250
251 // If private keys are enabled, check some things.
252 if (!wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
253 if (keys.keys.empty()) {
254 throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import descriptor without private keys to a wallet with private keys enabled");
255 }
256 if (!have_all_privkeys) {
257 warnings.push_back("Not all private keys provided. Some wallet functionality may return unexpected errors");
258 }
259 }
260
261 WalletDescriptor w_desc(std::move(parsed_desc), timestamp, range_start, range_end, next_index);
262
263 // Add descriptor to the wallet
264 auto spk_manager_res = wallet.AddWalletDescriptor(w_desc, keys, label, desc_internal);
265
266 if (!spk_manager_res) {
267 throw JSONRPCError(RPC_INVALID_PARAMETER, util::ErrorString(spk_manager_res).original);
268 }
269
270 auto spk_manager = spk_manager_res.value();
271
272 if (spk_manager == nullptr) {
273 throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Could not add descriptor '%s'", descriptor));
274 }
275
276 // Set descriptor as active if necessary
277 if (active) {
278 if (!w_desc.descriptor->GetOutputType()) {
279 warnings.push_back("Unknown output type, cannot set descriptor to active.");
280 } else {
281 wallet.AddActiveScriptPubKeyMan(spk_manager->GetID(), *w_desc.descriptor->GetOutputType(), desc_internal);
282 }
283 } else {
284 if (w_desc.descriptor->GetOutputType()) {
285 wallet.DeactivateScriptPubKeyMan(spk_manager->GetID(), *w_desc.descriptor->GetOutputType(), desc_internal);
286 }
287 }
288 }
289
290 result.pushKV("success", UniValue(true));
291 } catch (const UniValue& e) {
292 result.pushKV("success", UniValue(false));
293 result.pushKV("error", e);
294 }
295 PushWarnings(warnings, result);
296 return result;
297}
298
300{
301 return RPCHelpMan{
302 "importdescriptors",
303 "Import descriptors. This will trigger a rescan of the blockchain based on the earliest timestamp of all descriptors being imported. Requires a new wallet backup.\n"
304 "When importing descriptors with multipath key expressions, if the multipath specifier contains exactly two elements, the descriptor produced from the second element will be imported as an internal descriptor.\n"
305 "\nNote: This call can take over an hour to complete if using an early timestamp; during that time, other rpc calls\n"
306 "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n"
307 "The rescan is significantly faster if block filters are available (using startup option \"-blockfilterindex=1\").\n",
308 {
309 {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported",
310 {
312 {
313 {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "Descriptor to import."},
314 {"active", RPCArg::Type::BOOL, RPCArg::Default{false}, "Set this descriptor to be the active descriptor for the corresponding output type/externality"},
315 {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in the form [begin,end]) to import"},
316 {"next_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If a ranged descriptor is set to active, this specifies the next index to generate addresses from"},
317 {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Time from which to start rescanning the blockchain for this descriptor, in " + UNIX_EPOCH_TIME + "\n"
318 "Use the string \"now\" to substitute the current synced blockchain time.\n"
319 "\"now\" can be specified to bypass scanning, for outputs which are known to never have been used, and\n"
320 "0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest timestamp\n"
321 "of all descriptors being imported will be scanned as well as the mempool.",
322 RPCArgOptions{.type_str={"timestamp | \"now\"", "integer / string"}}
323 },
324 {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether matching outputs should be treated as not incoming payments (e.g. change)"},
325 {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false. Disabled for ranged descriptors"},
326 },
327 },
328 },
330 },
331 RPCResult{
332 RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result",
333 {
334 {RPCResult::Type::OBJ, "", "",
335 {
336 {RPCResult::Type::BOOL, "success", ""},
337 {RPCResult::Type::ARR, "warnings", /*optional=*/true, "",
338 {
339 {RPCResult::Type::STR, "", ""},
340 }},
341 {RPCResult::Type::OBJ, "error", /*optional=*/true, "",
342 {
343 {RPCResult::Type::ELISION, "", "JSONRPC error"},
344 }},
345 }},
346 }
347 },
349 HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"internal\": true }, "
350 "{ \"desc\": \"<my descriptor 2>\", \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
351 HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"active\": true, \"range\": [0,100], \"label\": \"<my bech32 wallet>\" }]'")
352 },
353 [&](const RPCHelpMan& self, const JSONRPCRequest& main_request) -> UniValue
354{
355 std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(main_request);
356 if (!pwallet) return UniValue::VNULL;
357 CWallet& wallet{*pwallet};
358
359 // Make sure the results are valid at least up to the most recent block
360 // the user could have gotten from another RPC command prior to now
361 wallet.BlockUntilSyncedToCurrentChain();
362
363 // Make sure wallet is a descriptor wallet
364 if (!pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
365 throw JSONRPCError(RPC_WALLET_ERROR, "importdescriptors is not available for non-descriptor wallets");
366 }
367
368 WalletRescanReserver reserver(*pwallet);
369 if (!reserver.reserve(/*with_passphrase=*/true)) {
370 throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
371 }
372
373 // Ensure that the wallet is not locked for the remainder of this RPC, as
374 // the passphrase is used to top up the keypool.
375 LOCK(pwallet->m_relock_mutex);
376
377 const UniValue& requests = main_request.params[0];
378 const int64_t minimum_timestamp = 1;
379 int64_t now = 0;
380 int64_t lowest_timestamp = 0;
381 bool rescan = false;
382 UniValue response(UniValue::VARR);
383 {
384 LOCK(pwallet->cs_wallet);
385 EnsureWalletIsUnlocked(*pwallet);
386
387 CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(lowest_timestamp).mtpTime(now)));
388
389 // Get all timestamps and extract the lowest timestamp
390 for (const UniValue& request : requests.getValues()) {
391 // This throws an error if "timestamp" doesn't exist
392 const int64_t timestamp = std::max(GetImportTimestamp(request, now), minimum_timestamp);
393 const UniValue result = ProcessDescriptorImport(*pwallet, request, timestamp);
394 response.push_back(result);
395
396 if (lowest_timestamp > timestamp ) {
397 lowest_timestamp = timestamp;
398 }
399
400 // If we know the chain tip, and at least one request was successful then allow rescan
401 if (!rescan && result["success"].get_bool()) {
402 rescan = true;
403 }
404 }
405 pwallet->ConnectScriptPubKeyManNotifiers();
406 }
407
408 // Rescan the blockchain using the lowest timestamp
409 if (rescan) {
410 int64_t scanned_time = pwallet->RescanFromTime(lowest_timestamp, reserver, /*update=*/true);
411 pwallet->ResubmitWalletTransactions(/*relay=*/false, /*force=*/true);
412
413 if (pwallet->IsAbortingRescan()) {
414 throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user.");
415 }
416
417 if (scanned_time > lowest_timestamp) {
418 std::vector<UniValue> results = response.getValues();
419 response.clear();
420 response.setArray();
421
422 // Compose the response
423 for (unsigned int i = 0; i < requests.size(); ++i) {
424 const UniValue& request = requests.getValues().at(i);
425
426 // If the descriptor timestamp is within the successfully scanned
427 // range, or if the import result already has an error set, let
428 // the result stand unmodified. Otherwise replace the result
429 // with an error message.
430 if (scanned_time <= GetImportTimestamp(request, now) || results.at(i).exists("error")) {
431 response.push_back(results.at(i));
432 } else {
433 std::string error_msg{strprintf("Rescan failed for descriptor with timestamp %d. There "
434 "was an error reading a block from time %d, which is after or within %d seconds "
435 "of key creation, and could contain transactions pertaining to the desc. As a "
436 "result, transactions and coins using this desc may not appear in the wallet.",
437 GetImportTimestamp(request, now), scanned_time - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)};
438 if (pwallet->chain().havePruned()) {
439 error_msg += strprintf(" This error could be caused by pruning or data corruption "
440 "(see bitcoind log for details) and could be dealt with by downloading and "
441 "rescanning the relevant blocks (see -reindex option and rescanblockchain RPC).");
442 } else if (pwallet->chain().hasAssumedValidChain()) {
443 error_msg += strprintf(" This error is likely caused by an in-progress assumeutxo "
444 "background sync. Check logs or getchainstates RPC for assumeutxo background "
445 "sync progress and try again later.");
446 } else {
447 error_msg += strprintf(" This error could potentially caused by data corruption. If "
448 "the issue persists you may want to reindex (see -reindex option).");
449 }
450
452 result.pushKV("success", UniValue(false));
453 result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, error_msg));
454 response.push_back(std::move(result));
455 }
456 }
457 }
458 }
459
460 return response;
461},
462 };
463}
464
466{
467 return RPCHelpMan{
468 "listdescriptors",
469 "List descriptors imported into a descriptor-enabled wallet.\n",
470 {
471 {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private descriptors."}
472 },
474 {RPCResult::Type::STR, "wallet_name", "Name of wallet this operation was performed on"},
475 {RPCResult::Type::ARR, "descriptors", "Array of descriptor objects (sorted by descriptor string representation)",
476 {
477 {RPCResult::Type::OBJ, "", "", {
478 {RPCResult::Type::STR, "desc", "Descriptor string representation"},
479 {RPCResult::Type::NUM, "timestamp", "The creation time of the descriptor"},
480 {RPCResult::Type::BOOL, "active", "Whether this descriptor is currently used to generate new addresses"},
481 {RPCResult::Type::BOOL, "internal", /*optional=*/true, "True if this descriptor is used to generate change addresses. False if this descriptor is used to generate receiving addresses; defined only for active descriptors"},
482 {RPCResult::Type::ARR_FIXED, "range", /*optional=*/true, "Defined only for ranged descriptors", {
483 {RPCResult::Type::NUM, "", "Range start inclusive"},
484 {RPCResult::Type::NUM, "", "Range end inclusive"},
485 }},
486 {RPCResult::Type::NUM, "next", /*optional=*/true, "Same as next_index field. Kept for compatibility reason."},
487 {RPCResult::Type::NUM, "next_index", /*optional=*/true, "The next index to generate addresses from; defined only for ranged descriptors"},
488 }},
489 }}
490 }},
492 HelpExampleCli("listdescriptors", "") + HelpExampleRpc("listdescriptors", "")
493 + HelpExampleCli("listdescriptors", "true") + HelpExampleRpc("listdescriptors", "true")
494 },
495 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
496{
497 const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);
498 if (!wallet) return UniValue::VNULL;
499
500 if (!wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) {
501 throw JSONRPCError(RPC_WALLET_ERROR, "listdescriptors is not available for non-descriptor wallets");
502 }
503
504 const bool priv = !request.params[0].isNull() && request.params[0].get_bool();
505 if (priv) {
507 }
508
509 LOCK(wallet->cs_wallet);
510
511 const auto active_spk_mans = wallet->GetActiveScriptPubKeyMans();
512
513 struct WalletDescInfo {
514 std::string descriptor;
515 uint64_t creation_time;
516 bool active;
517 std::optional<bool> internal;
518 std::optional<std::pair<int64_t,int64_t>> range;
519 int64_t next_index;
520 };
521
522 std::vector<WalletDescInfo> wallet_descriptors;
523 for (const auto& spk_man : wallet->GetAllScriptPubKeyMans()) {
524 const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
525 if (!desc_spk_man) {
526 throw JSONRPCError(RPC_WALLET_ERROR, "Unexpected ScriptPubKey manager type.");
527 }
528 LOCK(desc_spk_man->cs_desc_man);
529 const auto& wallet_descriptor = desc_spk_man->GetWalletDescriptor();
530 std::string descriptor;
531 if (!desc_spk_man->GetDescriptorString(descriptor, priv)) {
532 throw JSONRPCError(RPC_WALLET_ERROR, "Can't get descriptor string.");
533 }
534 const bool is_range = wallet_descriptor.descriptor->IsRange();
535 wallet_descriptors.push_back({
536 descriptor,
537 wallet_descriptor.creation_time,
538 active_spk_mans.count(desc_spk_man) != 0,
539 wallet->IsInternalScriptPubKeyMan(desc_spk_man),
540 is_range ? std::optional(std::make_pair(wallet_descriptor.range_start, wallet_descriptor.range_end)) : std::nullopt,
541 wallet_descriptor.next_index
542 });
543 }
544
545 std::sort(wallet_descriptors.begin(), wallet_descriptors.end(), [](const auto& a, const auto& b) {
546 return a.descriptor < b.descriptor;
547 });
548
549 UniValue descriptors(UniValue::VARR);
550 for (const WalletDescInfo& info : wallet_descriptors) {
552 spk.pushKV("desc", info.descriptor);
553 spk.pushKV("timestamp", info.creation_time);
554 spk.pushKV("active", info.active);
555 if (info.internal.has_value()) {
556 spk.pushKV("internal", info.internal.value());
557 }
558 if (info.range.has_value()) {
560 range.push_back(info.range->first);
561 range.push_back(info.range->second - 1);
562 spk.pushKV("range", std::move(range));
563 spk.pushKV("next", info.next_index);
564 spk.pushKV("next_index", info.next_index);
565 }
566 descriptors.push_back(std::move(spk));
567 }
568
569 UniValue response(UniValue::VOBJ);
570 response.pushKV("wallet_name", wallet->GetName());
571 response.pushKV("descriptors", std::move(descriptors));
572
573 return response;
574},
575 };
576}
577
579{
580 return RPCHelpMan{
581 "backupwallet",
582 "Safely copies the current wallet file to the specified destination, which can either be a directory or a path with a filename.\n",
583 {
584 {"destination", RPCArg::Type::STR, RPCArg::Optional::NO, "The destination directory or file"},
585 },
588 HelpExampleCli("backupwallet", "\"backup.dat\"")
589 + HelpExampleRpc("backupwallet", "\"backup.dat\"")
590 },
591 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
592{
593 const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
594 if (!pwallet) return UniValue::VNULL;
595
596 // Make sure the results are valid at least up to the most recent block
597 // the user could have gotten from another RPC command prior to now
598 pwallet->BlockUntilSyncedToCurrentChain();
599
600 LOCK(pwallet->cs_wallet);
601
602 std::string strDest = request.params[0].get_str();
603 if (!pwallet->BackupWallet(strDest)) {
604 throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
605 }
606
607 return UniValue::VNULL;
608},
609 };
610}
611
612
614{
615 return RPCHelpMan{
616 "restorewallet",
617 "Restores and loads a wallet from backup.\n"
618 "\nThe rescan is significantly faster if a descriptor wallet is restored"
619 "\nand block filters are available (using startup option \"-blockfilterindex=1\").\n",
620 {
621 {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name that will be applied to the restored wallet"},
622 {"backup_file", RPCArg::Type::STR, RPCArg::Optional::NO, "The backup file that will be used to restore the wallet."},
623 {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."},
624 },
625 RPCResult{
626 RPCResult::Type::OBJ, "", "",
627 {
628 {RPCResult::Type::STR, "name", "The wallet name if restored successfully."},
629 {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to restoring and loading the wallet.",
630 {
631 {RPCResult::Type::STR, "", ""},
632 }},
633 }
634 },
636 HelpExampleCli("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"")
637 + HelpExampleRpc("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"")
638 + HelpExampleCliNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}})
639 + HelpExampleRpcNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}})
640 },
641 [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
642{
643
644 WalletContext& context = EnsureWalletContext(request.context);
645
646 auto backup_file = fs::u8path(request.params[1].get_str());
647
648 std::string wallet_name = request.params[0].get_str();
649
650 std::optional<bool> load_on_start = request.params[2].isNull() ? std::nullopt : std::optional<bool>(request.params[2].get_bool());
651
652 DatabaseStatus status;
653 bilingual_str error;
654 std::vector<bilingual_str> warnings;
655
656 const std::shared_ptr<CWallet> wallet = RestoreWallet(context, backup_file, wallet_name, load_on_start, status, error, warnings);
657
658 HandleWalletError(wallet, status, error);
659
661 obj.pushKV("name", wallet->GetName());
662 PushWarnings(warnings, obj);
663
664 return obj;
665
666},
667 };
668}
669} // namespace wallet
static constexpr int64_t TIMESTAMP_WINDOW
Timestamp window used as a grace period by code that compares external timestamps (such as timestamps...
Definition: chain.h:37
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:102
uint256 hashMerkleRoot
Definition: block.h:27
uint256 GetHash() const
Definition: block.cpp:11
An encapsulated private key.
Definition: key.h:35
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:24
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:126
CBlockHeader header
Public only for unit testing.
Definition: merkleblock.h:129
CPartialMerkleTree txn
Definition: merkleblock.h:130
uint256 ExtractMatches(std::vector< uint256 > &vMatch, std::vector< unsigned int > &vnIndex)
extract the matching txid's represented by this partial merkle tree and their respective indices with...
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
void push_back(UniValue val)
Definition: univalue.cpp:104
const std::string & get_str() const
@ VNULL
Definition: univalue.h:24
@ VOBJ
Definition: univalue.h:24
@ VARR
Definition: univalue.h:24
void setArray()
Definition: univalue.cpp:92
void clear()
Definition: univalue.cpp:18
size_t size() const
Definition: univalue.h:71
enum VType type() const
Definition: univalue.h:126
const std::vector< UniValue > & getValues() const
bool isStr() const
Definition: univalue.h:83
Int getInt() const
Definition: univalue.h:138
bool isNum() const
Definition: univalue.h:84
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
Helper for findBlock to selectively return pieces of block data.
Definition: chain.h:48
static transaction_identifier FromUint256(const uint256 &id)
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:301
Descriptor with some wallet metadata.
Definition: walletutil.h:85
std::shared_ptr< Descriptor > descriptor
Definition: walletutil.h:87
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1063
bool reserve(bool with_passphrase=false)
Definition: wallet.h:1073
static UniValue Parse(std::string_view raw)
Parse string to UniValue or throw runtime_error if string contains invalid JSON.
Definition: client.cpp:317
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:196
static path u8path(const std::string &utf8_str)
Definition: fs.h:75
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:93
static UniValue ProcessDescriptorImport(CWallet &wallet, const UniValue &data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
Definition: backup.cpp:140
std::shared_ptr< CWallet > GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: util.cpp:57
RPCHelpMan removeprunedfunds()
Definition: backup.cpp:93
void HandleWalletError(const std::shared_ptr< CWallet > wallet, DatabaseStatus &status, bilingual_str &error)
Definition: util.cpp:117
void EnsureWalletIsUnlocked(const CWallet &wallet)
Definition: util.cpp:81
RPCHelpMan backupwallet()
Definition: backup.cpp:578
RPCHelpMan importprunedfunds()
Definition: backup.cpp:37
std::shared_ptr< CWallet > RestoreWallet(WalletContext &context, const fs::path &backup_file, const std::string &wallet_name, std::optional< bool > load_on_start, DatabaseStatus &status, bilingual_str &error, std::vector< bilingual_str > &warnings, bool load_after_restore)
Definition: wallet.cpp:491
WalletContext & EnsureWalletContext(const std::any &context)
Definition: util.cpp:88
RPCHelpMan listdescriptors()
Definition: backup.cpp:465
std::string LabelFromValue(const UniValue &value)
Definition: util.cpp:97
RPCHelpMan restorewallet()
Definition: backup.cpp:613
RPCHelpMan importdescriptors()
Definition: backup.cpp:299
static int64_t GetImportTimestamp(const UniValue &data, int64_t now)
Definition: backup.cpp:126
@ WALLET_FLAG_DESCRIPTORS
Indicate that this wallet supports DescriptorScriptPubKeyMan.
Definition: walletutil.h:74
@ WALLET_FLAG_DISABLE_PRIVATE_KEYS
Definition: walletutil.h:51
DatabaseStatus
Definition: db.h:183
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:70
@ RPC_MISC_ERROR
General application defined errors.
Definition: protocol.h:40
@ RPC_TYPE_ERROR
Unexpected type was passed as parameter.
Definition: protocol.h:41
@ RPC_INVALID_PARAMETER
Invalid, missing or duplicate parameter.
Definition: protocol.h:44
@ RPC_WALLET_ERROR
Wallet errors.
Definition: protocol.h:71
@ RPC_DESERIALIZATION_ERROR
Error parsing or validating structure in raw format.
Definition: protocol.h:46
@ RPC_INVALID_ADDRESS_OR_KEY
Invalid address or key.
Definition: protocol.h:42
std::pair< int64_t, int64_t > ParseDescriptorRange(const UniValue &value)
Parse a JSON range specified as int64, or [int64, int64].
Definition: util.cpp:1311
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:186
std::string HelpExampleRpcNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:210
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string_view name)
Definition: util.cpp:133
void PushWarnings(const UniValue &warnings, UniValue &obj)
Push warning messages to an RPC "warnings" field as a JSON array of strings.
Definition: util.cpp:1381
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:204
const std::string UNIX_EPOCH_TIME
String used to describe UNIX epoch time in documentation, factored out to a constant for consistency.
Definition: util.cpp:46
std::string HelpExampleCliNamed(const std::string &methodname, const RPCArgList &args)
Definition: util.cpp:191
uint256 ParseHashV(const UniValue &v, std::string_view name)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:120
A mutable version of CTransaction.
Definition: transaction.h:378
Txid GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
std::map< CKeyID, std::pair< CPubKey, KeyOriginInfo > > origins
bool GetKey(const CKeyID &keyid, CKey &key) const override
std::map< CKeyID, CKey > keys
@ RANGE
Special type that is a NUM or [NUM,NUM].
@ STR_HEX
Special type that is a STR with only hex chars.
@ OMITTED
Optional argument for which the default value is omitted from help text for one of two reasons:
@ NO
Required arg.
std::vector< std::string > type_str
Should be empty unless it is supposed to override the auto-generated type strings....
Definition: util.h:168
std::string oneline_description
Should be empty unless it is supposed to override the auto-generated summary line.
Definition: util.h:167
@ ELISION
Special type to denote elision (...)
@ ARR_FIXED
Special array that has a fixed number of entries.
Bilingual messages:
Definition: translation.h:24
State of transaction confirmed in a block.
Definition: transaction.h:31
WalletContext struct containing references to state shared between CWallet instances,...
Definition: context.h:36
#define LOCK(cs)
Definition: sync.h:257
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:49
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
const char * uvTypeName(UniValue::VType t)
Definition: univalue.cpp:218