Raven Core  3.0.0
P2P Digital Currency
rpcdump.cpp
Go to the documentation of this file.
1 // Copyright (c) 2009-2016 The Bitcoin Core developers
2 // Copyright (c) 2017-2019 The Raven Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include "base58.h"
7 #include "chain.h"
8 #include "rpc/safemode.h"
9 #include "rpc/server.h"
10 #include "init.h"
11 #include "validation.h"
12 #include "script/script.h"
13 #include "script/standard.h"
14 #include "sync.h"
15 #include "util.h"
16 #include "utiltime.h"
17 #include "wallet.h"
18 #include "merkleblock.h"
19 #include "core_io.h"
20 
21 #include "rpcwallet.h"
22 
23 #include <fstream>
24 #include <stdint.h>
25 
26 #include <boost/algorithm/string.hpp>
27 #include <boost/date_time/posix_time/posix_time.hpp>
28 
29 #include <univalue.h>
30 
31 
32 std::string static EncodeDumpTime(int64_t nTime) {
33  return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
34 }
35 
36 int64_t static DecodeDumpTime(const std::string &str) {
37  static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
38  static const std::locale loc(std::locale::classic(),
39  new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
40  std::istringstream iss(str);
41  iss.imbue(loc);
42  boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
43  iss >> ptime;
44  if (ptime.is_not_a_date_time())
45  return 0;
46  return (ptime - epoch).total_seconds();
47 }
48 
49 std::string static EncodeDumpString(const std::string &str) {
50  std::stringstream ret;
51  for (unsigned char c : str) {
52  if (c <= 32 || c >= 128 || c == '%') {
53  ret << '%' << HexStr(&c, &c + 1);
54  } else {
55  ret << c;
56  }
57  }
58  return ret.str();
59 }
60 
61 std::string DecodeDumpString(const std::string &str) {
62  std::stringstream ret;
63  for (unsigned int pos = 0; pos < str.length(); pos++) {
64  unsigned char c = str[pos];
65  if (c == '%' && pos+2 < str.length()) {
66  c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
67  ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
68  pos += 2;
69  }
70  ret << c;
71  }
72  return ret.str();
73 }
74 
76 {
77  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
78  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
79  return NullUniValue;
80  }
81 
82  if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
83  throw std::runtime_error(
84  "importprivkey \"privkey\" ( \"label\" ) ( rescan )\n"
85  "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n"
86  "\nArguments:\n"
87  "1. \"privkey\" (string, required) The private key (see dumpprivkey)\n"
88  "2. \"label\" (string, optional, default=\"\") An optional label\n"
89  "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
90  "\nNote: This call can take minutes to complete if rescan is true.\n"
91  "\nExamples:\n"
92  "\nDump a private key\n"
93  + HelpExampleCli("dumpprivkey", "\"myaddress\"") +
94  "\nImport the private key with rescan\n"
95  + HelpExampleCli("importprivkey", "\"mykey\"") +
96  "\nImport using a label and without rescan\n"
97  + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
98  "\nImport using default blank label and without rescan\n"
99  + HelpExampleCli("importprivkey", "\"mykey\" \"\" false") +
100  "\nAs a JSON-RPC call\n"
101  + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")
102  );
103 
104 
105  LOCK2(cs_main, pwallet->cs_wallet);
106 
107  EnsureWalletIsUnlocked(pwallet);
108 
109  std::string strSecret = request.params[0].get_str();
110  std::string strLabel = "";
111  if (!request.params[1].isNull())
112  strLabel = request.params[1].get_str();
113 
114  // Whether to perform rescan after import
115  bool fRescan = true;
116  if (!request.params[2].isNull())
117  fRescan = request.params[2].get_bool();
118 
119  if (fRescan && fPruneMode)
120  throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
121 
122  CRavenSecret vchSecret;
123  bool fGood = vchSecret.SetString(strSecret);
124 
125  if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
126 
127  CKey key = vchSecret.GetKey();
128  if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
129 
130  CPubKey pubkey = key.GetPubKey();
131  assert(key.VerifyPubKey(pubkey));
132  CKeyID vchAddress = pubkey.GetID();
133  {
134  pwallet->MarkDirty();
135  pwallet->SetAddressBook(vchAddress, strLabel, "receive");
136 
137  // Don't throw error in case a key is already there
138  if (pwallet->HaveKey(vchAddress)) {
139  return NullUniValue;
140  }
141 
142  pwallet->mapKeyMetadata[vchAddress].nCreateTime = 1;
143 
144  if (!pwallet->AddKeyPubKey(key, pubkey)) {
145  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
146  }
147 
148  // whenever a key is imported, we need to scan the whole chain
149  pwallet->UpdateTimeFirstKey(1);
150 
151  if (fRescan) {
152  pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
153  }
154  }
155 
156  return NullUniValue;
157 }
158 
160 {
161  CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
162  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
163  return NullUniValue;
164  }
165 
166  if (request.fHelp || request.params.size() > 0)
167  throw std::runtime_error(
168  "abortrescan\n"
169  "\nStops current wallet rescan triggered e.g. by an importprivkey call.\n"
170  "\nExamples:\n"
171  "\nImport a private key\n"
172  + HelpExampleCli("importprivkey", "\"mykey\"") +
173  "\nAbort the running wallet rescan\n"
174  + HelpExampleCli("abortrescan", "") +
175  "\nAs a JSON-RPC call\n"
176  + HelpExampleRpc("abortrescan", "")
177  );
178 
179  ObserveSafeMode();
180  if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false;
181  pwallet->AbortRescan();
182  return true;
183 }
184 
185 void ImportAddress(CWallet*, const CTxDestination& dest, const std::string& strLabel);
186 void ImportScript(CWallet* const pwallet, const CScript& script, const std::string& strLabel, bool isRedeemScript)
187 {
188  if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
189  throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
190  }
191 
192  pwallet->MarkDirty();
193 
194  if (!pwallet->HaveWatchOnly(script) && !pwallet->AddWatchOnly(script, 0 /* nCreateTime */)) {
195  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
196  }
197 
198  if (isRedeemScript) {
199  if (!pwallet->HaveCScript(script) && !pwallet->AddCScript(script)) {
200  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
201  }
202  ImportAddress(pwallet, CScriptID(script), strLabel);
203  } else {
204  CTxDestination destination;
205  if (ExtractDestination(script, destination)) {
206  pwallet->SetAddressBook(destination, strLabel, "receive");
207  }
208  }
209 }
210 
211 void ImportAddress(CWallet* const pwallet, const CTxDestination& dest, const std::string& strLabel)
212 {
213  CScript script = GetScriptForDestination(dest);
214  ImportScript(pwallet, script, strLabel, false);
215  // add to address book or update label
216  if (IsValidDestination(dest))
217  pwallet->SetAddressBook(dest, strLabel, "receive");
218 }
219 
221 {
222  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
223  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
224  return NullUniValue;
225  }
226 
227  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
228  throw std::runtime_error(
229  "importaddress \"address\" ( \"label\" rescan p2sh )\n"
230  "\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend.\n"
231  "\nArguments:\n"
232  "1. \"script\" (string, required) The hex-encoded script (or address)\n"
233  "2. \"label\" (string, optional, default=\"\") An optional label\n"
234  "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
235  "4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n"
236  "\nNote: This call can take minutes to complete if rescan is true.\n"
237  "If you have the full public key, you should call importpubkey instead of this.\n"
238  "\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n"
239  "as change, and not show up in many RPCs.\n"
240  "\nExamples:\n"
241  "\nImport a script with rescan\n"
242  + HelpExampleCli("importaddress", "\"myscript\"") +
243  "\nImport using a label without rescan\n"
244  + HelpExampleCli("importaddress", "\"myscript\" \"testing\" false") +
245  "\nAs a JSON-RPC call\n"
246  + HelpExampleRpc("importaddress", "\"myscript\", \"testing\", false")
247  );
248 
249 
250  std::string strLabel = "";
251  if (!request.params[1].isNull())
252  strLabel = request.params[1].get_str();
253 
254  // Whether to perform rescan after import
255  bool fRescan = true;
256  if (!request.params[2].isNull())
257  fRescan = request.params[2].get_bool();
258 
259  if (fRescan && fPruneMode)
260  throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
261 
262  // Whether to import a p2sh version, too
263  bool fP2SH = false;
264  if (!request.params[3].isNull())
265  fP2SH = request.params[3].get_bool();
266 
267  LOCK2(cs_main, pwallet->cs_wallet);
268 
269  CTxDestination dest = DecodeDestination(request.params[0].get_str());
270  if (IsValidDestination(dest)) {
271  if (fP2SH) {
272  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead");
273  }
274  ImportAddress(pwallet, dest, strLabel);
275  } else if (IsHex(request.params[0].get_str())) {
276  std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
277  ImportScript(pwallet, CScript(data.begin(), data.end()), strLabel, fP2SH);
278  } else {
279  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Raven address or script");
280  }
281 
282  if (fRescan)
283  {
284  pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
285  pwallet->ReacceptWalletTransactions();
286  }
287 
288  return NullUniValue;
289 }
290 
292 {
293  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
294  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
295  return NullUniValue;
296  }
297 
298  if (request.fHelp || request.params.size() != 2)
299  throw std::runtime_error(
300  "importprunedfunds\n"
301  "\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"
302  "\nArguments:\n"
303  "1. \"rawtransaction\" (string, required) A raw transaction in hex funding an already-existing address in wallet\n"
304  "2. \"txoutproof\" (string, required) The hex output from gettxoutproof that contains the transaction\n"
305  );
306 
308  if (!DecodeHexTx(tx, request.params[0].get_str()))
309  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
310  uint256 hashTx = tx.GetHash();
311  CWalletTx wtx(pwallet, MakeTransactionRef(std::move(tx)));
312 
313  CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION);
314  CMerkleBlock merkleBlock;
315  ssMB >> merkleBlock;
316 
317  //Search partial merkle tree in proof for our transaction and index in valid block
318  std::vector<uint256> vMatch;
319  std::vector<unsigned int> vIndex;
320  unsigned int txnIndex = 0;
321  if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {
322 
323  LOCK(cs_main);
324 
325  if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
326  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
327 
328  std::vector<uint256>::const_iterator it;
329  if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) {
330  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
331  }
332 
333  txnIndex = vIndex[it - vMatch.begin()];
334  }
335  else {
336  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
337  }
338 
339  wtx.nIndex = txnIndex;
340  wtx.hashBlock = merkleBlock.header.GetHash();
341 
342  LOCK2(cs_main, pwallet->cs_wallet);
343 
344  if (pwallet->IsMine(wtx)) {
345  pwallet->AddToWallet(wtx, false);
346  return NullUniValue;
347  }
348 
349  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
350 }
351 
353 {
354  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
355  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
356  return NullUniValue;
357  }
358 
359  if (request.fHelp || request.params.size() != 1)
360  throw std::runtime_error(
361  "removeprunedfunds \"txid\"\n"
362  "\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"
363  "\nArguments:\n"
364  "1. \"txid\" (string, required) The hex-encoded id of the transaction you are deleting\n"
365  "\nExamples:\n"
366  + HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
367  "\nAs a JSON-RPC call\n"
368  + HelpExampleRpc("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"")
369  );
370 
371  LOCK2(cs_main, pwallet->cs_wallet);
372 
373  uint256 hash;
374  hash.SetHex(request.params[0].get_str());
375  std::vector<uint256> vHash;
376  vHash.push_back(hash);
377  std::vector<uint256> vHashOut;
378 
379  if (pwallet->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) {
380  throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction.");
381  }
382 
383  if(vHashOut.empty()) {
384  throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction does not exist in wallet.");
385  }
386 
387  return NullUniValue;
388 }
389 
391 {
392  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
393  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
394  return NullUniValue;
395  }
396 
397  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
398  throw std::runtime_error(
399  "importpubkey \"pubkey\" ( \"label\" rescan )\n"
400  "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n"
401  "\nArguments:\n"
402  "1. \"pubkey\" (string, required) The hex-encoded public key\n"
403  "2. \"label\" (string, optional, default=\"\") An optional label\n"
404  "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
405  "\nNote: This call can take minutes to complete if rescan is true.\n"
406  "\nExamples:\n"
407  "\nImport a public key with rescan\n"
408  + HelpExampleCli("importpubkey", "\"mypubkey\"") +
409  "\nImport using a label without rescan\n"
410  + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") +
411  "\nAs a JSON-RPC call\n"
412  + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false")
413  );
414 
415 
416  std::string strLabel = "";
417  if (!request.params[1].isNull())
418  strLabel = request.params[1].get_str();
419 
420  // Whether to perform rescan after import
421  bool fRescan = true;
422  if (!request.params[2].isNull())
423  fRescan = request.params[2].get_bool();
424 
425  if (fRescan && fPruneMode)
426  throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
427 
428  if (!IsHex(request.params[0].get_str()))
429  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
430  std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
431  CPubKey pubKey(data.begin(), data.end());
432  if (!pubKey.IsFullyValid())
433  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
434 
435  LOCK2(cs_main, pwallet->cs_wallet);
436 
437  ImportAddress(pwallet, pubKey.GetID(), strLabel);
438  ImportScript(pwallet, GetScriptForRawPubKey(pubKey), strLabel, false);
439 
440  if (fRescan)
441  {
442  pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
443  pwallet->ReacceptWalletTransactions();
444  }
445 
446  return NullUniValue;
447 }
448 
449 
451 {
452  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
453  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
454  return NullUniValue;
455  }
456 
457  if (request.fHelp || request.params.size() != 1)
458  throw std::runtime_error(
459  "importwallet \"filename\"\n"
460  "\nImports keys from a wallet dump file (see dumpwallet).\n"
461  "\nArguments:\n"
462  "1. \"filename\" (string, required) The wallet file\n"
463  "\nExamples:\n"
464  "\nDump the wallet\n"
465  + HelpExampleCli("dumpwallet", "\"test\"") +
466  "\nImport the wallet\n"
467  + HelpExampleCli("importwallet", "\"test\"") +
468  "\nImport using the json rpc call\n"
469  + HelpExampleRpc("importwallet", "\"test\"")
470  );
471 
472  if (fPruneMode)
473  throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode");
474 
475  LOCK2(cs_main, pwallet->cs_wallet);
476 
477  EnsureWalletIsUnlocked(pwallet);
478 
479  std::ifstream file;
480  file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate);
481  if (!file.is_open())
482  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
483 
484  int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();
485 
486  bool fGood = true;
487 
488  int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
489  file.seekg(0, file.beg);
490 
491  pwallet->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
492  while (file.good()) {
493  pwallet->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
494  std::string line;
495  std::getline(file, line);
496  if (line.empty() || line[0] == '#')
497  continue;
498 
499  std::vector<std::string> vstr;
500  boost::split(vstr, line, boost::is_any_of(" "));
501  if (vstr.size() < 2)
502  continue;
503  CRavenSecret vchSecret;
504  if (!vchSecret.SetString(vstr[0]))
505  continue;
506  CKey key = vchSecret.GetKey();
507  CPubKey pubkey = key.GetPubKey();
508  assert(key.VerifyPubKey(pubkey));
509  CKeyID keyid = pubkey.GetID();
510  if (pwallet->HaveKey(keyid)) {
511  LogPrintf("Skipping import of %s (key already present)\n", EncodeDestination(keyid));
512  continue;
513  }
514  int64_t nTime = DecodeDumpTime(vstr[1]);
515  std::string strLabel;
516  bool fLabel = true;
517  for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
518  if (boost::algorithm::starts_with(vstr[nStr], "#"))
519  break;
520  if (vstr[nStr] == "change=1")
521  fLabel = false;
522  if (vstr[nStr] == "reserve=1")
523  fLabel = false;
524  if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
525  strLabel = DecodeDumpString(vstr[nStr].substr(6));
526  fLabel = true;
527  }
528  }
529  LogPrintf("Importing %s...\n", EncodeDestination(keyid));
530  if (!pwallet->AddKeyPubKey(key, pubkey)) {
531  fGood = false;
532  continue;
533  }
534  pwallet->mapKeyMetadata[keyid].nCreateTime = nTime;
535  if (fLabel)
536  pwallet->SetAddressBook(keyid, strLabel, "receive");
537  nTimeBegin = std::min(nTimeBegin, nTime);
538  }
539  file.close();
540  pwallet->ShowProgress("", 100); // hide progress dialog in GUI
541  pwallet->UpdateTimeFirstKey(nTimeBegin);
542  pwallet->RescanFromTime(nTimeBegin, false /* update */);
543  pwallet->MarkDirty();
544 
545  if (!fGood)
546  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
547 
548  return NullUniValue;
549 }
550 
552 {
553  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
554  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
555  return NullUniValue;
556  }
557 
558  if (request.fHelp || request.params.size() != 1)
559  throw std::runtime_error(
560  "dumpprivkey \"address\"\n"
561  "\nReveals the private key corresponding to 'address'.\n"
562  "Then the importprivkey can be used with this output\n"
563  "\nArguments:\n"
564  "1. \"address\" (string, required) The raven address for the private key\n"
565  "\nResult:\n"
566  "\"key\" (string) The private key\n"
567  "\nExamples:\n"
568  + HelpExampleCli("dumpprivkey", "\"myaddress\"")
569  + HelpExampleCli("importprivkey", "\"mykey\"")
570  + HelpExampleRpc("dumpprivkey", "\"myaddress\"")
571  );
572 
573  LOCK2(cs_main, pwallet->cs_wallet);
574 
575  EnsureWalletIsUnlocked(pwallet);
576 
577  std::string strAddress = request.params[0].get_str();
578  CTxDestination dest = DecodeDestination(strAddress);
579  if (!IsValidDestination(dest)) {
580  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Raven address");
581  }
582  const CKeyID *keyID = boost::get<CKeyID>(&dest);
583  if (!keyID) {
584  throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
585  }
586  CKey vchSecret;
587  if (!pwallet->GetKey(*keyID, vchSecret)) {
588  throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
589  }
590  return CRavenSecret(vchSecret).ToString();
591 }
592 
593 
595 {
596  CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
597  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
598  return NullUniValue;
599  }
600 
601  if (request.fHelp || request.params.size() != 1)
602  throw std::runtime_error(
603  "dumpwallet \"filename\"\n"
604  "\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\n"
605  "\nArguments:\n"
606  "1. \"filename\" (string, required) The filename with path (either absolute or relative to ravend)\n"
607  "\nResult:\n"
608  "{ (json object)\n"
609  " \"filename\" : { (string) The filename with full absolute path\n"
610  "}\n"
611  "\nExamples:\n"
612  + HelpExampleCli("dumpwallet", "\"test\"")
613  + HelpExampleRpc("dumpwallet", "\"test\"")
614  );
615 
616  LOCK2(cs_main, pwallet->cs_wallet);
617 
618  EnsureWalletIsUnlocked(pwallet);
619 
620  boost::filesystem::path filepath = request.params[0].get_str();
621  filepath = boost::filesystem::absolute(filepath);
622 
623  /* Prevent arbitrary files from being overwritten. There have been reports
624  * that users have overwritten wallet files this way:
625  * https://github.com/RavenProject/Ravencoin/issues/9934
626  * It may also avoid other security issues.
627  */
628  if (boost::filesystem::exists(filepath)) {
629  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");
630  }
631 
632  std::ofstream file;
633  file.open(filepath.string().c_str());
634  if (!file.is_open())
635  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
636 
637  std::map<CTxDestination, int64_t> mapKeyBirth;
638  const std::map<CKeyID, int64_t>& mapKeyPool = pwallet->GetAllReserveKeys();
639  pwallet->GetKeyBirthTimes(mapKeyBirth);
640 
641  // sort time/key pairs
642  std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
643  for (const auto& entry : mapKeyBirth) {
644  if (const CKeyID* keyID = boost::get<CKeyID>(&entry.first)) { // set and test
645  vKeyBirth.push_back(std::make_pair(entry.second, *keyID));
646  }
647  }
648  mapKeyBirth.clear();
649  std::sort(vKeyBirth.begin(), vKeyBirth.end());
650 
651  // produce output
652  file << strprintf("# Wallet dump created by Raven %s\n", CLIENT_BUILD);
653  file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
654  file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
655  file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
656  file << "\n";
657 
658  // add the base58check encoded extended master if the wallet uses HD
659  CKeyID seed_id = pwallet->GetHDChain().seed_id;
660  if (!seed_id.IsNull())
661  {
662  CKey seed;
663  if (pwallet->GetKey(seed_id, seed)) {
664  CExtKey masterKey;
665  masterKey.SetSeed(seed.begin(), seed.size());
666 
667  CRavenExtKey b58extkey;
668  b58extkey.SetKey(masterKey);
669 
670  file << "# extended private masterkey: " << b58extkey.ToString() << "\n\n";
671  }
672  }
673  for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
674  const CKeyID &keyid = it->second;
675  std::string strTime = EncodeDumpTime(it->first);
676  std::string strAddr = EncodeDestination(keyid);
677  CKey key;
678  if (pwallet->GetKey(keyid, key)) {
679  file << strprintf("%s %s ", CRavenSecret(key).ToString(), strTime);
680  if (pwallet->mapAddressBook.count(keyid)) {
681  file << strprintf("label=%s", EncodeDumpString(pwallet->mapAddressBook[keyid].name));
682  } else if (keyid == seed_id) {
683  file << "hdseed=1";
684  } else if (mapKeyPool.count(keyid)) {
685  file << "reserve=1";
686  } else if (pwallet->mapKeyMetadata[keyid].hdKeypath == "s") {
687  file << "inactivehdseed=1";
688  } else {
689  file << "change=1";
690  }
691  file << strprintf(" # addr=%s%s\n", strAddr, (pwallet->mapKeyMetadata[keyid].hdKeypath.size() > 0 ? " hdkeypath="+pwallet->mapKeyMetadata[keyid].hdKeypath : ""));
692  }
693  }
694  file << "\n";
695  file << "# End of dump\n";
696  file.close();
697 
698  UniValue reply(UniValue::VOBJ);
699  reply.push_back(Pair("filename", filepath.string()));
700 
701  return reply;
702 }
703 
704 
705 UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int64_t timestamp)
706 {
707  try {
708  bool success = false;
709 
710  // Required fields.
711  const UniValue& scriptPubKey = data["scriptPubKey"];
712 
713  // Should have script or JSON with "address".
714  if (!(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address")) && !(scriptPubKey.getType() == UniValue::VSTR)) {
715  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid scriptPubKey");
716  }
717 
718  // Optional fields.
719  const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : "";
720  const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue();
721  const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
722  const bool& internal = data.exists("internal") ? data["internal"].get_bool() : false;
723  const bool& watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
724  const std::string& label = data.exists("label") && !internal ? data["label"].get_str() : "";
725 
726  bool isScript = scriptPubKey.getType() == UniValue::VSTR;
727  bool isP2SH = strRedeemScript.length() > 0;
728  const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str();
729 
730  // Parse the output.
731  CScript script;
732  CTxDestination dest;
733 
734  if (!isScript) {
735  dest = DecodeDestination(output);
736  if (!IsValidDestination(dest)) {
737  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
738  }
739  script = GetScriptForDestination(dest);
740  } else {
741  if (!IsHex(output)) {
742  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey");
743  }
744 
745  std::vector<unsigned char> vData(ParseHex(output));
746  script = CScript(vData.begin(), vData.end());
747  }
748 
749  // Watchonly and private keys
750  if (watchOnly && keys.size()) {
751  throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between watchonly and keys");
752  }
753 
754  // Internal + Label
755  if (internal && data.exists("label")) {
756  throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between internal and label");
757  }
758 
759  // Not having Internal + Script
760  if (!internal && isScript) {
761  throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set for hex scriptPubKey");
762  }
763 
764  // Keys / PubKeys size check.
765  if (!isP2SH && (keys.size() > 1 || pubKeys.size() > 1)) { // Address / scriptPubKey
766  throw JSONRPCError(RPC_INVALID_PARAMETER, "More than private key given for one address");
767  }
768 
769  // Invalid P2SH redeemScript
770  if (isP2SH && !IsHex(strRedeemScript)) {
771  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script");
772  }
773 
774  // Process. //
775 
776  // P2SH
777  if (isP2SH) {
778  // Import redeem script.
779  std::vector<unsigned char> vData(ParseHex(strRedeemScript));
780  CScript redeemScript = CScript(vData.begin(), vData.end());
781 
782  // Invalid P2SH address
783  if (!script.IsPayToScriptHash()) {
784  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid P2SH address / script");
785  }
786 
787  pwallet->MarkDirty();
788 
789  if (!pwallet->AddWatchOnly(redeemScript, timestamp)) {
790  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
791  }
792 
793  if (!pwallet->HaveCScript(redeemScript) && !pwallet->AddCScript(redeemScript)) {
794  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
795  }
796 
797  CTxDestination redeem_dest = CScriptID(redeemScript);
798  CScript redeemDestination = GetScriptForDestination(redeem_dest);
799 
800  if (::IsMine(*pwallet, redeemDestination) == ISMINE_SPENDABLE) {
801  throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
802  }
803 
804  pwallet->MarkDirty();
805 
806  if (!pwallet->AddWatchOnly(redeemDestination, timestamp)) {
807  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
808  }
809 
810  // add to address book or update label
811  if (IsValidDestination(dest)) {
812  pwallet->SetAddressBook(dest, label, "receive");
813  }
814 
815  // Import private keys.
816  if (keys.size()) {
817  for (size_t i = 0; i < keys.size(); i++) {
818  const std::string& privkey = keys[i].get_str();
819 
820  CRavenSecret vchSecret;
821  bool fGood = vchSecret.SetString(privkey);
822 
823  if (!fGood) {
824  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
825  }
826 
827  CKey key = vchSecret.GetKey();
828 
829  if (!key.IsValid()) {
830  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
831  }
832 
833  CPubKey pubkey = key.GetPubKey();
834  assert(key.VerifyPubKey(pubkey));
835 
836  CKeyID vchAddress = pubkey.GetID();
837  pwallet->MarkDirty();
838  pwallet->SetAddressBook(vchAddress, label, "receive");
839 
840  if (pwallet->HaveKey(vchAddress)) {
841  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key");
842  }
843 
844  pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
845 
846  if (!pwallet->AddKeyPubKey(key, pubkey)) {
847  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
848  }
849 
850  pwallet->UpdateTimeFirstKey(timestamp);
851  }
852  }
853 
854  success = true;
855  } else {
856  // Import public keys.
857  if (pubKeys.size() && keys.size() == 0) {
858  const std::string& strPubKey = pubKeys[0].get_str();
859 
860  if (!IsHex(strPubKey)) {
861  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
862  }
863 
864  std::vector<unsigned char> vData(ParseHex(strPubKey));
865  CPubKey pubKey(vData.begin(), vData.end());
866 
867  if (!pubKey.IsFullyValid()) {
868  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
869  }
870 
871  CTxDestination pubkey_dest = pubKey.GetID();
872 
873  // Consistency check.
874  if (!isScript && !(pubkey_dest == dest)) {
875  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
876  }
877 
878  // Consistency check.
879  if (isScript) {
880  CTxDestination destination;
881 
882  if (ExtractDestination(script, destination)) {
883  if (!(destination == pubkey_dest)) {
884  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
885  }
886  }
887  }
888 
889  CScript pubKeyScript = GetScriptForDestination(pubkey_dest);
890 
891  if (::IsMine(*pwallet, pubKeyScript) == ISMINE_SPENDABLE) {
892  throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
893  }
894 
895  pwallet->MarkDirty();
896 
897  if (!pwallet->AddWatchOnly(pubKeyScript, timestamp)) {
898  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
899  }
900 
901  // add to address book or update label
902  if (IsValidDestination(pubkey_dest)) {
903  pwallet->SetAddressBook(pubkey_dest, label, "receive");
904  }
905 
906  // TODO Is this necessary?
907  CScript scriptRawPubKey = GetScriptForRawPubKey(pubKey);
908 
909  if (::IsMine(*pwallet, scriptRawPubKey) == ISMINE_SPENDABLE) {
910  throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
911  }
912 
913  pwallet->MarkDirty();
914 
915  if (!pwallet->AddWatchOnly(scriptRawPubKey, timestamp)) {
916  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
917  }
918 
919  success = true;
920  }
921 
922  // Import private keys.
923  if (keys.size()) {
924  const std::string& strPrivkey = keys[0].get_str();
925 
926  // Checks.
927  CRavenSecret vchSecret;
928  bool fGood = vchSecret.SetString(strPrivkey);
929 
930  if (!fGood) {
931  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
932  }
933 
934  CKey key = vchSecret.GetKey();
935  if (!key.IsValid()) {
936  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
937  }
938 
939  CPubKey pubKey = key.GetPubKey();
940  assert(key.VerifyPubKey(pubKey));
941 
942  CTxDestination pubkey_dest = pubKey.GetID();
943 
944  // Consistency check.
945  if (!isScript && !(pubkey_dest == dest)) {
946  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
947  }
948 
949  // Consistency check.
950  if (isScript) {
951  CTxDestination destination;
952 
953  if (ExtractDestination(script, destination)) {
954  if (!(destination == pubkey_dest)) {
955  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
956  }
957  }
958  }
959 
960  CKeyID vchAddress = pubKey.GetID();
961  pwallet->MarkDirty();
962  pwallet->SetAddressBook(vchAddress, label, "receive");
963 
964  if (pwallet->HaveKey(vchAddress)) {
965  throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
966  }
967 
968  pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
969 
970  if (!pwallet->AddKeyPubKey(key, pubKey)) {
971  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
972  }
973 
974  pwallet->UpdateTimeFirstKey(timestamp);
975 
976  success = true;
977  }
978 
979  // Import scriptPubKey only.
980  if (pubKeys.size() == 0 && keys.size() == 0) {
981  if (::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
982  throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
983  }
984 
985  pwallet->MarkDirty();
986 
987  if (!pwallet->AddWatchOnly(script, timestamp)) {
988  throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
989  }
990 
991  if (scriptPubKey.getType() == UniValue::VOBJ) {
992  // add to address book or update label
993  if (IsValidDestination(dest)) {
994  pwallet->SetAddressBook(dest, label, "receive");
995  }
996  }
997 
998  success = true;
999  }
1000  }
1001 
1002  UniValue result = UniValue(UniValue::VOBJ);
1003  result.pushKV("success", UniValue(success));
1004  return result;
1005  } catch (const UniValue& e) {
1006  UniValue result = UniValue(UniValue::VOBJ);
1007  result.pushKV("success", UniValue(false));
1008  result.pushKV("error", e);
1009  return result;
1010  } catch (...) {
1011  UniValue result = UniValue(UniValue::VOBJ);
1012  result.pushKV("success", UniValue(false));
1013  result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields"));
1014  return result;
1015  }
1016 }
1017 
1018 int64_t GetImportTimestamp(const UniValue& data, int64_t now)
1019 {
1020  if (data.exists("timestamp")) {
1021  const UniValue& timestamp = data["timestamp"];
1022  if (timestamp.isNum()) {
1023  return timestamp.get_int64();
1024  } else if (timestamp.isStr() && timestamp.get_str() == "now") {
1025  return now;
1026  }
1027  throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
1028  }
1029  throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
1030 }
1031 
1033 {
1034  CWallet * const pwallet = GetWalletForJSONRPCRequest(mainRequest);
1035  if (!EnsureWalletIsAvailable(pwallet, mainRequest.fHelp)) {
1036  return NullUniValue;
1037  }
1038 
1039  // clang-format off
1040  if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2)
1041  throw std::runtime_error(
1042  "importmulti \"requests\" ( \"options\" )\n\n"
1043  "Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options).\n\n"
1044  "Arguments:\n"
1045  "1. requests (array, required) Data to be imported\n"
1046  " [ (array of json objects)\n"
1047  " {\n"
1048  " \"scriptPubKey\": \"<script>\" | { \"address\":\"<address>\" }, (string / json, required) Type of scriptPubKey (string for script, json for address)\n"
1049  " \"timestamp\": timestamp | \"now\" , (integer / string, required) Creation time of the key in seconds since epoch (Jan 1 1970 GMT),\n"
1050  " or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n"
1051  " key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n"
1052  " \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n"
1053  " 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n"
1054  " creation time of all keys being imported by the importmulti call will be scanned.\n"
1055  " \"redeemscript\": \"<script>\" , (string, optional) Allowed only if the scriptPubKey is a P2SH address or a P2SH scriptPubKey\n"
1056  " \"pubkeys\": [\"<pubKey>\", ... ] , (array, optional) Array of strings giving pubkeys that must occur in the output or redeemscript\n"
1057  " \"keys\": [\"<key>\", ... ] , (array, optional) Array of strings giving private keys whose corresponding public keys must occur in the output or redeemscript\n"
1058  " \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be treated as not incoming payments\n"
1059  " \"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"
1060  " \"label\": <label> , (string, optional, default: '') Label to assign to the address (aka account name, for now), only allowed with internal=false\n"
1061  " }\n"
1062  " ,...\n"
1063  " ]\n"
1064  "2. options (json, optional)\n"
1065  " {\n"
1066  " \"rescan\": <false>, (boolean, optional, default: true) Stating if should rescan the blockchain after all imports\n"
1067  " }\n"
1068  "\nExamples:\n" +
1069  HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, "
1070  "{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
1071  HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") +
1072 
1073  "\nResponse is an array with the same size as the input that has the execution result :\n"
1074  " [{ \"success\": true } , { \"success\": false, \"error\": { \"code\": -1, \"message\": \"Internal Server Error\"} }, ... ]\n");
1075 
1076  // clang-format on
1077 
1078  RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ});
1079 
1080  const UniValue& requests = mainRequest.params[0];
1081 
1082  //Default options
1083  bool fRescan = true;
1084 
1085  if (!mainRequest.params[1].isNull()) {
1086  const UniValue& options = mainRequest.params[1];
1087 
1088  if (options.exists("rescan")) {
1089  fRescan = options["rescan"].get_bool();
1090  }
1091  }
1092 
1093  LOCK2(cs_main, pwallet->cs_wallet);
1094  EnsureWalletIsUnlocked(pwallet);
1095 
1096  // Verify all timestamps are present before importing any keys.
1097  const int64_t now = chainActive.Tip() ? chainActive.Tip()->GetMedianTimePast() : 0;
1098  for (const UniValue& data : requests.getValues()) {
1099  GetImportTimestamp(data, now);
1100  }
1101 
1102  bool fRunScan = false;
1103  const int64_t minimumTimestamp = 1;
1104  int64_t nLowestTimestamp = 0;
1105 
1106  if (fRescan && chainActive.Tip()) {
1107  nLowestTimestamp = chainActive.Tip()->GetBlockTime();
1108  } else {
1109  fRescan = false;
1110  }
1111 
1112  UniValue response(UniValue::VARR);
1113 
1114  for (const UniValue& data : requests.getValues()) {
1115  const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);
1116  const UniValue result = ProcessImport(pwallet, data, timestamp);
1117  response.push_back(result);
1118 
1119  if (!fRescan) {
1120  continue;
1121  }
1122 
1123  // If at least one request was successful then allow rescan.
1124  if (result["success"].get_bool()) {
1125  fRunScan = true;
1126  }
1127 
1128  // Get the lowest timestamp.
1129  if (timestamp < nLowestTimestamp) {
1130  nLowestTimestamp = timestamp;
1131  }
1132  }
1133 
1134  if (fRescan && fRunScan && requests.size()) {
1135  int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, true /* update */);
1136  pwallet->ReacceptWalletTransactions();
1137 
1138  if (scannedTime > nLowestTimestamp) {
1139  std::vector<UniValue> results = response.getValues();
1140  response.clear();
1141  response.setArray();
1142  size_t i = 0;
1143  for (const UniValue& request : requests.getValues()) {
1144  // If key creation date is within the successfully scanned
1145  // range, or if the import result already has an error set, let
1146  // the result stand unmodified. Otherwise replace the result
1147  // with an error message.
1148  if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists("error")) {
1149  response.push_back(results.at(i));
1150  } else {
1151  UniValue result = UniValue(UniValue::VOBJ);
1152  result.pushKV("success", UniValue(false));
1153  result.pushKV(
1154  "error",
1155  JSONRPCError(
1157  strprintf("Rescan failed for key with creation timestamp %d. There was an error reading a "
1158  "block from time %d, which is after or within %d seconds of key creation, and "
1159  "could contain transactions pertaining to the key. As a result, transactions "
1160  "and coins using this key may not appear in the wallet. This error could be "
1161  "caused by pruning or data corruption (see ravend log for details) and could "
1162  "be dealt with by downloading and rescanning the relevant blocks (see -reindex "
1163  "and -rescan options).",
1164  GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));
1165  response.push_back(std::move(result));
1166  }
1167  ++i;
1168  }
1169  }
1170  }
1171 
1172  return response;
1173 }
std::string DecodeDumpString(const std::string &str)
Definition: rpcdump.cpp:61
UniValue abortrescan(const JSONRPCRequest &request)
Definition: rpcdump.cpp:159
void SetKey(const K &key)
Definition: base58.h:139
boost::variant< CNoDestination, CKeyID, CScriptID > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:89
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:89
const std::vector< UniValue > & getValues() const
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:210
bool HaveKey(const CKeyID &address) const override
Check whether a key corresponding to a given address is present in the store.
Definition: crypter.h:164
int64_t GetBlockTime() const
Definition: chain.h:299
void GetKeyBirthTimes(std::map< CTxDestination, int64_t > &mapKeyBirth) const
Definition: wallet.cpp:4361
bool get_bool() const
const std::map< CKeyID, int64_t > & GetAllReserveKeys() const
Definition: wallet.h:1051
UniValue dumpprivkey(const JSONRPCRequest &request)
Definition: rpcdump.cpp:551
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:829
CCriticalSection cs_wallet
Definition: wallet.h:751
#define strprintf
Definition: tinyformat.h:1054
bool IsPayToScriptHash() const
Definition: script.cpp:221
bool VerifyPubKey(const CPubKey &vchPubKey) const
Verify thoroughly whether a private key and a public key match.
Definition: key.cpp:176
UniValue importmulti(const JSONRPCRequest &mainRequest)
Definition: rpcdump.cpp:1032
CPubKey GetPubKey() const
Compute the public key from a private key.
Definition: key.cpp:148
int nIndex
Definition: wallet.h:219
bool EnsureWalletIsAvailable(CWallet *const pwallet, bool avoidException)
Definition: rpcwallet.cpp:63
bool HaveCScript(const CScriptID &hash) const override
Definition: keystore.cpp:50
std::string DateTimeStrFormat(const char *pszFormat, int64_t nTime)
Definition: utiltime.cpp:79
bool AddKeyPubKey(const CKey &key, const CPubKey &pubkey) override
Adds a key to the store, and saves it to disk.
Definition: wallet.cpp:256
Definition: key.h:136
void ReacceptWalletTransactions()
Definition: wallet.cpp:1678
int Height() const
Return the maximal height in the chain.
Definition: chain.h:479
uint256 hashBlock
Definition: wallet.h:212
CCriticalSection cs_main
Global state.
Definition: validation.cpp:72
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:402
CTxDestination DecodeDestination(const std::string &str)
Definition: base58.cpp:333
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
Definition: standard.cpp:363
UniValue dumpwallet(const JSONRPCRequest &request)
Definition: rpcdump.cpp:594
isminetype IsMine(const CKeyStore &keystore, const CScript &scriptPubKey, SigVersion sigversion)
Definition: ismine.cpp:32
const std::string & get_str() const
enum VType getType() const
Definition: univalue.h:66
bool isNum() const
Definition: univalue.h:84
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:527
const UniValue & get_array() const
bool isStr() const
Definition: univalue.h:83
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:147
int64_t get_int64() const
std::map< CTxDestination, CKeyMetadata > mapKeyMetadata
Definition: wallet.h:776
CKey GetKey()
Definition: base58.cpp:301
const unsigned char * begin() const
Definition: key.h:84
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:143
bool IsNull() const
Definition: uint256.h:33
bool AddWatchOnly(const CScript &dest) override
Private version of AddWatchOnly method which does not accept a timestamp, and which will reset the wa...
Definition: wallet.cpp:332
void RPCTypeCheck(const UniValue &params, const std::list< UniValue::VType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: server.cpp:58
Invalid, missing or duplicate parameter.
Definition: protocol.h:54
std::string ToString() const
Definition: base58.cpp:194
uint256 GetBlockHash() const
Definition: chain.h:294
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3832
void MarkDirty()
Definition: wallet.cpp:846
#define LOCK2(cs1, cs2)
Definition: sync.h:177
const char * uvTypeName(UniValue::VType t)
Definition: univalue.cpp:221
Used to relay blocks as header + vector<merkle branch> to filtered nodes.
Definition: merkleblock.h:128
bool push_back(const UniValue &val)
Definition: univalue.cpp:110
#define LogPrintf(...)
Definition: util.h:149
UniValue params
Definition: server.h:45
bool AddCScript(const CScript &redeemScript) override
Support for BIP 0013 : see https://github.com/raven/bips/blob/master/bip-0013.mediawiki.
Definition: wallet.cpp:309
bool DecodeHexTx(CMutableTransaction &tx, const std::string &strHexTx, bool fTryNoWitness=false)
Definition: core_read.cpp:112
#define LOCK(cs)
Definition: sync.h:176
bool exists(const std::string &key) const
Definition: univalue.h:77
void ImportScript(CWallet *const pwallet, const CScript &script, const std::string &strLabel, bool isRedeemScript)
Definition: rpcdump.cpp:186
bool Contains(const CBlockIndex *pindex) const
Efficiently check whether a block is present in this chain.
Definition: chain.h:466
UniValue removeprunedfunds(const JSONRPCRequest &request)
Definition: rpcdump.cpp:352
An encapsulated public key.
Definition: pubkey.h:40
bool SetString(const char *pszSecret)
Definition: base58.cpp:316
bool IsHex(const std::string &str)
Unexpected type was passed as parameter.
Definition: protocol.h:51
void UpdateTimeFirstKey(int64_t nCreateTime)
Update wallet first key creation time.
Definition: wallet.cpp:297
General application defined errors.
Definition: protocol.h:49
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:135
UniValue ProcessImport(CWallet *const pwallet, const UniValue &data, const int64_t timestamp)
Definition: rpcdump.cpp:705
bool GetKey(const CKeyID &address, CKey &keyOut) const override
Definition: crypter.cpp:242
DBErrors ZapSelectTx(std::vector< uint256 > &vHashIn, std::vector< uint256 > &vHashOut)
Definition: wallet.cpp:3779
unsigned int size() const
Simple read-only vector-like interface.
Definition: key.h:83
CChain chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:75
std::string ToString() const
Definition: uint256.cpp:63
Invalid address or key.
Definition: protocol.h:52
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Raven scriptPubKey for the given CTxDestination.
Definition: standard.cpp:347
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:522
bool isNull() const
Definition: univalue.h:79
void SetSeed(const unsigned char *seed, unsigned int nSeedLen)
Definition: key.cpp:245
bool AddToWallet(const CWalletTx &wtxIn, bool fFlushOnClose=true)
Definition: wallet.cpp:884
int64_t GetMedianTimePast() const
Definition: chain.h:311
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:285
std::vector< unsigned char > ParseHexV(const UniValue &v, std::string strName)
Definition: server.cpp:142
int64_t RescanFromTime(int64_t startTime, bool update)
Scan active chain for relevant transactions after importing keys.
Definition: wallet.cpp:1595
bool fHelp
Definition: server.h:46
int64_t GetImportTimestamp(const UniValue &data, int64_t now)
Definition: rpcdump.cpp:1018
256-bit opaque blob.
Definition: uint256.h:123
enum VType type() const
Definition: univalue.h:175
bool setArray()
Definition: univalue.cpp:96
uint256 GetHash() const
Compute the hash of this CMutableTransaction.
Definition: transaction.cpp:69
std::string EncodeDestination(const CTxDestination &dest)
Definition: base58.cpp:326
A base58-encoded secret key.
Definition: base58.h:123
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:396
UniValue importpubkey(const JSONRPCRequest &request)
Definition: rpcdump.cpp:390
A reference to a CKey: the Hash160 of its serialized public key.
Definition: pubkey.h:30
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:448
bool IsScanning()
Definition: wallet.h:909
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:673
const UniValue NullUniValue
Definition: univalue.cpp:15
CWallet * GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: rpcwallet.cpp:40
UniValue importprivkey(const JSONRPCRequest &request)
Definition: rpcdump.cpp:75
void AbortRescan()
Definition: wallet.h:907
UniValue importwallet(const JSONRPCRequest &request)
Definition: rpcdump.cpp:450
void ObserveSafeMode()
Definition: safemode.cpp:7
boost::signals2::signal< void(const std::string &title, int nProgress)> ShowProgress
Show progress e.g.
Definition: wallet.h:1142
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:23
UniValue importaddress(const JSONRPCRequest &request)
Definition: rpcdump.cpp:220
A mutable version of CTransaction.
Definition: transaction.h:389
Wallet errors.
Definition: protocol.h:78
bool IsAbortingRescan()
Definition: wallet.h:908
void ImportAddress(CWallet *, const CTxDestination &dest, const std::string &strLabel)
Definition: rpcdump.cpp:211
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:55
void clear()
Definition: univalue.cpp:17
size_t size() const
Definition: univalue.h:70
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
An encapsulated private key.
Definition: key.h:36
bool HaveWatchOnly(const CScript &dest) const override
Definition: keystore.cpp:104
isminetype IsMine(const CTxIn &txin) const
Definition: wallet.cpp:1241
const CHDChain & GetHDChain() const
Definition: wallet.h:1174
CKeyID seed_id
seed hash160
Definition: walletdb.h:66
void SetHex(const char *psz)
Definition: uint256.cpp:28
const std::string CLIENT_BUILD
BlockMap mapBlockIndex
Definition: validation.cpp:74
UniValue importprunedfunds(const JSONRPCRequest &request)
Definition: rpcdump.cpp:291
std::string _(const char *psz)
Translation function: Call Translate signal on UI interface, which returns a boost::optional result...
Definition: util.h:66
Error parsing or validating structure in raw format.
Definition: protocol.h:56
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:88
void EnsureWalletIsUnlocked(CWallet *const pwallet)
Definition: rpcwallet.cpp:80
std::vector< unsigned char > ParseHex(const char *psz)