Merge #11605: [Wallet] Enable RBF by default in QT
[bitcoinplatinum.git] / src / wallet / rpcdump.cpp
blob41179ebd4a623d26e432c58d1618a767a14237c0
1 // Copyright (c) 2009-2016 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.
5 #include <base58.h>
6 #include <chain.h>
7 #include <rpc/safemode.h>
8 #include <rpc/server.h>
9 #include <wallet/init.h>
10 #include <validation.h>
11 #include <script/script.h>
12 #include <script/standard.h>
13 #include <sync.h>
14 #include <util.h>
15 #include <utiltime.h>
16 #include <wallet/wallet.h>
17 #include <merkleblock.h>
18 #include <core_io.h>
20 #include <wallet/rpcwallet.h>
22 #include <fstream>
23 #include <stdint.h>
25 #include <boost/algorithm/string.hpp>
26 #include <boost/date_time/posix_time/posix_time.hpp>
28 #include <univalue.h>
31 std::string static EncodeDumpTime(int64_t nTime) {
32 return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
35 int64_t static DecodeDumpTime(const std::string &str) {
36 static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
37 static const std::locale loc(std::locale::classic(),
38 new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
39 std::istringstream iss(str);
40 iss.imbue(loc);
41 boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
42 iss >> ptime;
43 if (ptime.is_not_a_date_time())
44 return 0;
45 return (ptime - epoch).total_seconds();
48 std::string static EncodeDumpString(const std::string &str) {
49 std::stringstream ret;
50 for (unsigned char c : str) {
51 if (c <= 32 || c >= 128 || c == '%') {
52 ret << '%' << HexStr(&c, &c + 1);
53 } else {
54 ret << c;
57 return ret.str();
60 std::string DecodeDumpString(const std::string &str) {
61 std::stringstream ret;
62 for (unsigned int pos = 0; pos < str.length(); pos++) {
63 unsigned char c = str[pos];
64 if (c == '%' && pos+2 < str.length()) {
65 c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
66 ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
67 pos += 2;
69 ret << c;
71 return ret.str();
74 UniValue importprivkey(const JSONRPCRequest& request)
76 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
77 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
78 return NullUniValue;
81 if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
82 throw std::runtime_error(
83 "importprivkey \"privkey\" ( \"label\" ) ( rescan )\n"
84 "\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\n"
85 "\nArguments:\n"
86 "1. \"privkey\" (string, required) The private key (see dumpprivkey)\n"
87 "2. \"label\" (string, optional, default=\"\") An optional label\n"
88 "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
89 "\nNote: This call can take minutes to complete if rescan is true.\n"
90 "\nExamples:\n"
91 "\nDump a private key\n"
92 + HelpExampleCli("dumpprivkey", "\"myaddress\"") +
93 "\nImport the private key with rescan\n"
94 + HelpExampleCli("importprivkey", "\"mykey\"") +
95 "\nImport using a label and without rescan\n"
96 + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
97 "\nImport using default blank label and without rescan\n"
98 + HelpExampleCli("importprivkey", "\"mykey\" \"\" false") +
99 "\nAs a JSON-RPC call\n"
100 + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")
104 LOCK2(cs_main, pwallet->cs_wallet);
106 EnsureWalletIsUnlocked(pwallet);
108 std::string strSecret = request.params[0].get_str();
109 std::string strLabel = "";
110 if (!request.params[1].isNull())
111 strLabel = request.params[1].get_str();
113 // Whether to perform rescan after import
114 bool fRescan = true;
115 if (!request.params[2].isNull())
116 fRescan = request.params[2].get_bool();
118 if (fRescan && fPruneMode)
119 throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
121 CBitcoinSecret vchSecret;
122 bool fGood = vchSecret.SetString(strSecret);
124 if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
126 CKey key = vchSecret.GetKey();
127 if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
129 CPubKey pubkey = key.GetPubKey();
130 assert(key.VerifyPubKey(pubkey));
131 CKeyID vchAddress = pubkey.GetID();
133 pwallet->MarkDirty();
134 pwallet->SetAddressBook(vchAddress, strLabel, "receive");
136 // Don't throw error in case a key is already there
137 if (pwallet->HaveKey(vchAddress)) {
138 return NullUniValue;
141 pwallet->mapKeyMetadata[vchAddress].nCreateTime = 1;
143 if (!pwallet->AddKeyPubKey(key, pubkey)) {
144 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
147 // whenever a key is imported, we need to scan the whole chain
148 pwallet->UpdateTimeFirstKey(1);
150 if (fRescan) {
151 pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
155 return NullUniValue;
158 UniValue abortrescan(const JSONRPCRequest& request)
160 CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
161 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
162 return NullUniValue;
165 if (request.fHelp || request.params.size() > 0)
166 throw std::runtime_error(
167 "abortrescan\n"
168 "\nStops current wallet rescan triggered by an RPC call, e.g. by an importprivkey call.\n"
169 "\nExamples:\n"
170 "\nImport a private key\n"
171 + HelpExampleCli("importprivkey", "\"mykey\"") +
172 "\nAbort the running wallet rescan\n"
173 + HelpExampleCli("abortrescan", "") +
174 "\nAs a JSON-RPC call\n"
175 + HelpExampleRpc("abortrescan", "")
178 ObserveSafeMode();
179 if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false;
180 pwallet->AbortRescan();
181 return true;
184 void ImportAddress(CWallet*, const CTxDestination& dest, const std::string& strLabel);
185 void ImportScript(CWallet* const pwallet, const CScript& script, const std::string& strLabel, bool isRedeemScript)
187 if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
188 throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
191 pwallet->MarkDirty();
193 if (!pwallet->HaveWatchOnly(script) && !pwallet->AddWatchOnly(script, 0 /* nCreateTime */)) {
194 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
197 if (isRedeemScript) {
198 if (!pwallet->HaveCScript(script) && !pwallet->AddCScript(script)) {
199 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
201 ImportAddress(pwallet, CScriptID(script), strLabel);
202 } else {
203 CTxDestination destination;
204 if (ExtractDestination(script, destination)) {
205 pwallet->SetAddressBook(destination, strLabel, "receive");
210 void ImportAddress(CWallet* const pwallet, const CTxDestination& dest, const std::string& strLabel)
212 CScript script = GetScriptForDestination(dest);
213 ImportScript(pwallet, script, strLabel, false);
214 // add to address book or update label
215 if (IsValidDestination(dest))
216 pwallet->SetAddressBook(dest, strLabel, "receive");
219 UniValue importaddress(const JSONRPCRequest& request)
221 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
222 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
223 return NullUniValue;
226 if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
227 throw std::runtime_error(
228 "importaddress \"address\" ( \"label\" rescan p2sh )\n"
229 "\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n"
230 "\nArguments:\n"
231 "1. \"script\" (string, required) The hex-encoded script (or address)\n"
232 "2. \"label\" (string, optional, default=\"\") An optional label\n"
233 "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
234 "4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n"
235 "\nNote: This call can take minutes to complete if rescan is true.\n"
236 "If you have the full public key, you should call importpubkey instead of this.\n"
237 "\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n"
238 "as change, and not show up in many RPCs.\n"
239 "\nExamples:\n"
240 "\nImport a script with rescan\n"
241 + HelpExampleCli("importaddress", "\"myscript\"") +
242 "\nImport using a label without rescan\n"
243 + HelpExampleCli("importaddress", "\"myscript\" \"testing\" false") +
244 "\nAs a JSON-RPC call\n"
245 + HelpExampleRpc("importaddress", "\"myscript\", \"testing\", false")
249 std::string strLabel = "";
250 if (!request.params[1].isNull())
251 strLabel = request.params[1].get_str();
253 // Whether to perform rescan after import
254 bool fRescan = true;
255 if (!request.params[2].isNull())
256 fRescan = request.params[2].get_bool();
258 if (fRescan && fPruneMode)
259 throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
261 // Whether to import a p2sh version, too
262 bool fP2SH = false;
263 if (!request.params[3].isNull())
264 fP2SH = request.params[3].get_bool();
266 LOCK2(cs_main, pwallet->cs_wallet);
268 CTxDestination dest = DecodeDestination(request.params[0].get_str());
269 if (IsValidDestination(dest)) {
270 if (fP2SH) {
271 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead");
273 ImportAddress(pwallet, dest, strLabel);
274 } else if (IsHex(request.params[0].get_str())) {
275 std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
276 ImportScript(pwallet, CScript(data.begin(), data.end()), strLabel, fP2SH);
277 } else {
278 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address or script");
281 if (fRescan)
283 pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
284 pwallet->ReacceptWalletTransactions();
287 return NullUniValue;
290 UniValue importprunedfunds(const JSONRPCRequest& request)
292 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
293 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
294 return NullUniValue;
297 if (request.fHelp || request.params.size() != 2)
298 throw std::runtime_error(
299 "importprunedfunds\n"
300 "\nImports 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"
301 "\nArguments:\n"
302 "1. \"rawtransaction\" (string, required) A raw transaction in hex funding an already-existing address in wallet\n"
303 "2. \"txoutproof\" (string, required) The hex output from gettxoutproof that contains the transaction\n"
306 CMutableTransaction tx;
307 if (!DecodeHexTx(tx, request.params[0].get_str()))
308 throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
309 uint256 hashTx = tx.GetHash();
310 CWalletTx wtx(pwallet, MakeTransactionRef(std::move(tx)));
312 CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION);
313 CMerkleBlock merkleBlock;
314 ssMB >> merkleBlock;
316 //Search partial merkle tree in proof for our transaction and index in valid block
317 std::vector<uint256> vMatch;
318 std::vector<unsigned int> vIndex;
319 unsigned int txnIndex = 0;
320 if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {
322 LOCK(cs_main);
324 if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
325 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
327 std::vector<uint256>::const_iterator it;
328 if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) {
329 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
332 txnIndex = vIndex[it - vMatch.begin()];
334 else {
335 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
338 wtx.nIndex = txnIndex;
339 wtx.hashBlock = merkleBlock.header.GetHash();
341 LOCK2(cs_main, pwallet->cs_wallet);
343 if (pwallet->IsMine(*wtx.tx)) {
344 pwallet->AddToWallet(wtx, false);
345 return NullUniValue;
348 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
351 UniValue removeprunedfunds(const JSONRPCRequest& request)
353 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
354 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
355 return NullUniValue;
358 if (request.fHelp || request.params.size() != 1)
359 throw std::runtime_error(
360 "removeprunedfunds \"txid\"\n"
361 "\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\n"
362 "\nArguments:\n"
363 "1. \"txid\" (string, required) The hex-encoded id of the transaction you are deleting\n"
364 "\nExamples:\n"
365 + HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
366 "\nAs a JSON-RPC call\n"
367 + HelpExampleRpc("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"")
370 LOCK2(cs_main, pwallet->cs_wallet);
372 uint256 hash;
373 hash.SetHex(request.params[0].get_str());
374 std::vector<uint256> vHash;
375 vHash.push_back(hash);
376 std::vector<uint256> vHashOut;
378 if (pwallet->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) {
379 throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction.");
382 if(vHashOut.empty()) {
383 throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction does not exist in wallet.");
386 return NullUniValue;
389 UniValue importpubkey(const JSONRPCRequest& request)
391 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
392 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
393 return NullUniValue;
396 if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
397 throw std::runtime_error(
398 "importpubkey \"pubkey\" ( \"label\" rescan )\n"
399 "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n"
400 "\nArguments:\n"
401 "1. \"pubkey\" (string, required) The hex-encoded public key\n"
402 "2. \"label\" (string, optional, default=\"\") An optional label\n"
403 "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
404 "\nNote: This call can take minutes to complete if rescan is true.\n"
405 "\nExamples:\n"
406 "\nImport a public key with rescan\n"
407 + HelpExampleCli("importpubkey", "\"mypubkey\"") +
408 "\nImport using a label without rescan\n"
409 + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") +
410 "\nAs a JSON-RPC call\n"
411 + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false")
415 std::string strLabel = "";
416 if (!request.params[1].isNull())
417 strLabel = request.params[1].get_str();
419 // Whether to perform rescan after import
420 bool fRescan = true;
421 if (!request.params[2].isNull())
422 fRescan = request.params[2].get_bool();
424 if (fRescan && fPruneMode)
425 throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
427 if (!IsHex(request.params[0].get_str()))
428 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
429 std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
430 CPubKey pubKey(data.begin(), data.end());
431 if (!pubKey.IsFullyValid())
432 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
434 LOCK2(cs_main, pwallet->cs_wallet);
436 ImportAddress(pwallet, pubKey.GetID(), strLabel);
437 ImportScript(pwallet, GetScriptForRawPubKey(pubKey), strLabel, false);
439 if (fRescan)
441 pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
442 pwallet->ReacceptWalletTransactions();
445 return NullUniValue;
449 UniValue importwallet(const JSONRPCRequest& request)
451 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
452 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
453 return NullUniValue;
456 if (request.fHelp || request.params.size() != 1)
457 throw std::runtime_error(
458 "importwallet \"filename\"\n"
459 "\nImports keys from a wallet dump file (see dumpwallet). Requires a new wallet backup to include imported keys.\n"
460 "\nArguments:\n"
461 "1. \"filename\" (string, required) The wallet file\n"
462 "\nExamples:\n"
463 "\nDump the wallet\n"
464 + HelpExampleCli("dumpwallet", "\"test\"") +
465 "\nImport the wallet\n"
466 + HelpExampleCli("importwallet", "\"test\"") +
467 "\nImport using the json rpc call\n"
468 + HelpExampleRpc("importwallet", "\"test\"")
471 if (fPruneMode)
472 throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode");
474 LOCK2(cs_main, pwallet->cs_wallet);
476 EnsureWalletIsUnlocked(pwallet);
478 std::ifstream file;
479 file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate);
480 if (!file.is_open())
481 throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
483 int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();
485 bool fGood = true;
487 int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
488 file.seekg(0, file.beg);
490 pwallet->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
491 while (file.good()) {
492 pwallet->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
493 std::string line;
494 std::getline(file, line);
495 if (line.empty() || line[0] == '#')
496 continue;
498 std::vector<std::string> vstr;
499 boost::split(vstr, line, boost::is_any_of(" "));
500 if (vstr.size() < 2)
501 continue;
502 CBitcoinSecret vchSecret;
503 if (vchSecret.SetString(vstr[0])) {
504 CKey key = vchSecret.GetKey();
505 CPubKey pubkey = key.GetPubKey();
506 assert(key.VerifyPubKey(pubkey));
507 CKeyID keyid = pubkey.GetID();
508 if (pwallet->HaveKey(keyid)) {
509 LogPrintf("Skipping import of %s (key already present)\n", EncodeDestination(keyid));
510 continue;
512 int64_t nTime = DecodeDumpTime(vstr[1]);
513 std::string strLabel;
514 bool fLabel = true;
515 for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
516 if (boost::algorithm::starts_with(vstr[nStr], "#"))
517 break;
518 if (vstr[nStr] == "change=1")
519 fLabel = false;
520 if (vstr[nStr] == "reserve=1")
521 fLabel = false;
522 if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
523 strLabel = DecodeDumpString(vstr[nStr].substr(6));
524 fLabel = true;
527 LogPrintf("Importing %s...\n", EncodeDestination(keyid));
528 if (!pwallet->AddKeyPubKey(key, pubkey)) {
529 fGood = false;
530 continue;
532 pwallet->mapKeyMetadata[keyid].nCreateTime = nTime;
533 if (fLabel)
534 pwallet->SetAddressBook(keyid, strLabel, "receive");
535 nTimeBegin = std::min(nTimeBegin, nTime);
536 } else if(IsHex(vstr[0])) {
537 std::vector<unsigned char> vData(ParseHex(vstr[0]));
538 CScript script = CScript(vData.begin(), vData.end());
539 if (pwallet->HaveCScript(script)) {
540 LogPrintf("Skipping import of %s (script already present)\n", vstr[0]);
541 continue;
543 if(!pwallet->AddCScript(script)) {
544 LogPrintf("Error importing script %s\n", vstr[0]);
545 fGood = false;
546 continue;
548 int64_t birth_time = DecodeDumpTime(vstr[1]);
549 if (birth_time > 0) {
550 pwallet->m_script_metadata[CScriptID(script)].nCreateTime = birth_time;
551 nTimeBegin = std::min(nTimeBegin, birth_time);
555 file.close();
556 pwallet->ShowProgress("", 100); // hide progress dialog in GUI
557 pwallet->UpdateTimeFirstKey(nTimeBegin);
558 pwallet->RescanFromTime(nTimeBegin, false /* update */);
559 pwallet->MarkDirty();
561 if (!fGood)
562 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys/scripts to wallet");
564 return NullUniValue;
567 UniValue dumpprivkey(const JSONRPCRequest& request)
569 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
570 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
571 return NullUniValue;
574 if (request.fHelp || request.params.size() != 1)
575 throw std::runtime_error(
576 "dumpprivkey \"address\"\n"
577 "\nReveals the private key corresponding to 'address'.\n"
578 "Then the importprivkey can be used with this output\n"
579 "\nArguments:\n"
580 "1. \"address\" (string, required) The bitcoin address for the private key\n"
581 "\nResult:\n"
582 "\"key\" (string) The private key\n"
583 "\nExamples:\n"
584 + HelpExampleCli("dumpprivkey", "\"myaddress\"")
585 + HelpExampleCli("importprivkey", "\"mykey\"")
586 + HelpExampleRpc("dumpprivkey", "\"myaddress\"")
589 LOCK2(cs_main, pwallet->cs_wallet);
591 EnsureWalletIsUnlocked(pwallet);
593 std::string strAddress = request.params[0].get_str();
594 CTxDestination dest = DecodeDestination(strAddress);
595 if (!IsValidDestination(dest)) {
596 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
598 const CKeyID *keyID = boost::get<CKeyID>(&dest);
599 if (!keyID) {
600 throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
602 CKey vchSecret;
603 if (!pwallet->GetKey(*keyID, vchSecret)) {
604 throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
606 return CBitcoinSecret(vchSecret).ToString();
610 UniValue dumpwallet(const JSONRPCRequest& request)
612 CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
613 if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
614 return NullUniValue;
617 if (request.fHelp || request.params.size() != 1)
618 throw std::runtime_error(
619 "dumpwallet \"filename\"\n"
620 "\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\n"
621 "Imported scripts are included in the dumpfile, but corresponding BIP173 addresses, etc. may not be added automatically by importwallet.\n"
622 "Note that if your wallet contains keys which are not derived from your HD seed (e.g. imported keys), these are not covered by\n"
623 "only backing up the seed itself, and must be backed up too (e.g. ensure you back up the whole dumpfile).\n"
624 "\nArguments:\n"
625 "1. \"filename\" (string, required) The filename with path (either absolute or relative to bitcoind)\n"
626 "\nResult:\n"
627 "{ (json object)\n"
628 " \"filename\" : { (string) The filename with full absolute path\n"
629 "}\n"
630 "\nExamples:\n"
631 + HelpExampleCli("dumpwallet", "\"test\"")
632 + HelpExampleRpc("dumpwallet", "\"test\"")
635 LOCK2(cs_main, pwallet->cs_wallet);
637 EnsureWalletIsUnlocked(pwallet);
639 boost::filesystem::path filepath = request.params[0].get_str();
640 filepath = boost::filesystem::absolute(filepath);
642 /* Prevent arbitrary files from being overwritten. There have been reports
643 * that users have overwritten wallet files this way:
644 * https://github.com/bitcoin/bitcoin/issues/9934
645 * It may also avoid other security issues.
647 if (boost::filesystem::exists(filepath)) {
648 throw JSONRPCError(RPC_INVALID_PARAMETER, filepath.string() + " already exists. If you are sure this is what you want, move it out of the way first");
651 std::ofstream file;
652 file.open(filepath.string().c_str());
653 if (!file.is_open())
654 throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
656 std::map<CTxDestination, int64_t> mapKeyBirth;
657 const std::map<CKeyID, int64_t>& mapKeyPool = pwallet->GetAllReserveKeys();
658 pwallet->GetKeyBirthTimes(mapKeyBirth);
660 std::set<CScriptID> scripts = pwallet->GetCScripts();
661 // TODO: include scripts in GetKeyBirthTimes() output instead of separate
663 // sort time/key pairs
664 std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
665 for (const auto& entry : mapKeyBirth) {
666 if (const CKeyID* keyID = boost::get<CKeyID>(&entry.first)) { // set and test
667 vKeyBirth.push_back(std::make_pair(entry.second, *keyID));
670 mapKeyBirth.clear();
671 std::sort(vKeyBirth.begin(), vKeyBirth.end());
673 // produce output
674 file << strprintf("# Wallet dump created by Bitcoin %s\n", CLIENT_BUILD);
675 file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
676 file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
677 file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
678 file << "\n";
680 // add the base58check encoded extended master if the wallet uses HD
681 CKeyID masterKeyID = pwallet->GetHDChain().masterKeyID;
682 if (!masterKeyID.IsNull())
684 CKey key;
685 if (pwallet->GetKey(masterKeyID, key)) {
686 CExtKey masterKey;
687 masterKey.SetMaster(key.begin(), key.size());
689 CBitcoinExtKey b58extkey;
690 b58extkey.SetKey(masterKey);
692 file << "# extended private masterkey: " << b58extkey.ToString() << "\n\n";
695 for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
696 const CKeyID &keyid = it->second;
697 std::string strTime = EncodeDumpTime(it->first);
698 std::string strAddr = EncodeDestination(keyid);
699 CKey key;
700 if (pwallet->GetKey(keyid, key)) {
701 file << strprintf("%s %s ", CBitcoinSecret(key).ToString(), strTime);
702 if (pwallet->mapAddressBook.count(keyid)) {
703 file << strprintf("label=%s", EncodeDumpString(pwallet->mapAddressBook[keyid].name));
704 } else if (keyid == masterKeyID) {
705 file << "hdmaster=1";
706 } else if (mapKeyPool.count(keyid)) {
707 file << "reserve=1";
708 } else if (pwallet->mapKeyMetadata[keyid].hdKeypath == "m") {
709 file << "inactivehdmaster=1";
710 } else {
711 file << "change=1";
713 file << strprintf(" # addr=%s%s\n", strAddr, (pwallet->mapKeyMetadata[keyid].hdKeypath.size() > 0 ? " hdkeypath="+pwallet->mapKeyMetadata[keyid].hdKeypath : ""));
716 file << "\n";
717 for (const CScriptID &scriptid : scripts) {
718 CScript script;
719 std::string create_time = "0";
720 std::string address = EncodeDestination(scriptid);
721 // get birth times for scripts with metadata
722 auto it = pwallet->m_script_metadata.find(scriptid);
723 if (it != pwallet->m_script_metadata.end()) {
724 create_time = EncodeDumpTime(it->second.nCreateTime);
726 if(pwallet->GetCScript(scriptid, script)) {
727 file << strprintf("%s %s script=1", HexStr(script.begin(), script.end()), create_time);
728 file << strprintf(" # addr=%s\n", address);
731 file << "\n";
732 file << "# End of dump\n";
733 file.close();
735 UniValue reply(UniValue::VOBJ);
736 reply.push_back(Pair("filename", filepath.string()));
738 return reply;
742 UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int64_t timestamp)
744 try {
745 bool success = false;
747 // Required fields.
748 const UniValue& scriptPubKey = data["scriptPubKey"];
750 // Should have script or JSON with "address".
751 if (!(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address")) && !(scriptPubKey.getType() == UniValue::VSTR)) {
752 throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid scriptPubKey");
755 // Optional fields.
756 const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : "";
757 const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue();
758 const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
759 const bool internal = data.exists("internal") ? data["internal"].get_bool() : false;
760 const bool watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
761 const std::string& label = data.exists("label") && !internal ? data["label"].get_str() : "";
763 bool isScript = scriptPubKey.getType() == UniValue::VSTR;
764 bool isP2SH = strRedeemScript.length() > 0;
765 const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str();
767 // Parse the output.
768 CScript script;
769 CTxDestination dest;
771 if (!isScript) {
772 dest = DecodeDestination(output);
773 if (!IsValidDestination(dest)) {
774 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
776 script = GetScriptForDestination(dest);
777 } else {
778 if (!IsHex(output)) {
779 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey");
782 std::vector<unsigned char> vData(ParseHex(output));
783 script = CScript(vData.begin(), vData.end());
786 // Watchonly and private keys
787 if (watchOnly && keys.size()) {
788 throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between watchonly and keys");
791 // Internal + Label
792 if (internal && data.exists("label")) {
793 throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between internal and label");
796 // Not having Internal + Script
797 if (!internal && isScript) {
798 throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set for hex scriptPubKey");
801 // Keys / PubKeys size check.
802 if (!isP2SH && (keys.size() > 1 || pubKeys.size() > 1)) { // Address / scriptPubKey
803 throw JSONRPCError(RPC_INVALID_PARAMETER, "More than private key given for one address");
806 // Invalid P2SH redeemScript
807 if (isP2SH && !IsHex(strRedeemScript)) {
808 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script");
811 // Process. //
813 // P2SH
814 if (isP2SH) {
815 // Import redeem script.
816 std::vector<unsigned char> vData(ParseHex(strRedeemScript));
817 CScript redeemScript = CScript(vData.begin(), vData.end());
819 // Invalid P2SH address
820 if (!script.IsPayToScriptHash()) {
821 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid P2SH address / script");
824 pwallet->MarkDirty();
826 if (!pwallet->AddWatchOnly(redeemScript, timestamp)) {
827 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
830 if (!pwallet->HaveCScript(redeemScript) && !pwallet->AddCScript(redeemScript)) {
831 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
834 CTxDestination redeem_dest = CScriptID(redeemScript);
835 CScript redeemDestination = GetScriptForDestination(redeem_dest);
837 if (::IsMine(*pwallet, redeemDestination) == ISMINE_SPENDABLE) {
838 throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
841 pwallet->MarkDirty();
843 if (!pwallet->AddWatchOnly(redeemDestination, timestamp)) {
844 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
847 // add to address book or update label
848 if (IsValidDestination(dest)) {
849 pwallet->SetAddressBook(dest, label, "receive");
852 // Import private keys.
853 if (keys.size()) {
854 for (size_t i = 0; i < keys.size(); i++) {
855 const std::string& privkey = keys[i].get_str();
857 CBitcoinSecret vchSecret;
858 bool fGood = vchSecret.SetString(privkey);
860 if (!fGood) {
861 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
864 CKey key = vchSecret.GetKey();
866 if (!key.IsValid()) {
867 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
870 CPubKey pubkey = key.GetPubKey();
871 assert(key.VerifyPubKey(pubkey));
873 CKeyID vchAddress = pubkey.GetID();
874 pwallet->MarkDirty();
875 pwallet->SetAddressBook(vchAddress, label, "receive");
877 if (pwallet->HaveKey(vchAddress)) {
878 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key");
881 pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
883 if (!pwallet->AddKeyPubKey(key, pubkey)) {
884 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
887 pwallet->UpdateTimeFirstKey(timestamp);
891 success = true;
892 } else {
893 // Import public keys.
894 if (pubKeys.size() && keys.size() == 0) {
895 const std::string& strPubKey = pubKeys[0].get_str();
897 if (!IsHex(strPubKey)) {
898 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
901 std::vector<unsigned char> vData(ParseHex(strPubKey));
902 CPubKey pubKey(vData.begin(), vData.end());
904 if (!pubKey.IsFullyValid()) {
905 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
908 CTxDestination pubkey_dest = pubKey.GetID();
910 // Consistency check.
911 if (!isScript && !(pubkey_dest == dest)) {
912 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
915 // Consistency check.
916 if (isScript) {
917 CTxDestination destination;
919 if (ExtractDestination(script, destination)) {
920 if (!(destination == pubkey_dest)) {
921 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
926 CScript pubKeyScript = GetScriptForDestination(pubkey_dest);
928 if (::IsMine(*pwallet, pubKeyScript) == ISMINE_SPENDABLE) {
929 throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
932 pwallet->MarkDirty();
934 if (!pwallet->AddWatchOnly(pubKeyScript, timestamp)) {
935 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
938 // add to address book or update label
939 if (IsValidDestination(pubkey_dest)) {
940 pwallet->SetAddressBook(pubkey_dest, label, "receive");
943 // TODO Is this necessary?
944 CScript scriptRawPubKey = GetScriptForRawPubKey(pubKey);
946 if (::IsMine(*pwallet, scriptRawPubKey) == ISMINE_SPENDABLE) {
947 throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
950 pwallet->MarkDirty();
952 if (!pwallet->AddWatchOnly(scriptRawPubKey, timestamp)) {
953 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
956 success = true;
959 // Import private keys.
960 if (keys.size()) {
961 const std::string& strPrivkey = keys[0].get_str();
963 // Checks.
964 CBitcoinSecret vchSecret;
965 bool fGood = vchSecret.SetString(strPrivkey);
967 if (!fGood) {
968 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
971 CKey key = vchSecret.GetKey();
972 if (!key.IsValid()) {
973 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
976 CPubKey pubKey = key.GetPubKey();
977 assert(key.VerifyPubKey(pubKey));
979 CTxDestination pubkey_dest = pubKey.GetID();
981 // Consistency check.
982 if (!isScript && !(pubkey_dest == dest)) {
983 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
986 // Consistency check.
987 if (isScript) {
988 CTxDestination destination;
990 if (ExtractDestination(script, destination)) {
991 if (!(destination == pubkey_dest)) {
992 throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
997 CKeyID vchAddress = pubKey.GetID();
998 pwallet->MarkDirty();
999 pwallet->SetAddressBook(vchAddress, label, "receive");
1001 if (pwallet->HaveKey(vchAddress)) {
1002 throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
1005 pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
1007 if (!pwallet->AddKeyPubKey(key, pubKey)) {
1008 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
1011 pwallet->UpdateTimeFirstKey(timestamp);
1013 success = true;
1016 // Import scriptPubKey only.
1017 if (pubKeys.size() == 0 && keys.size() == 0) {
1018 if (::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
1019 throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
1022 pwallet->MarkDirty();
1024 if (!pwallet->AddWatchOnly(script, timestamp)) {
1025 throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
1028 if (scriptPubKey.getType() == UniValue::VOBJ) {
1029 // add to address book or update label
1030 if (IsValidDestination(dest)) {
1031 pwallet->SetAddressBook(dest, label, "receive");
1035 success = true;
1039 UniValue result = UniValue(UniValue::VOBJ);
1040 result.pushKV("success", UniValue(success));
1041 return result;
1042 } catch (const UniValue& e) {
1043 UniValue result = UniValue(UniValue::VOBJ);
1044 result.pushKV("success", UniValue(false));
1045 result.pushKV("error", e);
1046 return result;
1047 } catch (...) {
1048 UniValue result = UniValue(UniValue::VOBJ);
1049 result.pushKV("success", UniValue(false));
1050 result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields"));
1051 return result;
1055 int64_t GetImportTimestamp(const UniValue& data, int64_t now)
1057 if (data.exists("timestamp")) {
1058 const UniValue& timestamp = data["timestamp"];
1059 if (timestamp.isNum()) {
1060 return timestamp.get_int64();
1061 } else if (timestamp.isStr() && timestamp.get_str() == "now") {
1062 return now;
1064 throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
1066 throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
1069 UniValue importmulti(const JSONRPCRequest& mainRequest)
1071 CWallet * const pwallet = GetWalletForJSONRPCRequest(mainRequest);
1072 if (!EnsureWalletIsAvailable(pwallet, mainRequest.fHelp)) {
1073 return NullUniValue;
1076 // clang-format off
1077 if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2)
1078 throw std::runtime_error(
1079 "importmulti \"requests\" ( \"options\" )\n\n"
1080 "Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options). Requires a new wallet backup.\n\n"
1081 "Arguments:\n"
1082 "1. requests (array, required) Data to be imported\n"
1083 " [ (array of json objects)\n"
1084 " {\n"
1085 " \"scriptPubKey\": \"<script>\" | { \"address\":\"<address>\" }, (string / json, required) Type of scriptPubKey (string for script, json for address)\n"
1086 " \"timestamp\": timestamp | \"now\" , (integer / string, required) Creation time of the key in seconds since epoch (Jan 1 1970 GMT),\n"
1087 " or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n"
1088 " key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n"
1089 " \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n"
1090 " 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n"
1091 " creation time of all keys being imported by the importmulti call will be scanned.\n"
1092 " \"redeemscript\": \"<script>\" , (string, optional) Allowed only if the scriptPubKey is a P2SH address or a P2SH scriptPubKey\n"
1093 " \"pubkeys\": [\"<pubKey>\", ... ] , (array, optional) Array of strings giving pubkeys that must occur in the output or redeemscript\n"
1094 " \"keys\": [\"<key>\", ... ] , (array, optional) Array of strings giving private keys whose corresponding public keys must occur in the output or redeemscript\n"
1095 " \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be treated as not incoming payments\n"
1096 " \"watchonly\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be considered watched even when they're not spendable, only allowed if keys are empty\n"
1097 " \"label\": <label> , (string, optional, default: '') Label to assign to the address (aka account name, for now), only allowed with internal=false\n"
1098 " }\n"
1099 " ,...\n"
1100 " ]\n"
1101 "2. options (json, optional)\n"
1102 " {\n"
1103 " \"rescan\": <false>, (boolean, optional, default: true) Stating if should rescan the blockchain after all imports\n"
1104 " }\n"
1105 "\nExamples:\n" +
1106 HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, "
1107 "{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
1108 HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") +
1110 "\nResponse is an array with the same size as the input that has the execution result :\n"
1111 " [{ \"success\": true } , { \"success\": false, \"error\": { \"code\": -1, \"message\": \"Internal Server Error\"} }, ... ]\n");
1113 // clang-format on
1115 RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ});
1117 const UniValue& requests = mainRequest.params[0];
1119 //Default options
1120 bool fRescan = true;
1122 if (!mainRequest.params[1].isNull()) {
1123 const UniValue& options = mainRequest.params[1];
1125 if (options.exists("rescan")) {
1126 fRescan = options["rescan"].get_bool();
1130 LOCK2(cs_main, pwallet->cs_wallet);
1131 EnsureWalletIsUnlocked(pwallet);
1133 // Verify all timestamps are present before importing any keys.
1134 const int64_t now = chainActive.Tip() ? chainActive.Tip()->GetMedianTimePast() : 0;
1135 for (const UniValue& data : requests.getValues()) {
1136 GetImportTimestamp(data, now);
1139 bool fRunScan = false;
1140 const int64_t minimumTimestamp = 1;
1141 int64_t nLowestTimestamp = 0;
1143 if (fRescan && chainActive.Tip()) {
1144 nLowestTimestamp = chainActive.Tip()->GetBlockTime();
1145 } else {
1146 fRescan = false;
1149 UniValue response(UniValue::VARR);
1151 for (const UniValue& data : requests.getValues()) {
1152 const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);
1153 const UniValue result = ProcessImport(pwallet, data, timestamp);
1154 response.push_back(result);
1156 if (!fRescan) {
1157 continue;
1160 // If at least one request was successful then allow rescan.
1161 if (result["success"].get_bool()) {
1162 fRunScan = true;
1165 // Get the lowest timestamp.
1166 if (timestamp < nLowestTimestamp) {
1167 nLowestTimestamp = timestamp;
1171 if (fRescan && fRunScan && requests.size()) {
1172 int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, true /* update */);
1173 pwallet->ReacceptWalletTransactions();
1175 if (scannedTime > nLowestTimestamp) {
1176 std::vector<UniValue> results = response.getValues();
1177 response.clear();
1178 response.setArray();
1179 size_t i = 0;
1180 for (const UniValue& request : requests.getValues()) {
1181 // If key creation date is within the successfully scanned
1182 // range, or if the import result already has an error set, let
1183 // the result stand unmodified. Otherwise replace the result
1184 // with an error message.
1185 if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists("error")) {
1186 response.push_back(results.at(i));
1187 } else {
1188 UniValue result = UniValue(UniValue::VOBJ);
1189 result.pushKV("success", UniValue(false));
1190 result.pushKV(
1191 "error",
1192 JSONRPCError(
1193 RPC_MISC_ERROR,
1194 strprintf("Rescan failed for key with creation timestamp %d. There was an error reading a "
1195 "block from time %d, which is after or within %d seconds of key creation, and "
1196 "could contain transactions pertaining to the key. As a result, transactions "
1197 "and coins using this key may not appear in the wallet. This error could be "
1198 "caused by pruning or data corruption (see bitcoind log for details) and could "
1199 "be dealt with by downloading and rescanning the relevant blocks (see -reindex "
1200 "and -rescan options).",
1201 GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));
1202 response.push_back(std::move(result));
1204 ++i;
1209 return response;