Branch data Line data Source code
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 <node/types.h>
13 : : #include <rpc/util.h>
14 : : #include <script/descriptor.h>
15 : : #include <script/script.h>
16 : : #include <script/solver.h>
17 : : #include <sync.h>
18 : : #include <uint256.h>
19 : : #include <util/bip32.h>
20 : : #include <util/fs.h>
21 : : #include <util/time.h>
22 : : #include <util/translation.h>
23 : : #include <wallet/rpc/util.h>
24 : : #include <wallet/wallet.h>
25 : :
26 : : #include <cstdint>
27 : : #include <fstream>
28 : : #include <tuple>
29 : : #include <string>
30 : :
31 : : #include <univalue.h>
32 : :
33 : :
34 : :
35 : : using interfaces::FoundBlock;
36 : :
37 : : namespace wallet {
38 : 823 : RPCHelpMan importprunedfunds()
39 : : {
40 : 823 : return RPCHelpMan{
41 : 823 : "importprunedfunds",
42 [ + - ]: 1646 : "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",
43 : : {
44 [ + - + - ]: 1646 : {"rawtransaction", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A raw transaction in hex funding an already-existing address in wallet"},
45 [ + - + - ]: 1646 : {"txoutproof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex output from gettxoutproof that contains the transaction"},
46 : : },
47 [ + - + - : 1646 : RPCResult{RPCResult::Type::NONE, "", ""},
+ - + - ]
48 [ + - + - ]: 2469 : RPCExamples{""},
49 : 823 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
50 : : {
51 : 7 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
52 [ - + ]: 7 : if (!pwallet) return UniValue::VNULL;
53 : :
54 [ + - ]: 7 : CMutableTransaction tx;
55 [ + - + - : 7 : if (!DecodeHexTx(tx, request.params[0].get_str())) {
+ - + + ]
56 [ + - + - ]: 2 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
57 : : }
58 : :
59 [ + - + - : 12 : DataStream ssMB{ParseHexV(request.params[1], "proof")};
+ - ]
60 [ + - ]: 6 : CMerkleBlock merkleBlock;
61 [ + - ]: 6 : ssMB >> merkleBlock;
62 : :
63 : : //Search partial merkle tree in proof for our transaction and index in valid block
64 : 6 : std::vector<Txid> vMatch;
65 : 6 : std::vector<unsigned int> vIndex;
66 [ + - + + ]: 6 : if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) {
67 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
68 : : }
69 : :
70 [ + - ]: 5 : LOCK(pwallet->cs_wallet);
71 : 5 : int height;
72 [ + - + - : 5 : if (!pwallet->chain().findAncestorByHash(pwallet->GetLastBlockHash(), merkleBlock.header.GetHash(), FoundBlock().height(height))) {
+ + ]
73 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
74 : : }
75 : :
76 : 4 : std::vector<Txid>::const_iterator it;
77 [ + - + + ]: 4 : if ((it = std::find(vMatch.begin(), vMatch.end(), tx.GetHash())) == vMatch.end()) {
78 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
79 : : }
80 : :
81 [ + - ]: 3 : unsigned int txnIndex = vIndex[it - vMatch.begin()];
82 : :
83 [ + - ]: 3 : CTransactionRef tx_ref = MakeTransactionRef(tx);
84 [ + - + + ]: 3 : if (pwallet->IsMine(*tx_ref)) {
85 [ + - + - ]: 4 : pwallet->AddToWallet(std::move(tx_ref), TxStateConfirmed{merkleBlock.header.GetHash(), height, static_cast<int>(txnIndex)});
86 [ - + ]: 2 : return UniValue::VNULL;
87 : : }
88 : :
89 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
90 [ + - ]: 29 : },
91 [ + - + - : 4938 : };
+ + - - ]
92 [ + - + - : 3292 : }
- - ]
93 : :
94 : 819 : RPCHelpMan removeprunedfunds()
95 : : {
96 : 819 : return RPCHelpMan{
97 : 819 : "removeprunedfunds",
98 [ + - ]: 1638 : "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",
99 : : {
100 [ + - + - ]: 1638 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex-encoded id of the transaction you are deleting"},
101 : : },
102 [ + - + - : 1638 : RPCResult{RPCResult::Type::NONE, "", ""},
+ - + - ]
103 : 819 : RPCExamples{
104 [ + - + - : 1638 : HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
+ - ]
105 : 819 : "\nAs a JSON-RPC call\n"
106 [ + - + - : 3276 : + HelpExampleRpc("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"")
+ - + - ]
107 [ + - ]: 819 : },
108 : 819 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
109 : : {
110 : 3 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
111 [ - + ]: 3 : if (!pwallet) return UniValue::VNULL;
112 : :
113 [ + - ]: 3 : LOCK(pwallet->cs_wallet);
114 : :
115 [ + - + - ]: 3 : Txid hash{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
116 : 3 : std::vector<Txid> vHash;
117 [ + - ]: 3 : vHash.push_back(hash);
118 [ + - + + ]: 3 : if (auto res = pwallet->RemoveTxs(vHash); !res) {
119 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_ERROR, util::ErrorString(res).original);
120 : 1 : }
121 : :
122 : 2 : return UniValue::VNULL;
123 [ + - ]: 8 : },
124 [ + - + - : 4095 : };
+ + - - ]
125 [ + - ]: 1638 : }
126 : :
127 : 707 : static int64_t GetImportTimestamp(const UniValue& data, int64_t now)
128 : : {
129 [ + - ]: 1414 : if (data.exists("timestamp")) {
130 [ + - ]: 707 : const UniValue& timestamp = data["timestamp"];
131 [ + + ]: 707 : if (timestamp.isNum()) {
132 : 209 : return timestamp.getInt<int64_t>();
133 [ + - - + ]: 498 : } else if (timestamp.isStr() && timestamp.get_str() == "now") {
134 : : return now;
135 : : }
136 [ # # # # : 0 : throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
# # ]
137 : : }
138 [ # # # # ]: 0 : throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
139 : : }
140 : :
141 : 705 : static UniValue ProcessDescriptorImport(CWallet& wallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet)
142 : : {
143 : 705 : UniValue warnings(UniValue::VARR);
144 : 705 : UniValue result(UniValue::VOBJ);
145 : :
146 : 705 : try {
147 [ + - + + ]: 1410 : if (!data.exists("desc")) {
148 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor not found.");
149 : : }
150 : :
151 [ + - + - : 704 : const std::string& descriptor = data["desc"].get_str();
+ - ]
152 [ + - + + : 1715 : const bool active = data.exists("active") ? data["active"].get_bool() : false;
+ - + - +
- ]
153 [ + - + - : 705 : const std::string label{LabelFromValue(data["label"])};
+ + ]
154 : :
155 : : // Parse descriptor string
156 : 703 : FlatSigningProvider keys;
157 [ - + ]: 703 : std::string error;
158 [ - + + - ]: 703 : auto parsed_descs = Parse(descriptor, keys, error, /* require_checksum = */ true);
159 [ + + ]: 703 : if (parsed_descs.empty()) {
160 [ + - ]: 8 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error);
161 : : }
162 : 695 : std::optional<bool> internal;
163 [ + - + + ]: 1390 : if (data.exists("internal")) {
164 [ - + + + ]: 118 : if (parsed_descs.size() > 1) {
165 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot have multipath descriptor while also specifying \'internal\'");
166 : : }
167 [ + - + - : 117 : internal = data["internal"].get_bool();
+ - ]
168 : : }
169 : :
170 : : // Range check
171 : 694 : std::optional<bool> is_ranged;
172 : 694 : int64_t range_start = 0, range_end = 1, next_index = 0;
173 [ + - + - : 956 : if (!parsed_descs.at(0)->IsRange() && data.exists("range")) {
+ + + - +
- + + +
+ ]
174 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor");
175 [ + - + - : 693 : } else if (parsed_descs.at(0)->IsRange()) {
+ + ]
176 [ + - + + ]: 864 : if (data.exists("range")) {
177 [ + - + - : 116 : auto range = ParseDescriptorRange(data["range"]);
+ + ]
178 : 106 : range_start = range.first;
179 : 106 : range_end = range.second + 1; // Specified range end is inclusive, but we need range end as exclusive
180 : : } else {
181 [ + - + - ]: 321 : warnings.push_back("Range not given, using default keypool range");
182 : 321 : range_start = 0;
183 : 321 : range_end = wallet.m_keypool_size;
184 : : }
185 : 427 : next_index = range_start;
186 : 427 : is_ranged = true;
187 : :
188 [ + - + + ]: 854 : if (data.exists("next_index")) {
189 [ + - + - : 71 : next_index = data["next_index"].getInt<int64_t>();
+ - ]
190 : : // bound checks
191 [ - + ]: 71 : if (next_index < range_start || next_index >= range_end) {
192 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "next_index is out of range");
193 : : }
194 : : }
195 : : }
196 : :
197 : : // Active descriptors must be ranged
198 [ + + + - : 976 : if (active && !parsed_descs.at(0)->IsRange()) {
+ + ]
199 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Active descriptors must be ranged");
200 : : }
201 : :
202 : : // Multipath descriptors should not have a label
203 [ - + + + : 730 : if (parsed_descs.size() > 1 && data.exists("label")) {
+ - + - +
+ + + ]
204 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Multipath descriptors should not have a label");
205 : : }
206 : :
207 : : // Ranged descriptors should not have a label
208 [ + + + - : 1112 : if (is_ranged.has_value() && is_ranged.value() && data.exists("label")) {
+ - + - +
+ + + ]
209 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptors should not have a label");
210 : : }
211 : :
212 [ + + + + : 780 : bool desc_internal = internal.has_value() && internal.value();
+ + ]
213 : : // Internal addresses should not have a label either
214 [ + - + - : 780 : if (desc_internal && data.exists("label")) {
+ + + + ]
215 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal addresses should not have a label");
216 : : }
217 : :
218 : : // Combo descriptor check
219 [ + + + - : 968 : if (active && !parsed_descs.at(0)->IsSingleType()) {
+ + ]
220 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_ERROR, "Combo descriptors cannot be set to active");
221 : : }
222 : :
223 : : // If the wallet disabled private keys, abort if private keys exist
224 [ + - + + : 682 : if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !keys.keys.empty()) {
+ + ]
225 [ + - + - ]: 6 : throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled");
226 : : }
227 : :
228 [ - + + + ]: 1396 : for (size_t j = 0; j < parsed_descs.size(); ++j) {
229 [ - + ]: 724 : auto parsed_desc = std::move(parsed_descs[j]);
230 [ - + + + ]: 724 : if (parsed_descs.size() == 2) {
231 : 78 : desc_internal = j == 1;
232 [ + + ]: 646 : } else if (parsed_descs.size() > 2) {
233 [ + - ]: 9 : CHECK_NONFATAL(!desc_internal);
234 : : }
235 : : // Need to ExpandPrivate to check if private keys are available for all pubkeys
236 : 724 : FlatSigningProvider expand_keys;
237 : 724 : std::vector<CScript> scripts;
238 [ + - + + ]: 724 : if (!parsed_desc->Expand(0, keys, scripts, expand_keys)) {
239 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_ERROR, "Cannot expand descriptor. Probably because of hardened derivations without private keys provided");
240 : : }
241 [ + - ]: 723 : parsed_desc->ExpandPrivate(0, keys, expand_keys);
242 : :
243 : : // Check if all private keys are provided
244 : 723 : bool have_all_privkeys = !expand_keys.keys.empty();
245 [ + + ]: 1176 : for (const auto& entry : expand_keys.origins) {
246 : 806 : const CKeyID& key_id = entry.first;
247 : 806 : CKey key;
248 [ + - + + ]: 806 : if (!expand_keys.GetKey(key_id, key)) {
249 : 353 : have_all_privkeys = false;
250 : 353 : break;
251 : : }
252 : 806 : }
253 : :
254 : : // If private keys are enabled, check some things.
255 [ + - + + ]: 723 : if (!wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
256 [ + + ]: 538 : if (keys.keys.empty()) {
257 [ + - + - ]: 6 : throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import descriptor without private keys to a wallet with private keys enabled");
258 : : }
259 [ + + ]: 535 : if (!have_all_privkeys) {
260 [ + - + - ]: 176 : warnings.push_back("Not all private keys provided. Some wallet functionality may return unexpected errors");
261 : : }
262 : : }
263 : :
264 [ + - + - ]: 720 : WalletDescriptor w_desc(std::move(parsed_desc), timestamp, range_start, range_end, next_index);
265 : :
266 : : // Add descriptor to the wallet
267 [ + - ]: 720 : auto spk_manager_res = wallet.AddWalletDescriptor(w_desc, keys, label, desc_internal);
268 : :
269 [ + + ]: 720 : if (!spk_manager_res) {
270 [ + - + - : 9 : throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Could not add descriptor '%s': %s", descriptor, util::ErrorString(spk_manager_res).original));
+ - ]
271 : : }
272 : :
273 [ + + ]: 717 : auto& spk_manager = spk_manager_res.value().get();
274 : :
275 : : // Set descriptor as active if necessary
276 [ + + ]: 717 : if (active) {
277 [ + - + + ]: 326 : if (!w_desc.descriptor->GetOutputType()) {
278 [ + - + - ]: 1 : warnings.push_back("Unknown output type, cannot set descriptor to active.");
279 : : } else {
280 [ + - + - : 325 : wallet.AddActiveScriptPubKeyMan(spk_manager.GetID(), *w_desc.descriptor->GetOutputType(), desc_internal);
+ - ]
281 : : }
282 : : } else {
283 [ + - + + ]: 391 : if (w_desc.descriptor->GetOutputType()) {
284 [ + - + - : 217 : wallet.DeactivateScriptPubKeyMan(spk_manager.GetID(), *w_desc.descriptor->GetOutputType(), desc_internal);
+ - ]
285 : : }
286 : : }
287 : 741 : }
288 : :
289 [ + - + - : 1344 : result.pushKV("success", UniValue(true));
+ - ]
290 [ - + ]: 767 : } catch (const UniValue& e) {
291 [ + - + - : 66 : result.pushKV("success", UniValue(false));
+ - ]
292 [ + - + - : 66 : result.pushKV("error", e);
+ - ]
293 : 33 : }
294 [ + - ]: 705 : PushWarnings(warnings, result);
295 : 705 : return result;
296 : 705 : }
297 : :
298 : 1437 : RPCHelpMan importdescriptors()
299 : : {
300 : 1437 : return RPCHelpMan{
301 : 1437 : "importdescriptors",
302 [ + - ]: 2874 : "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"
303 : : "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"
304 : : "\nNote: This call can take over an hour to complete if using an early timestamp; during that time, other rpc calls\n"
305 : : "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n"
306 : : "The rescan is significantly faster if block filters are available (using startup option \"-blockfilterindex=1\").\n",
307 : : {
308 [ + - + - ]: 2874 : {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported",
309 : : {
310 [ + - + - ]: 2874 : {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
311 : : {
312 [ + - + - ]: 2874 : {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "Descriptor to import."},
313 [ + - + - : 4311 : {"active", RPCArg::Type::BOOL, RPCArg::Default{false}, "Set this descriptor to be the active descriptor for the corresponding output type/externality"},
+ - ]
314 [ + - + - ]: 2874 : {"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"},
315 [ + - + - ]: 2874 : {"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"},
316 [ + - + - ]: 2874 : {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Time from which to start rescanning the blockchain for this descriptor, in " + UNIX_EPOCH_TIME + "\n"
317 : : "Use the string \"now\" to substitute the current synced blockchain time.\n"
318 : : "\"now\" can be specified to bypass scanning, for outputs which are known to never have been used, and\n"
319 : : "0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest timestamp\n"
320 : 1437 : "of all descriptors being imported will be scanned as well as the mempool.",
321 [ + - ]: 2874 : RPCArgOptions{.type_str={"timestamp | \"now\"", "integer / string"}}
322 : : },
323 [ + - + - : 4311 : {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether matching outputs should be treated as not incoming payments (e.g. change)"},
+ - ]
324 [ + - + - : 4311 : {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false. Disabled for ranged descriptors"},
+ - ]
325 : : },
326 : : },
327 : : },
328 [ + - ]: 1437 : RPCArgOptions{.oneline_description="requests"}},
329 : : },
330 [ + - ]: 2874 : RPCResult{
331 [ + - + - ]: 2874 : RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result",
332 : : {
333 [ + - + - ]: 2874 : {RPCResult::Type::OBJ, "", "",
334 : : {
335 [ + - + - ]: 2874 : {RPCResult::Type::BOOL, "success", ""},
336 [ + - + - ]: 2874 : {RPCResult::Type::ARR, "warnings", /*optional=*/true, "",
337 : : {
338 [ + - + - ]: 2874 : {RPCResult::Type::STR, "", ""},
339 : : }},
340 [ + - + - ]: 2874 : {RPCResult::Type::OBJ, "error", /*optional=*/true, "",
341 : : {
342 [ + - + - ]: 2874 : {RPCResult::Type::ELISION, "", "JSONRPC error"},
343 : : }},
344 : : }},
345 : : }
346 [ + - + - : 18681 : },
+ - + - +
- + + + +
+ + + + -
- - - - -
- - ]
347 : 1437 : RPCExamples{
348 [ + - + - : 2874 : HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"internal\": true }, "
+ - ]
349 : 1437 : "{ \"desc\": \"<my descriptor 2>\", \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
350 [ + - + - : 4311 : HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"active\": true, \"range\": [0,100], \"label\": \"<my bech32 wallet>\" }]'")
+ - + - ]
351 [ + - ]: 1437 : },
352 : 1437 : [&](const RPCHelpMan& self, const JSONRPCRequest& main_request) -> UniValue
353 : : {
354 : 621 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(main_request);
355 [ - + ]: 621 : if (!pwallet) return UniValue::VNULL;
356 [ + - ]: 621 : CWallet& wallet{*pwallet};
357 : :
358 : : // Make sure the results are valid at least up to the most recent block
359 : : // the user could have gotten from another RPC command prior to now
360 [ + - ]: 621 : wallet.BlockUntilSyncedToCurrentChain();
361 : :
362 : 621 : WalletRescanReserver reserver(*pwallet);
363 [ - + ]: 621 : if (!reserver.reserve(/*with_passphrase=*/true)) {
364 [ # # # # ]: 0 : throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
365 : : }
366 : :
367 : : // Ensure that the wallet is not locked for the remainder of this RPC, as
368 : : // the passphrase is used to top up the keypool.
369 [ + - ]: 621 : LOCK(pwallet->m_relock_mutex);
370 : :
371 [ + - ]: 621 : const UniValue& requests = main_request.params[0];
372 : 621 : const int64_t minimum_timestamp = 1;
373 : 621 : int64_t now = 0;
374 : 621 : int64_t lowest_timestamp = 0;
375 : 621 : bool rescan = false;
376 : 621 : UniValue response(UniValue::VARR);
377 : 621 : {
378 [ + - ]: 621 : LOCK(pwallet->cs_wallet);
379 [ + - ]: 621 : EnsureWalletIsUnlocked(*pwallet);
380 : :
381 [ + - + - ]: 621 : CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(lowest_timestamp).mtpTime(now)));
382 : :
383 : : // Get all timestamps and extract the lowest timestamp
384 [ + - + + ]: 1326 : for (const UniValue& request : requests.getValues()) {
385 : : // This throws an error if "timestamp" doesn't exist
386 [ + - + + ]: 705 : const int64_t timestamp = std::max(GetImportTimestamp(request, now), minimum_timestamp);
387 [ + - ]: 705 : const UniValue result = ProcessDescriptorImport(*pwallet, request, timestamp);
388 [ + - + - ]: 705 : response.push_back(result);
389 : :
390 [ + + ]: 705 : if (lowest_timestamp > timestamp ) {
391 : 483 : lowest_timestamp = timestamp;
392 : : }
393 : :
394 : : // If we know the chain tip, and at least one request was successful then allow rescan
395 [ + + + - : 1327 : if (!rescan && result["success"].get_bool()) {
+ - + - +
+ + + -
- ]
396 : 589 : rescan = true;
397 : : }
398 : 705 : }
399 [ + - ]: 621 : pwallet->ConnectScriptPubKeyManNotifiers();
400 [ + - ]: 621 : pwallet->RefreshAllTXOs();
401 : 0 : }
402 : :
403 : : // Rescan the blockchain using the lowest timestamp
404 [ + + ]: 621 : if (rescan) {
405 [ + - ]: 589 : int64_t scanned_time = pwallet->RescanFromTime(lowest_timestamp, reserver, /*update=*/true);
406 [ + - ]: 589 : pwallet->ResubmitWalletTransactions(node::TxBroadcast::MEMPOOL_NO_BROADCAST, /*force=*/true);
407 : :
408 [ - + ]: 589 : if (pwallet->IsAbortingRescan()) {
409 [ # # # # ]: 0 : throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user.");
410 : : }
411 : :
412 [ + + ]: 589 : if (scanned_time > lowest_timestamp) {
413 [ + - + - ]: 1 : std::vector<UniValue> results = response.getValues();
414 [ + - ]: 1 : response.clear();
415 [ + - ]: 1 : response.setArray();
416 : :
417 : : // Compose the response
418 [ - + + + ]: 2 : for (unsigned int i = 0; i < requests.size(); ++i) {
419 [ + - + - ]: 1 : const UniValue& request = requests.getValues().at(i);
420 : :
421 : : // If the descriptor timestamp is within the successfully scanned
422 : : // range, or if the import result already has an error set, let
423 : : // the result stand unmodified. Otherwise replace the result
424 : : // with an error message.
425 [ + - + - : 2 : if (scanned_time <= GetImportTimestamp(request, now) || results.at(i).exists("error")) {
+ - + - +
- + - - +
- - ]
426 [ # # # # : 0 : response.push_back(results.at(i));
# # ]
427 : : } else {
428 : 1 : std::string error_msg{strprintf("Rescan failed for descriptor with timestamp %d. There "
429 : : "was an error reading a block from time %d, which is after or within %d seconds "
430 : : "of key creation, and could contain transactions pertaining to the desc. As a "
431 : : "result, transactions and coins using this desc may not appear in the wallet.",
432 [ + - + - ]: 1 : GetImportTimestamp(request, now), scanned_time - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)};
433 [ + - - + ]: 1 : if (pwallet->chain().havePruned()) {
434 [ # # ]: 0 : error_msg += strprintf(" This error could be caused by pruning or data corruption "
435 : : "(see bitcoind log for details) and could be dealt with by downloading and "
436 : 0 : "rescanning the relevant blocks (see -reindex option and rescanblockchain RPC).");
437 [ + - + - ]: 1 : } else if (pwallet->chain().hasAssumedValidChain()) {
438 [ + - ]: 2 : error_msg += strprintf(" This error is likely caused by an in-progress assumeutxo "
439 : : "background sync. Check logs or getchainstates RPC for assumeutxo background "
440 : 1 : "sync progress and try again later.");
441 : : } else {
442 [ # # ]: 0 : error_msg += strprintf(" This error could potentially caused by data corruption. If "
443 : 0 : "the issue persists you may want to reindex (see -reindex option).");
444 : : }
445 : :
446 : 1 : UniValue result = UniValue(UniValue::VOBJ);
447 [ + - + - : 2 : result.pushKV("success", UniValue(false));
+ - ]
448 [ + - + - : 2 : result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, error_msg));
+ - ]
449 [ + - ]: 1 : response.push_back(std::move(result));
450 : 1 : }
451 : : }
452 : 1 : }
453 : : }
454 : :
455 : 621 : return response;
456 [ + - ]: 1863 : },
457 [ + - + - : 24429 : };
+ - + - +
+ + + + +
- - - - -
- ]
458 [ + - + - : 31614 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - - -
- ]
459 : :
460 : 966 : RPCHelpMan listdescriptors()
461 : : {
462 : 966 : return RPCHelpMan{
463 : 966 : "listdescriptors",
464 [ + - ]: 1932 : "List all descriptors present in a wallet.\n",
465 : : {
466 [ + - + - : 2898 : {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private descriptors."}
+ - ]
467 : : },
468 [ + - + - : 3864 : RPCResult{RPCResult::Type::OBJ, "", "", {
+ - ]
469 [ + - + - ]: 1932 : {RPCResult::Type::STR, "wallet_name", "Name of wallet this operation was performed on"},
470 [ + - + - ]: 1932 : {RPCResult::Type::ARR, "descriptors", "Array of descriptor objects (sorted by descriptor string representation)",
471 : : {
472 [ + - + - ]: 1932 : {RPCResult::Type::OBJ, "", "", {
473 [ + - + - ]: 1932 : {RPCResult::Type::STR, "desc", "Descriptor string representation"},
474 [ + - + - ]: 1932 : {RPCResult::Type::NUM, "timestamp", "The creation time of the descriptor"},
475 [ + - + - ]: 1932 : {RPCResult::Type::BOOL, "active", "Whether this descriptor is currently used to generate new addresses"},
476 [ + - + - ]: 1932 : {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"},
477 [ + - + - ]: 1932 : {RPCResult::Type::ARR_FIXED, "range", /*optional=*/true, "Defined only for ranged descriptors", {
478 [ + - + - ]: 1932 : {RPCResult::Type::NUM, "", "Range start inclusive"},
479 [ + - + - ]: 1932 : {RPCResult::Type::NUM, "", "Range end inclusive"},
480 : : }},
481 [ + - + - ]: 1932 : {RPCResult::Type::NUM, "next", /*optional=*/true, "Same as next_index field. Kept for compatibility reason."},
482 [ + - + - ]: 1932 : {RPCResult::Type::NUM, "next_index", /*optional=*/true, "The next index to generate addresses from; defined only for ranged descriptors"},
483 : : }},
484 : : }}
485 [ + - + - : 24150 : }},
+ - + - +
- + + + +
+ + + + -
- - - - -
- - ]
486 : 966 : RPCExamples{
487 [ + - + - : 1932 : HelpExampleCli("listdescriptors", "") + HelpExampleRpc("listdescriptors", "")
+ - + - +
- + - +
- ]
488 [ + - + - : 3864 : + HelpExampleCli("listdescriptors", "true") + HelpExampleRpc("listdescriptors", "true")
+ - + - +
- + - + -
+ - ]
489 [ + - ]: 966 : },
490 : 966 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
491 : : {
492 [ - + ]: 150 : const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request);
493 [ - + ]: 149 : if (!wallet) return UniValue::VNULL;
494 : :
495 [ + - + + : 149 : const bool priv = !request.params[0].isNull() && request.params[0].get_bool();
+ - + - +
+ ]
496 : 60 : if (priv) {
497 [ + + ]: 60 : EnsureWalletIsUnlocked(*wallet);
498 : : }
499 : :
500 [ + - ]: 148 : LOCK(wallet->cs_wallet);
501 : :
502 [ + - ]: 148 : const auto active_spk_mans = wallet->GetActiveScriptPubKeyMans();
503 : :
504 [ - - ]: 3035 : struct WalletDescInfo {
505 : : std::string descriptor;
506 : : uint64_t creation_time;
507 : : bool active;
508 : : std::optional<bool> internal;
509 : : std::optional<std::pair<int64_t,int64_t>> range;
510 : : int64_t next_index;
511 : : };
512 : :
513 : 148 : std::vector<WalletDescInfo> wallet_descriptors;
514 [ + - + + ]: 1227 : for (const auto& spk_man : wallet->GetAllScriptPubKeyMans()) {
515 [ + - ]: 1080 : const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man);
516 [ - + ]: 1080 : if (!desc_spk_man) {
517 [ # # # # ]: 0 : throw JSONRPCError(RPC_WALLET_ERROR, "Unexpected ScriptPubKey manager type.");
518 : : }
519 [ + - ]: 1080 : LOCK(desc_spk_man->cs_desc_man);
520 [ + - ]: 1080 : const auto& wallet_descriptor = desc_spk_man->GetWalletDescriptor();
521 [ + - ]: 1080 : std::string descriptor;
522 [ + - + + ]: 1080 : if (!desc_spk_man->GetDescriptorString(descriptor, priv)) {
523 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_ERROR, "Can't get descriptor string.");
524 : : }
525 [ + - ]: 1079 : const bool is_range = wallet_descriptor.descriptor->IsRange();
526 [ - + ]: 2158 : wallet_descriptors.push_back({
527 : : descriptor,
528 : 1079 : wallet_descriptor.creation_time,
529 : 2158 : active_spk_mans.count(desc_spk_man) != 0,
530 [ + - ]: 1079 : wallet->IsInternalScriptPubKeyMan(desc_spk_man),
531 [ + + ]: 1079 : is_range ? std::optional(std::make_pair(wallet_descriptor.range_start, wallet_descriptor.range_end)) : std::nullopt,
532 : 1079 : wallet_descriptor.next_index
533 : : });
534 [ + - ]: 2161 : }
535 : :
536 : 147 : std::sort(wallet_descriptors.begin(), wallet_descriptors.end(), [](const auto& a, const auto& b) {
537 [ - - - - : 2963 : return a.descriptor < b.descriptor;
+ + - - -
- - - - -
- - - - -
- - - +
+ ]
538 : : });
539 : :
540 : 147 : UniValue descriptors(UniValue::VARR);
541 [ + + ]: 1226 : for (const WalletDescInfo& info : wallet_descriptors) {
542 : 1079 : UniValue spk(UniValue::VOBJ);
543 [ + - + - : 2158 : spk.pushKV("desc", info.descriptor);
+ - ]
544 [ + - + - : 2158 : spk.pushKV("timestamp", info.creation_time);
+ - ]
545 [ + - + - : 2158 : spk.pushKV("active", info.active);
+ - ]
546 [ + + ]: 1079 : if (info.internal.has_value()) {
547 [ + - + - : 2066 : spk.pushKV("internal", info.internal.value());
+ - ]
548 : : }
549 [ + + ]: 1079 : if (info.range.has_value()) {
550 : 1048 : UniValue range(UniValue::VARR);
551 [ + - + - ]: 1048 : range.push_back(info.range->first);
552 [ + - + - ]: 1048 : range.push_back(info.range->second - 1);
553 [ + - + - ]: 2096 : spk.pushKV("range", std::move(range));
554 [ + - + - : 2096 : spk.pushKV("next", info.next_index);
+ - ]
555 [ + - + - : 2096 : spk.pushKV("next_index", info.next_index);
+ - ]
556 : 1048 : }
557 [ + - ]: 1079 : descriptors.push_back(std::move(spk));
558 : 1079 : }
559 : :
560 : 147 : UniValue response(UniValue::VOBJ);
561 [ + - + - : 294 : response.pushKV("wallet_name", wallet->GetName());
+ - ]
562 [ + - + - ]: 294 : response.pushKV("descriptors", std::move(descriptors));
563 : :
564 : 147 : return response;
565 [ + - + - : 2602 : },
+ - ]
566 [ + - + - : 4830 : };
+ + - - ]
567 [ + - + - : 13524 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - - - -
- - - ]
568 : :
569 : 882 : RPCHelpMan backupwallet()
570 : : {
571 : 882 : return RPCHelpMan{
572 : 882 : "backupwallet",
573 [ + - ]: 1764 : "Safely copies the current wallet file to the specified destination, which can either be a directory or a path with a filename.\n",
574 : : {
575 [ + - + - ]: 1764 : {"destination", RPCArg::Type::STR, RPCArg::Optional::NO, "The destination directory or file"},
576 : : },
577 [ + - + - : 1764 : RPCResult{RPCResult::Type::NONE, "", ""},
+ - + - ]
578 : 882 : RPCExamples{
579 [ + - + - : 1764 : HelpExampleCli("backupwallet", "\"backup.dat\"")
+ - ]
580 [ + - + - : 3528 : + HelpExampleRpc("backupwallet", "\"backup.dat\"")
+ - + - ]
581 [ + - ]: 882 : },
582 : 882 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
583 : : {
584 [ - + ]: 66 : const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
585 [ - + ]: 66 : if (!pwallet) return UniValue::VNULL;
586 : :
587 : : // Make sure the results are valid at least up to the most recent block
588 : : // the user could have gotten from another RPC command prior to now
589 [ + - ]: 66 : pwallet->BlockUntilSyncedToCurrentChain();
590 : :
591 [ + - ]: 66 : LOCK(pwallet->cs_wallet);
592 : :
593 [ + - + - : 66 : std::string strDest = request.params[0].get_str();
- + ]
594 [ + - + + ]: 66 : if (!pwallet->BackupWallet(strDest)) {
595 [ + - + - ]: 8 : throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
596 : : }
597 : :
598 : 62 : return UniValue::VNULL;
599 [ + - ]: 194 : },
600 [ + - + - : 4410 : };
+ + - - ]
601 [ + - ]: 1764 : }
602 : :
603 : :
604 : 842 : RPCHelpMan restorewallet()
605 : : {
606 : 842 : return RPCHelpMan{
607 : 842 : "restorewallet",
608 [ + - ]: 1684 : "Restores and loads a wallet from backup.\n"
609 : : "\nThe rescan is significantly faster if block filters are available"
610 : : "\n(using startup option \"-blockfilterindex=1\").\n",
611 : : {
612 [ + - + - ]: 1684 : {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name that will be applied to the restored wallet"},
613 [ + - + - ]: 1684 : {"backup_file", RPCArg::Type::STR, RPCArg::Optional::NO, "The backup file that will be used to restore the wallet."},
614 [ + - + - ]: 1684 : {"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."},
615 : : },
616 [ + - ]: 1684 : RPCResult{
617 [ + - + - ]: 1684 : RPCResult::Type::OBJ, "", "",
618 : : {
619 [ + - + - ]: 1684 : {RPCResult::Type::STR, "name", "The wallet name if restored successfully."},
620 [ + - + - ]: 1684 : {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to restoring and loading the wallet.",
621 : : {
622 [ + - + - ]: 1684 : {RPCResult::Type::STR, "", ""},
623 : : }},
624 : : }
625 [ + - + - : 5894 : },
+ - + + +
+ - - -
- ]
626 : 842 : RPCExamples{
627 [ + - + - : 1684 : HelpExampleCli("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"")
+ - ]
628 [ + - + - : 3368 : + HelpExampleRpc("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"")
+ - + - ]
629 [ + - + - : 5894 : + HelpExampleCliNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}})
+ - + - +
+ - - ]
630 [ + - + - : 5894 : + HelpExampleRpcNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}})
+ - + - +
+ - - ]
631 [ + - ]: 842 : },
632 : 842 : [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
633 : : {
634 : :
635 : 26 : WalletContext& context = EnsureWalletContext(request.context);
636 : :
637 [ - + ]: 26 : auto backup_file = fs::u8path(request.params[1].get_str());
638 : :
639 [ + - + - : 26 : std::string wallet_name = request.params[0].get_str();
- + ]
640 : :
641 [ + - + - : 26 : std::optional<bool> load_on_start = request.params[2].isNull() ? std::nullopt : std::optional<bool>(request.params[2].get_bool());
- - - - ]
642 : :
643 : 26 : DatabaseStatus status;
644 [ + - ]: 26 : bilingual_str error;
645 : 26 : std::vector<bilingual_str> warnings;
646 : :
647 [ + - ]: 26 : const std::shared_ptr<CWallet> wallet = RestoreWallet(context, backup_file, wallet_name, load_on_start, status, error, warnings);
648 : :
649 [ + + + + ]: 52 : HandleWalletError(wallet, status, error);
650 : :
651 : 14 : UniValue obj(UniValue::VOBJ);
652 [ + - + - : 28 : obj.pushKV("name", wallet->GetName());
+ - ]
653 [ + - ]: 14 : PushWarnings(warnings, obj);
654 : :
655 [ + - ]: 14 : return obj;
656 : :
657 : 78 : },
658 [ + - + - : 5894 : };
+ + - - ]
659 [ + - + - : 9262 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
- - - - -
- - - ]
660 : : } // namespace wallet
|