/tmp/bitcoin/src/wallet/rpc/backup.cpp
Line | Count | Source |
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/check.h> |
21 | | #include <util/fs.h> |
22 | | #include <util/time.h> |
23 | | #include <util/translation.h> |
24 | | #include <wallet/export.h> |
25 | | #include <wallet/imports.h> |
26 | | #include <wallet/rpc/util.h> |
27 | | #include <wallet/scan.h> |
28 | | #include <wallet/wallet.h> |
29 | | |
30 | | #include <cstdint> |
31 | | #include <fstream> |
32 | | #include <tuple> |
33 | | #include <string> |
34 | | |
35 | | #include <univalue.h> |
36 | | |
37 | | |
38 | | |
39 | | using interfaces::FoundBlock; |
40 | | |
41 | | namespace wallet { |
42 | | RPCMethod importprunedfunds() |
43 | 894 | { |
44 | 894 | return RPCMethod{ |
45 | 894 | "importprunedfunds", |
46 | 894 | "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", |
47 | 894 | { |
48 | 894 | {"rawtransaction", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A raw transaction in hex funding an already-existing address in wallet"}, |
49 | 894 | {"txoutproof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex output from gettxoutproof that contains the transaction"}, |
50 | 894 | }, |
51 | 894 | RPCResult{RPCResult::Type::NONE, "", ""}, |
52 | 894 | RPCExamples{""}, |
53 | 894 | [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue |
54 | 894 | { |
55 | 9 | std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); |
56 | 9 | if (!pwallet) return UniValue::VNULL; |
57 | | |
58 | 9 | CMutableTransaction tx; |
59 | 9 | if (!DecodeHexTx(tx, request.params[0].get_str())) { |
60 | 1 | throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input."); |
61 | 1 | } |
62 | | |
63 | 8 | CMerkleBlock merkleBlock; |
64 | 8 | SpanReader{ParseHexV(request.params[1], "proof")} >> merkleBlock; |
65 | | |
66 | | //Search partial merkle tree in proof for our transaction and index in valid block |
67 | 8 | std::vector<Txid> vMatch; |
68 | 8 | std::vector<unsigned int> vIndex; |
69 | 8 | if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) { |
70 | 1 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock"); |
71 | 1 | } |
72 | | |
73 | 7 | LOCK(pwallet->cs_wallet); |
74 | 7 | int height; |
75 | 7 | if (!pwallet->chain().findAncestorByHash(pwallet->GetLastBlockHash(), merkleBlock.header.GetHash(), FoundBlock().height(height))) { |
76 | 1 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); |
77 | 1 | } |
78 | | |
79 | 6 | std::vector<Txid>::const_iterator it; |
80 | 6 | if ((it = std::find(vMatch.begin(), vMatch.end(), tx.GetHash())) == vMatch.end()) { |
81 | 1 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof"); |
82 | 1 | } |
83 | | |
84 | 5 | unsigned int txnIndex = vIndex[it - vMatch.begin()]; |
85 | | |
86 | 5 | const CTransactionRef tx_ref = MakeTransactionRef(tx); |
87 | 5 | auto tx_state = TxStateConfirmed{merkleBlock.header.GetHash(), height, static_cast<int>(txnIndex)}; |
88 | 5 | if (pwallet->AddToWalletIfInvolvingMe(tx_ref, tx_state, /*rescanning_old_block=*/false)) { |
89 | 4 | return UniValue::VNULL; |
90 | 4 | } |
91 | | |
92 | 1 | throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction"); |
93 | 5 | }, |
94 | 894 | }; |
95 | 894 | } |
96 | | |
97 | | /** |
98 | | * Converts the timestamp from UniValue data to an int64_t. |
99 | | * |
100 | | * @returns The import timestamp in int64_t, or std::nullopt if now was provided. |
101 | | */ |
102 | | static std::optional<int64_t> GetImportTimestamp(const UniValue& data) |
103 | 778 | { |
104 | 778 | if (data.exists("timestamp")) { |
105 | 777 | const UniValue& timestamp = data["timestamp"]; |
106 | 777 | if (timestamp.isNum()) { |
107 | 220 | const int64_t value{timestamp.getInt<int64_t>()}; |
108 | 220 | if (value < 0) { |
109 | 1 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Timestamp must not be negative"); |
110 | 1 | } |
111 | 219 | return value; |
112 | 557 | } else if (timestamp.isStr() && timestamp.get_str() == "now") { |
113 | 556 | return std::nullopt; // std::nullopt means use the current best block's MTP time |
114 | 556 | } |
115 | 1 | throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type()))); |
116 | 777 | } |
117 | 1 | throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key"); |
118 | 778 | } |
119 | | |
120 | | static ImportDescriptorRequest ProcessUniValueDescriptor(const UniValue& data, std::optional<int64_t> timestamp) |
121 | 775 | { |
122 | 775 | ImportDescriptorRequest request; |
123 | 775 | if (!data.exists("desc")) { |
124 | 2 | throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor not found."); |
125 | 2 | } |
126 | 773 | request.descriptor = data["desc"].get_str(); |
127 | 773 | request.label = LabelFromValue(data["label"]); |
128 | 773 | request.timestamp = timestamp; |
129 | 773 | if (data.exists("active")) request.active = data["active"].get_bool(); |
130 | 773 | if (data.exists("internal")) request.internal = data["internal"].get_bool(); |
131 | 773 | if (data.exists("range")) request.range = ParseDescriptorRange(data["range"]); |
132 | 773 | if (data.exists("next_index")) request.next_index = data["next_index"].getInt<int64_t>(); |
133 | 773 | return request; |
134 | 775 | } |
135 | | |
136 | | RPCMethod importdescriptors() |
137 | 1.56k | { |
138 | 1.56k | return RPCMethod{ |
139 | 1.56k | "importdescriptors", |
140 | 1.56k | "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" |
141 | 1.56k | "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" |
142 | 1.56k | "\nNote: This call can take over an hour to complete if using an early timestamp; during that time, other rpc calls\n" |
143 | 1.56k | "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n" |
144 | 1.56k | "The rescan is significantly faster if block filters are available (using startup option \"-blockfilterindex=1\").\n", |
145 | 1.56k | { |
146 | 1.56k | {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported", |
147 | 1.56k | { |
148 | 1.56k | {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", |
149 | 1.56k | { |
150 | 1.56k | {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "Descriptor to import."}, |
151 | 1.56k | {"active", RPCArg::Type::BOOL, RPCArg::Default{false}, "Set this descriptor to be the active descriptor for the corresponding output type/externality"}, |
152 | 1.56k | {"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"}, |
153 | 1.56k | {"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"}, |
154 | 1.56k | {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Time from which to start rescanning the blockchain for this descriptor, in " + UNIX_EPOCH_TIME + "\n" |
155 | 1.56k | "Use the string \"now\" to substitute the current synced blockchain time.\n" |
156 | 1.56k | "\"now\" can be specified to bypass scanning, for outputs which are known to never have been used, and\n" |
157 | 1.56k | "0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest timestamp\n" |
158 | 1.56k | "of all descriptors being imported will be scanned as well as the mempool.", |
159 | 1.56k | RPCArgOptions{.type_str={"timestamp | \"now\"", "integer / string"}} |
160 | 1.56k | }, |
161 | 1.56k | {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether matching outputs should be treated as not incoming payments (e.g. change)"}, |
162 | 1.56k | {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false. Disabled for ranged descriptors"}, |
163 | 1.56k | }, |
164 | 1.56k | }, |
165 | 1.56k | }, |
166 | 1.56k | RPCArgOptions{.oneline_description="requests"}}, |
167 | 1.56k | }, |
168 | 1.56k | RPCResult{ |
169 | 1.56k | RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result", |
170 | 1.56k | { |
171 | 1.56k | {RPCResult::Type::OBJ, "", "", |
172 | 1.56k | { |
173 | 1.56k | {RPCResult::Type::BOOL, "success", ""}, |
174 | 1.56k | {RPCResult::Type::ARR, "warnings", /*optional=*/true, "", |
175 | 1.56k | { |
176 | 1.56k | {RPCResult::Type::STR, "", ""}, |
177 | 1.56k | }}, |
178 | 1.56k | {RPCResult::Type::OBJ, "error", /*optional=*/true, "", |
179 | 1.56k | { |
180 | 1.56k | {RPCResult::Type::NUM, "code", "JSONRPC error code"}, |
181 | 1.56k | {RPCResult::Type::STR, "message", "JSONRPC error message"}, |
182 | 1.56k | }}, |
183 | 1.56k | }}, |
184 | 1.56k | } |
185 | 1.56k | }, |
186 | 1.56k | RPCExamples{ |
187 | 1.56k | HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"internal\": true }, " |
188 | 1.56k | "{ \"desc\": \"<my descriptor 2>\", \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") + |
189 | 1.56k | HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"active\": true, \"range\": [0,100], \"label\": \"<my bech32 wallet>\" }]'") |
190 | 1.56k | }, |
191 | 1.56k | [](const RPCMethod& self, const JSONRPCRequest& main_request) -> UniValue |
192 | 1.56k | { |
193 | 684 | std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(main_request); |
194 | 684 | if (!pwallet) return UniValue::VNULL; |
195 | 684 | CWallet& wallet{*pwallet}; |
196 | | |
197 | 684 | const UniValue& univalue_requests = main_request.params[0]; |
198 | | // One result per input, in input order. |
199 | 684 | std::vector<UniValue> results(univalue_requests.size()); |
200 | | // Successfully parsed requests, each with the index of the input it came from. |
201 | 684 | struct ParsedRequest { |
202 | 684 | size_t input_index; |
203 | 684 | ImportDescriptorRequest request; |
204 | 684 | }; |
205 | 684 | std::vector<ParsedRequest> requests; |
206 | | |
207 | | // Malformed inputs (e.g. invalid label) are returned as per-item failures. |
208 | 1.45k | for (size_t i = 0; i < univalue_requests.size(); ++i) { |
209 | | // Throws a top-level RPC error if "timestamp" is missing or invalid |
210 | 778 | std::optional<int64_t> timestamp = GetImportTimestamp(univalue_requests[i]); |
211 | 778 | try { |
212 | 778 | requests.push_back({i, ProcessUniValueDescriptor(univalue_requests[i], timestamp)}); |
213 | 778 | } catch (const UniValue& e) { |
214 | 8 | results[i] = UniValue(UniValue::VOBJ); |
215 | 8 | results[i].pushKV("success", UniValue(false)); |
216 | 8 | results[i].pushKV("error", e); |
217 | 8 | } |
218 | 778 | } |
219 | | |
220 | | // Hand off the successfully parsed requests to the batch importer, which |
221 | | // handles wallet locking, rescanning and rescan-failure error composition. |
222 | 684 | std::vector<ImportDescriptorRequest> descriptor_requests; |
223 | 681 | descriptor_requests.reserve(requests.size()); |
224 | 767 | for (auto& parsed : requests) { |
225 | 767 | descriptor_requests.push_back(std::move(parsed.request)); |
226 | 767 | } |
227 | | |
228 | 681 | std::vector<ImportResult> import_results{ProcessDescriptorsImport(wallet, descriptor_requests)}; |
229 | | |
230 | | // Wallet-wide precondition failure (e.g. already rescanning, or locked): |
231 | | // surface as a top-level RPC error. |
232 | 681 | if (import_results.size() == 1 && import_results[0].has_error() && import_results[0].error->is_general_error) { |
233 | 4 | const ImportError& import_error = import_results[0].error.value(); |
234 | 4 | RPCErrorCode rpc_error_code{HandleWalletErrorCode(import_error.wallet_error.code)}; |
235 | 4 | throw JSONRPCError(rpc_error_code, import_error.wallet_error.message.original); |
236 | 4 | } |
237 | | |
238 | | // Translate each ImportResult into the per-input UniValue result. Inputs |
239 | | // that failed to parse already hold an error in results[] and are not |
240 | | // part of `requests`, so use input_index to map each import_results[k] |
241 | | // back to its slot. |
242 | 677 | CHECK_NONFATAL(import_results.size() == requests.size()); |
243 | 1.44k | for (size_t k = 0; k < requests.size(); ++k) { |
244 | 764 | UniValue& result = results[requests[k].input_index]; |
245 | 764 | const ImportResult& import_result = import_results[k]; |
246 | 764 | result = UniValue(UniValue::VOBJ); |
247 | 764 | UniValue warnings(UniValue::VARR); |
248 | 764 | if (import_result.has_error()) { |
249 | 35 | const WalletError& error = import_result.error.value().wallet_error; |
250 | 35 | auto write_error = [&result, &error](int code) { |
251 | 35 | result.pushKV("success", false); |
252 | 35 | result.pushKV("error", JSONRPCError(code, error.message.original)); |
253 | 35 | }; |
254 | 35 | if (error.code == WalletErrorCode::UnlockNeeded) NONFATAL_UNREACHABLE(); |
255 | 35 | write_error(HandleWalletErrorCode(error.code)); |
256 | 729 | } else { |
257 | 729 | result.pushKV("success", true); |
258 | 729 | } |
259 | 764 | for (const auto& w : import_result.warnings) { |
260 | 600 | warnings.push_back(w); |
261 | 600 | } |
262 | 764 | PushWarnings(warnings, result); |
263 | 764 | } |
264 | | |
265 | 677 | UniValue response(UniValue::VARR); |
266 | 772 | for (UniValue& result : results) { |
267 | 772 | response.push_back(std::move(result)); |
268 | 772 | } |
269 | 677 | return response; |
270 | 681 | }, |
271 | 1.56k | }; |
272 | 1.56k | } |
273 | | |
274 | | RPCMethod listdescriptors() |
275 | 1.15k | { |
276 | 1.15k | return RPCMethod{ |
277 | 1.15k | "listdescriptors", |
278 | 1.15k | "List all descriptors present in a wallet.\n", |
279 | 1.15k | { |
280 | 1.15k | {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private descriptors."} |
281 | 1.15k | }, |
282 | 1.15k | RPCResult{RPCResult::Type::OBJ, "", "", { |
283 | 1.15k | {RPCResult::Type::STR, "wallet_name", "Name of wallet this operation was performed on"}, |
284 | 1.15k | {RPCResult::Type::ARR, "descriptors", "Array of descriptor objects (sorted by descriptor string representation)", |
285 | 1.15k | { |
286 | 1.15k | {RPCResult::Type::OBJ, "", "", { |
287 | 1.15k | {RPCResult::Type::STR, "desc", "Descriptor string representation"}, |
288 | 1.15k | {RPCResult::Type::NUM, "timestamp", "The creation time of the descriptor"}, |
289 | 1.15k | {RPCResult::Type::BOOL, "active", "Whether this descriptor is currently used to generate new addresses"}, |
290 | 1.15k | {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"}, |
291 | 1.15k | {RPCResult::Type::ARR_FIXED, "range", /*optional=*/true, "Defined only for ranged descriptors", { |
292 | 1.15k | {RPCResult::Type::NUM, "", "Range start inclusive"}, |
293 | 1.15k | {RPCResult::Type::NUM, "", "Range end inclusive"}, |
294 | 1.15k | }}, |
295 | 1.15k | {RPCResult::Type::NUM, "next", /*optional=*/true, "Same as next_index field. Kept for compatibility reason."}, |
296 | 1.15k | {RPCResult::Type::NUM, "next_index", /*optional=*/true, "The next index to generate addresses from; defined only for ranged descriptors"}, |
297 | 1.15k | }}, |
298 | 1.15k | }} |
299 | 1.15k | }}, |
300 | 1.15k | RPCExamples{ |
301 | 1.15k | HelpExampleCli("listdescriptors", "") + HelpExampleRpc("listdescriptors", "") |
302 | 1.15k | + HelpExampleCli("listdescriptors", "true") + HelpExampleRpc("listdescriptors", "true") |
303 | 1.15k | }, |
304 | 1.15k | [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue |
305 | 1.15k | { |
306 | 269 | const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request); |
307 | 269 | if (!wallet) return UniValue::VNULL; |
308 | | |
309 | 269 | const bool priv{self.Arg<bool>("private")}; |
310 | 269 | if (wallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && priv) { |
311 | 1 | throw JSONRPCError(RPC_WALLET_ERROR, "Can't get private descriptor string for watch-only wallets"); |
312 | 1 | } |
313 | 268 | if (priv) { |
314 | 88 | EnsureWalletIsUnlocked(*wallet); |
315 | 88 | } |
316 | | |
317 | 268 | LOCK(wallet->cs_wallet); |
318 | 268 | util::Expected<std::vector<WalletDescInfo>, std::string> exported = ExportDescriptors(*wallet, priv); |
319 | 268 | if (!exported) { |
320 | 0 | throw JSONRPCError(RPC_WALLET_ERROR, exported.error()); |
321 | 0 | } |
322 | 268 | std::vector<WalletDescInfo> wallet_descriptors = *exported; |
323 | | |
324 | 5.59k | std::sort(wallet_descriptors.begin(), wallet_descriptors.end(), [](const auto& a, const auto& b) { |
325 | 5.59k | return a.descriptor < b.descriptor; |
326 | 5.59k | }); |
327 | | |
328 | 268 | UniValue descriptors(UniValue::VARR); |
329 | 2.09k | for (const WalletDescInfo& info : wallet_descriptors) { |
330 | 2.09k | UniValue spk(UniValue::VOBJ); |
331 | 2.09k | spk.pushKV("desc", info.descriptor); |
332 | 2.09k | spk.pushKV("timestamp", info.creation_time); |
333 | 2.09k | spk.pushKV("active", info.active); |
334 | 2.09k | if (info.internal.has_value()) { |
335 | 1.90k | spk.pushKV("internal", info.internal.value()); |
336 | 1.90k | } |
337 | 2.09k | if (info.range.has_value()) { |
338 | 1.95k | UniValue range(UniValue::VARR); |
339 | 1.95k | range.push_back(info.range->first); |
340 | 1.95k | range.push_back(info.range->second - 1); |
341 | 1.95k | spk.pushKV("range", std::move(range)); |
342 | 1.95k | spk.pushKV("next", info.next_index); |
343 | 1.95k | spk.pushKV("next_index", info.next_index); |
344 | 1.95k | } |
345 | 2.09k | descriptors.push_back(std::move(spk)); |
346 | 2.09k | } |
347 | | |
348 | 268 | UniValue response(UniValue::VOBJ); |
349 | 268 | response.pushKV("wallet_name", wallet->GetName()); |
350 | 268 | response.pushKV("descriptors", std::move(descriptors)); |
351 | | |
352 | 268 | return response; |
353 | 268 | }, |
354 | 1.15k | }; |
355 | 1.15k | } |
356 | | |
357 | | RPCMethod backupwallet() |
358 | 954 | { |
359 | 954 | return RPCMethod{ |
360 | 954 | "backupwallet", |
361 | 954 | "Safely copies the current wallet file to the specified destination, which can either be a directory or a path with a filename.\n", |
362 | 954 | { |
363 | 954 | {"destination", RPCArg::Type::STR, RPCArg::Optional::NO, "The destination directory or file"}, |
364 | 954 | }, |
365 | 954 | RPCResult{RPCResult::Type::NONE, "", ""}, |
366 | 954 | RPCExamples{ |
367 | 954 | HelpExampleCli("backupwallet", "\"backup.dat\"") |
368 | 954 | + HelpExampleRpc("backupwallet", "\"backup.dat\"") |
369 | 954 | }, |
370 | 954 | [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue |
371 | 954 | { |
372 | 69 | const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); |
373 | 69 | if (!pwallet) return UniValue::VNULL; |
374 | | |
375 | | // Make sure the results are valid at least up to the most recent block |
376 | | // the user could have gotten from another RPC command prior to now |
377 | 69 | pwallet->BlockUntilSyncedToCurrentChain(); |
378 | | |
379 | 69 | LOCK(pwallet->cs_wallet); |
380 | | |
381 | 69 | std::string strDest = request.params[0].get_str(); |
382 | 69 | if (!pwallet->BackupWallet(strDest)) { |
383 | 4 | throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); |
384 | 4 | } |
385 | | |
386 | 65 | return UniValue::VNULL; |
387 | 69 | }, |
388 | 954 | }; |
389 | 954 | } |
390 | | |
391 | | |
392 | | RPCMethod restorewallet() |
393 | 932 | { |
394 | 932 | return RPCMethod{ |
395 | 932 | "restorewallet", |
396 | 932 | "Restores and loads a wallet from backup.\n" |
397 | 932 | "\nThe rescan is significantly faster if block filters are available" |
398 | 932 | "\n(using startup option \"-blockfilterindex=1\").\n", |
399 | 932 | { |
400 | 932 | {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name that will be applied to the restored wallet"}, |
401 | 932 | {"backup_file", RPCArg::Type::STR, RPCArg::Optional::NO, "The backup file that will be used to restore the wallet."}, |
402 | 932 | {"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."}, |
403 | 932 | }, |
404 | 932 | RPCResult{ |
405 | 932 | RPCResult::Type::OBJ, "", "", |
406 | 932 | { |
407 | 932 | {RPCResult::Type::STR, "name", "The wallet name if restored successfully."}, |
408 | 932 | {RPCResult::Type::ARR, "warnings", /*optional=*/true, "Warning messages, if any, related to restoring and loading the wallet.", |
409 | 932 | { |
410 | 932 | {RPCResult::Type::STR, "", ""}, |
411 | 932 | }}, |
412 | 932 | } |
413 | 932 | }, |
414 | 932 | RPCExamples{ |
415 | 932 | HelpExampleCli("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"") |
416 | 932 | + HelpExampleRpc("restorewallet", R"("testwallet", "home\\backups\\backup-file.bak")") |
417 | 932 | + HelpExampleCliNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak"}, {"load_on_startup", true}}) |
418 | 932 | + HelpExampleRpcNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak"}, {"load_on_startup", true}}) |
419 | 932 | }, |
420 | 932 | [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue |
421 | 932 | { |
422 | | |
423 | 47 | WalletContext& context = EnsureWalletContext(request.context); |
424 | | |
425 | 47 | auto backup_file = fs::u8path(request.params[1].get_str()); |
426 | | |
427 | 47 | std::string wallet_name = request.params[0].get_str(); |
428 | | |
429 | 47 | std::optional<bool> load_on_start = request.params[2].isNull() ? std::nullopt : std::optional<bool>(request.params[2].get_bool()); |
430 | | |
431 | 47 | DatabaseStatus status; |
432 | 47 | bilingual_str error; |
433 | 47 | std::vector<bilingual_str> warnings; |
434 | | |
435 | 47 | const std::shared_ptr<CWallet> wallet = RestoreWallet(context, backup_file, wallet_name, load_on_start, status, error, warnings); |
436 | | |
437 | 47 | HandleWalletError(wallet, status, error); |
438 | | |
439 | 47 | UniValue obj(UniValue::VOBJ); |
440 | 47 | obj.pushKV("name", wallet->GetName()); |
441 | 47 | PushWarnings(warnings, obj); |
442 | | |
443 | 47 | return obj; |
444 | | |
445 | 47 | }, |
446 | 932 | }; |
447 | 932 | } |
448 | | } // namespace wallet |