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