Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

rpcdump.cpp 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. // Copyright (c) 2009-2016 The Bitcoin Core developers
  2. // Distributed under the MIT software license, see the accompanying
  3. // file COPYING or http://www.opensource.org/licenses/mit-license.php.
  4. #include "base58.h"
  5. #include "chain.h"
  6. #include "rpc/server.h"
  7. #include "init.h"
  8. #include "validation.h"
  9. #include "script/script.h"
  10. #include "script/standard.h"
  11. #include "sync.h"
  12. #include "util.h"
  13. #include "utiltime.h"
  14. #include "wallet.h"
  15. #include "merkleblock.h"
  16. #include "core_io.h"
  17. #include "rpcwallet.h"
  18. #include <fstream>
  19. #include <stdint.h>
  20. #include <boost/algorithm/string.hpp>
  21. #include <boost/date_time/posix_time/posix_time.hpp>
  22. #include <univalue.h>
  23. std::string static EncodeDumpTime(int64_t nTime) {
  24. return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
  25. }
  26. int64_t static DecodeDumpTime(const std::string &str) {
  27. static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
  28. static const std::locale loc(std::locale::classic(),
  29. new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
  30. std::istringstream iss(str);
  31. iss.imbue(loc);
  32. boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
  33. iss >> ptime;
  34. if (ptime.is_not_a_date_time())
  35. return 0;
  36. return (ptime - epoch).total_seconds();
  37. }
  38. std::string static EncodeDumpString(const std::string &str) {
  39. std::stringstream ret;
  40. for (unsigned char c : str) {
  41. if (c <= 32 || c >= 128 || c == '%') {
  42. ret << '%' << HexStr(&c, &c + 1);
  43. } else {
  44. ret << c;
  45. }
  46. }
  47. return ret.str();
  48. }
  49. std::string DecodeDumpString(const std::string &str) {
  50. std::stringstream ret;
  51. for (unsigned int pos = 0; pos < str.length(); pos++) {
  52. unsigned char c = str[pos];
  53. if (c == '%' && pos+2 < str.length()) {
  54. c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
  55. ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
  56. pos += 2;
  57. }
  58. ret << c;
  59. }
  60. return ret.str();
  61. }
  62. UniValue importprivkey(const JSONRPCRequest& request)
  63. {
  64. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  65. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  66. return NullUniValue;
  67. }
  68. if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
  69. throw std::runtime_error(
  70. "importprivkey \"privkey\" ( \"label\" ) ( rescan )\n"
  71. "\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\n"
  72. "\nArguments:\n"
  73. "1. \"privkey\" (string, required) The private key (see dumpprivkey)\n"
  74. "2. \"label\" (string, optional, default=\"\") An optional label\n"
  75. "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
  76. "\nNote: This call can take minutes to complete if rescan is true.\n"
  77. "\nExamples:\n"
  78. "\nDump a private key\n"
  79. + HelpExampleCli("dumpprivkey", "\"myaddress\"") +
  80. "\nImport the private key with rescan\n"
  81. + HelpExampleCli("importprivkey", "\"mykey\"") +
  82. "\nImport using a label and without rescan\n"
  83. + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
  84. "\nImport using default blank label and without rescan\n"
  85. + HelpExampleCli("importprivkey", "\"mykey\" \"\" false") +
  86. "\nAs a JSON-RPC call\n"
  87. + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")
  88. );
  89. LOCK2(cs_main, pwallet->cs_wallet);
  90. EnsureWalletIsUnlocked(pwallet);
  91. std::string strSecret = request.params[0].get_str();
  92. std::string strLabel = "";
  93. if (!request.params[1].isNull())
  94. strLabel = request.params[1].get_str();
  95. // Whether to perform rescan after import
  96. bool fRescan = true;
  97. if (!request.params[2].isNull())
  98. fRescan = request.params[2].get_bool();
  99. if (fRescan && fPruneMode)
  100. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
  101. CBitcoinSecret vchSecret;
  102. bool fGood = vchSecret.SetString(strSecret);
  103. if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
  104. CKey key = vchSecret.GetKey();
  105. if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
  106. CPubKey pubkey = key.GetPubKey();
  107. assert(key.VerifyPubKey(pubkey));
  108. CKeyID vchAddress = pubkey.GetID();
  109. {
  110. pwallet->MarkDirty();
  111. pwallet->SetAddressBook(vchAddress, strLabel, "receive");
  112. // Don't throw error in case a key is already there
  113. if (pwallet->HaveKey(vchAddress)) {
  114. return NullUniValue;
  115. }
  116. pwallet->mapKeyMetadata[vchAddress].nCreateTime = 1;
  117. if (!pwallet->AddKeyPubKey(key, pubkey)) {
  118. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
  119. }
  120. // whenever a key is imported, we need to scan the whole chain
  121. pwallet->UpdateTimeFirstKey(1);
  122. if (fRescan) {
  123. pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
  124. }
  125. }
  126. return NullUniValue;
  127. }
  128. UniValue abortrescan(const JSONRPCRequest& request)
  129. {
  130. CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
  131. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  132. return NullUniValue;
  133. }
  134. if (request.fHelp || request.params.size() > 0)
  135. throw std::runtime_error(
  136. "abortrescan\n"
  137. "\nStops current wallet rescan triggered e.g. by an importprivkey call.\n"
  138. "\nExamples:\n"
  139. "\nImport a private key\n"
  140. + HelpExampleCli("importprivkey", "\"mykey\"") +
  141. "\nAbort the running wallet rescan\n"
  142. + HelpExampleCli("abortrescan", "") +
  143. "\nAs a JSON-RPC call\n"
  144. + HelpExampleRpc("abortrescan", "")
  145. );
  146. if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false;
  147. pwallet->AbortRescan();
  148. return true;
  149. }
  150. void ImportAddress(CWallet*, const CBitcoinAddress& address, const std::string& strLabel);
  151. void ImportScript(CWallet* const pwallet, const CScript& script, const std::string& strLabel, bool isRedeemScript)
  152. {
  153. if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
  154. throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
  155. }
  156. pwallet->MarkDirty();
  157. if (!pwallet->HaveWatchOnly(script) && !pwallet->AddWatchOnly(script, 0 /* nCreateTime */)) {
  158. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
  159. }
  160. if (isRedeemScript) {
  161. if (!pwallet->HaveCScript(script) && !pwallet->AddCScript(script)) {
  162. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
  163. }
  164. ImportAddress(pwallet, CBitcoinAddress(CScriptID(script)), strLabel);
  165. } else {
  166. CTxDestination destination;
  167. if (ExtractDestination(script, destination)) {
  168. pwallet->SetAddressBook(destination, strLabel, "receive");
  169. }
  170. }
  171. }
  172. void ImportAddress(CWallet* const pwallet, const CBitcoinAddress& address, const std::string& strLabel)
  173. {
  174. CScript script = GetScriptForDestination(address.Get());
  175. ImportScript(pwallet, script, strLabel, false);
  176. // add to address book or update label
  177. if (address.IsValid())
  178. pwallet->SetAddressBook(address.Get(), strLabel, "receive");
  179. }
  180. UniValue importaddress(const JSONRPCRequest& request)
  181. {
  182. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  183. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  184. return NullUniValue;
  185. }
  186. if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
  187. throw std::runtime_error(
  188. "importaddress \"address\" ( \"label\" rescan p2sh )\n"
  189. "\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n"
  190. "\nArguments:\n"
  191. "1. \"script\" (string, required) The hex-encoded script (or address)\n"
  192. "2. \"label\" (string, optional, default=\"\") An optional label\n"
  193. "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
  194. "4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n"
  195. "\nNote: This call can take minutes to complete if rescan is true.\n"
  196. "If you have the full public key, you should call importpubkey instead of this.\n"
  197. "\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n"
  198. "as change, and not show up in many RPCs.\n"
  199. "\nExamples:\n"
  200. "\nImport a script with rescan\n"
  201. + HelpExampleCli("importaddress", "\"myscript\"") +
  202. "\nImport using a label without rescan\n"
  203. + HelpExampleCli("importaddress", "\"myscript\" \"testing\" false") +
  204. "\nAs a JSON-RPC call\n"
  205. + HelpExampleRpc("importaddress", "\"myscript\", \"testing\", false")
  206. );
  207. std::string strLabel = "";
  208. if (!request.params[1].isNull())
  209. strLabel = request.params[1].get_str();
  210. // Whether to perform rescan after import
  211. bool fRescan = true;
  212. if (!request.params[2].isNull())
  213. fRescan = request.params[2].get_bool();
  214. if (fRescan && fPruneMode)
  215. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
  216. // Whether to import a p2sh version, too
  217. bool fP2SH = false;
  218. if (!request.params[3].isNull())
  219. fP2SH = request.params[3].get_bool();
  220. LOCK2(cs_main, pwallet->cs_wallet);
  221. CBitcoinAddress address(request.params[0].get_str());
  222. if (address.IsValid()) {
  223. if (fP2SH)
  224. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead");
  225. ImportAddress(pwallet, address, strLabel);
  226. } else if (IsHex(request.params[0].get_str())) {
  227. std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
  228. ImportScript(pwallet, CScript(data.begin(), data.end()), strLabel, fP2SH);
  229. } else {
  230. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address or script");
  231. }
  232. if (fRescan)
  233. {
  234. pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
  235. pwallet->ReacceptWalletTransactions();
  236. }
  237. return NullUniValue;
  238. }
  239. UniValue importprunedfunds(const JSONRPCRequest& request)
  240. {
  241. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  242. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  243. return NullUniValue;
  244. }
  245. if (request.fHelp || request.params.size() != 2)
  246. throw std::runtime_error(
  247. "importprunedfunds\n"
  248. "\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"
  249. "\nArguments:\n"
  250. "1. \"rawtransaction\" (string, required) A raw transaction in hex funding an already-existing address in wallet\n"
  251. "2. \"txoutproof\" (string, required) The hex output from gettxoutproof that contains the transaction\n"
  252. );
  253. CMutableTransaction tx;
  254. if (!DecodeHexTx(tx, request.params[0].get_str()))
  255. throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
  256. uint256 hashTx = tx.GetHash();
  257. CWalletTx wtx(pwallet, MakeTransactionRef(std::move(tx)));
  258. CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION);
  259. CMerkleBlock merkleBlock;
  260. ssMB >> merkleBlock;
  261. //Search partial merkle tree in proof for our transaction and index in valid block
  262. std::vector<uint256> vMatch;
  263. std::vector<unsigned int> vIndex;
  264. unsigned int txnIndex = 0;
  265. if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {
  266. LOCK(cs_main);
  267. if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
  268. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
  269. std::vector<uint256>::const_iterator it;
  270. if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) {
  271. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
  272. }
  273. txnIndex = vIndex[it - vMatch.begin()];
  274. }
  275. else {
  276. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
  277. }
  278. wtx.nIndex = txnIndex;
  279. wtx.hashBlock = merkleBlock.header.GetHash();
  280. LOCK2(cs_main, pwallet->cs_wallet);
  281. if (pwallet->IsMine(wtx)) {
  282. pwallet->AddToWallet(wtx, false);
  283. return NullUniValue;
  284. }
  285. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
  286. }
  287. UniValue removeprunedfunds(const JSONRPCRequest& request)
  288. {
  289. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  290. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  291. return NullUniValue;
  292. }
  293. if (request.fHelp || request.params.size() != 1)
  294. throw std::runtime_error(
  295. "removeprunedfunds \"txid\"\n"
  296. "\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"
  297. "\nArguments:\n"
  298. "1. \"txid\" (string, required) The hex-encoded id of the transaction you are deleting\n"
  299. "\nExamples:\n"
  300. + HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") +
  301. "\nAs a JSON-RPC call\n"
  302. + HelpExampleRpc("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"")
  303. );
  304. LOCK2(cs_main, pwallet->cs_wallet);
  305. uint256 hash;
  306. hash.SetHex(request.params[0].get_str());
  307. std::vector<uint256> vHash;
  308. vHash.push_back(hash);
  309. std::vector<uint256> vHashOut;
  310. if (pwallet->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) {
  311. throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction.");
  312. }
  313. if(vHashOut.empty()) {
  314. throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction does not exist in wallet.");
  315. }
  316. return NullUniValue;
  317. }
  318. UniValue importpubkey(const JSONRPCRequest& request)
  319. {
  320. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  321. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  322. return NullUniValue;
  323. }
  324. if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
  325. throw std::runtime_error(
  326. "importpubkey \"pubkey\" ( \"label\" rescan )\n"
  327. "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n"
  328. "\nArguments:\n"
  329. "1. \"pubkey\" (string, required) The hex-encoded public key\n"
  330. "2. \"label\" (string, optional, default=\"\") An optional label\n"
  331. "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
  332. "\nNote: This call can take minutes to complete if rescan is true.\n"
  333. "\nExamples:\n"
  334. "\nImport a public key with rescan\n"
  335. + HelpExampleCli("importpubkey", "\"mypubkey\"") +
  336. "\nImport using a label without rescan\n"
  337. + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") +
  338. "\nAs a JSON-RPC call\n"
  339. + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false")
  340. );
  341. std::string strLabel = "";
  342. if (!request.params[1].isNull())
  343. strLabel = request.params[1].get_str();
  344. // Whether to perform rescan after import
  345. bool fRescan = true;
  346. if (!request.params[2].isNull())
  347. fRescan = request.params[2].get_bool();
  348. if (fRescan && fPruneMode)
  349. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
  350. if (!IsHex(request.params[0].get_str()))
  351. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
  352. std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
  353. CPubKey pubKey(data.begin(), data.end());
  354. if (!pubKey.IsFullyValid())
  355. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
  356. LOCK2(cs_main, pwallet->cs_wallet);
  357. ImportAddress(pwallet, CBitcoinAddress(pubKey.GetID()), strLabel);
  358. ImportScript(pwallet, GetScriptForRawPubKey(pubKey), strLabel, false);
  359. if (fRescan)
  360. {
  361. pwallet->RescanFromTime(TIMESTAMP_MIN, true /* update */);
  362. pwallet->ReacceptWalletTransactions();
  363. }
  364. return NullUniValue;
  365. }
  366. UniValue importwallet(const JSONRPCRequest& request)
  367. {
  368. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  369. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  370. return NullUniValue;
  371. }
  372. if (request.fHelp || request.params.size() != 1)
  373. throw std::runtime_error(
  374. "importwallet \"filename\"\n"
  375. "\nImports keys from a wallet dump file (see dumpwallet). Requires a new wallet backup to include imported keys.\n"
  376. "\nArguments:\n"
  377. "1. \"filename\" (string, required) The wallet file\n"
  378. "\nExamples:\n"
  379. "\nDump the wallet\n"
  380. + HelpExampleCli("dumpwallet", "\"test\"") +
  381. "\nImport the wallet\n"
  382. + HelpExampleCli("importwallet", "\"test\"") +
  383. "\nImport using the json rpc call\n"
  384. + HelpExampleRpc("importwallet", "\"test\"")
  385. );
  386. if (fPruneMode)
  387. throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode");
  388. LOCK2(cs_main, pwallet->cs_wallet);
  389. EnsureWalletIsUnlocked(pwallet);
  390. std::ifstream file;
  391. file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate);
  392. if (!file.is_open())
  393. throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
  394. int64_t nTimeBegin = chainActive.Tip()->GetBlockTime();
  395. bool fGood = true;
  396. int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
  397. file.seekg(0, file.beg);
  398. pwallet->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
  399. while (file.good()) {
  400. pwallet->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
  401. std::string line;
  402. std::getline(file, line);
  403. if (line.empty() || line[0] == '#')
  404. continue;
  405. std::vector<std::string> vstr;
  406. boost::split(vstr, line, boost::is_any_of(" "));
  407. if (vstr.size() < 2)
  408. continue;
  409. CBitcoinSecret vchSecret;
  410. if (!vchSecret.SetString(vstr[0]))
  411. continue;
  412. CKey key = vchSecret.GetKey();
  413. CPubKey pubkey = key.GetPubKey();
  414. assert(key.VerifyPubKey(pubkey));
  415. CKeyID keyid = pubkey.GetID();
  416. if (pwallet->HaveKey(keyid)) {
  417. LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString());
  418. continue;
  419. }
  420. int64_t nTime = DecodeDumpTime(vstr[1]);
  421. std::string strLabel;
  422. bool fLabel = true;
  423. for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
  424. if (boost::algorithm::starts_with(vstr[nStr], "#"))
  425. break;
  426. if (vstr[nStr] == "change=1")
  427. fLabel = false;
  428. if (vstr[nStr] == "reserve=1")
  429. fLabel = false;
  430. if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
  431. strLabel = DecodeDumpString(vstr[nStr].substr(6));
  432. fLabel = true;
  433. }
  434. }
  435. LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString());
  436. if (!pwallet->AddKeyPubKey(key, pubkey)) {
  437. fGood = false;
  438. continue;
  439. }
  440. pwallet->mapKeyMetadata[keyid].nCreateTime = nTime;
  441. if (fLabel)
  442. pwallet->SetAddressBook(keyid, strLabel, "receive");
  443. nTimeBegin = std::min(nTimeBegin, nTime);
  444. }
  445. file.close();
  446. pwallet->ShowProgress("", 100); // hide progress dialog in GUI
  447. pwallet->UpdateTimeFirstKey(nTimeBegin);
  448. pwallet->RescanFromTime(nTimeBegin, false /* update */);
  449. pwallet->MarkDirty();
  450. if (!fGood)
  451. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet");
  452. return NullUniValue;
  453. }
  454. UniValue dumpprivkey(const JSONRPCRequest& request)
  455. {
  456. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  457. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  458. return NullUniValue;
  459. }
  460. if (request.fHelp || request.params.size() != 1)
  461. throw std::runtime_error(
  462. "dumpprivkey \"address\"\n"
  463. "\nReveals the private key corresponding to 'address'.\n"
  464. "Then the importprivkey can be used with this output\n"
  465. "\nArguments:\n"
  466. "1. \"address\" (string, required) The bitcoin address for the private key\n"
  467. "\nResult:\n"
  468. "\"key\" (string) The private key\n"
  469. "\nExamples:\n"
  470. + HelpExampleCli("dumpprivkey", "\"myaddress\"")
  471. + HelpExampleCli("importprivkey", "\"mykey\"")
  472. + HelpExampleRpc("dumpprivkey", "\"myaddress\"")
  473. );
  474. LOCK2(cs_main, pwallet->cs_wallet);
  475. EnsureWalletIsUnlocked(pwallet);
  476. std::string strAddress = request.params[0].get_str();
  477. CBitcoinAddress address;
  478. if (!address.SetString(strAddress))
  479. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address");
  480. CKeyID keyID;
  481. if (!address.GetKeyID(keyID))
  482. throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
  483. CKey vchSecret;
  484. if (!pwallet->GetKey(keyID, vchSecret)) {
  485. throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
  486. }
  487. return CBitcoinSecret(vchSecret).ToString();
  488. }
  489. UniValue dumpwallet(const JSONRPCRequest& request)
  490. {
  491. CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
  492. if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
  493. return NullUniValue;
  494. }
  495. if (request.fHelp || request.params.size() != 1)
  496. throw std::runtime_error(
  497. "dumpwallet \"filename\"\n"
  498. "\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\n"
  499. "Note that if your wallet contains keys which are not derived from your HD seed (e.g. imported keys), these are not covered by only backing up the seed itself, and must be backed up too (e.g. ensure you back up the whole dumpfile).\n"
  500. "\nArguments:\n"
  501. "1. \"filename\" (string, required) The filename with path (either absolute or relative to bitcoind)\n"
  502. "\nResult:\n"
  503. "{ (json object)\n"
  504. " \"filename\" : { (string) The filename with full absolute path\n"
  505. "}\n"
  506. "\nExamples:\n"
  507. + HelpExampleCli("dumpwallet", "\"test\"")
  508. + HelpExampleRpc("dumpwallet", "\"test\"")
  509. );
  510. LOCK2(cs_main, pwallet->cs_wallet);
  511. EnsureWalletIsUnlocked(pwallet);
  512. boost::filesystem::path filepath = request.params[0].get_str();
  513. filepath = boost::filesystem::absolute(filepath);
  514. /* Prevent arbitrary files from being overwritten. There have been reports
  515. * that users have overwritten wallet files this way:
  516. * https://github.com/bitcoin/bitcoin/issues/9934
  517. * It may also avoid other security issues.
  518. */
  519. if (boost::filesystem::exists(filepath)) {
  520. 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");
  521. }
  522. std::ofstream file;
  523. file.open(filepath.string().c_str());
  524. if (!file.is_open())
  525. throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
  526. std::map<CTxDestination, int64_t> mapKeyBirth;
  527. const std::map<CKeyID, int64_t>& mapKeyPool = pwallet->GetAllReserveKeys();
  528. pwallet->GetKeyBirthTimes(mapKeyBirth);
  529. // sort time/key pairs
  530. std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
  531. for (const auto& entry : mapKeyBirth) {
  532. if (const CKeyID* keyID = boost::get<CKeyID>(&entry.first)) { // set and test
  533. vKeyBirth.push_back(std::make_pair(entry.second, *keyID));
  534. }
  535. }
  536. mapKeyBirth.clear();
  537. std::sort(vKeyBirth.begin(), vKeyBirth.end());
  538. // produce output
  539. file << strprintf("# Wallet dump created by Bitcoin %s\n", CLIENT_BUILD);
  540. file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
  541. file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
  542. file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
  543. file << "\n";
  544. // add the base58check encoded extended master if the wallet uses HD
  545. CKeyID masterKeyID = pwallet->GetHDChain().masterKeyID;
  546. if (!masterKeyID.IsNull())
  547. {
  548. CKey key;
  549. if (pwallet->GetKey(masterKeyID, key)) {
  550. CExtKey masterKey;
  551. masterKey.SetMaster(key.begin(), key.size());
  552. CBitcoinExtKey b58extkey;
  553. b58extkey.SetKey(masterKey);
  554. file << "# extended private masterkey: " << b58extkey.ToString() << "\n\n";
  555. }
  556. }
  557. for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
  558. const CKeyID &keyid = it->second;
  559. std::string strTime = EncodeDumpTime(it->first);
  560. std::string strAddr = CBitcoinAddress(keyid).ToString();
  561. CKey key;
  562. if (pwallet->GetKey(keyid, key)) {
  563. file << strprintf("%s %s ", CBitcoinSecret(key).ToString(), strTime);
  564. if (pwallet->mapAddressBook.count(keyid)) {
  565. file << strprintf("label=%s", EncodeDumpString(pwallet->mapAddressBook[keyid].name));
  566. } else if (keyid == masterKeyID) {
  567. file << "hdmaster=1";
  568. } else if (mapKeyPool.count(keyid)) {
  569. file << "reserve=1";
  570. } else if (pwallet->mapKeyMetadata[keyid].hdKeypath == "m") {
  571. file << "inactivehdmaster=1";
  572. } else {
  573. file << "change=1";
  574. }
  575. file << strprintf(" # addr=%s%s\n", strAddr, (pwallet->mapKeyMetadata[keyid].hdKeypath.size() > 0 ? " hdkeypath="+pwallet->mapKeyMetadata[keyid].hdKeypath : ""));
  576. }
  577. }
  578. file << "\n";
  579. file << "# End of dump\n";
  580. file.close();
  581. UniValue reply(UniValue::VOBJ);
  582. reply.push_back(Pair("filename", filepath.string()));
  583. return reply;
  584. }
  585. UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int64_t timestamp)
  586. {
  587. try {
  588. bool success = false;
  589. // Required fields.
  590. const UniValue& scriptPubKey = data["scriptPubKey"];
  591. // Should have script or JSON with "address".
  592. if (!(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address")) && !(scriptPubKey.getType() == UniValue::VSTR)) {
  593. throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid scriptPubKey");
  594. }
  595. // Optional fields.
  596. const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : "";
  597. const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue();
  598. const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
  599. const bool& internal = data.exists("internal") ? data["internal"].get_bool() : false;
  600. const bool& watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
  601. const std::string& label = data.exists("label") && !internal ? data["label"].get_str() : "";
  602. bool isScript = scriptPubKey.getType() == UniValue::VSTR;
  603. bool isP2SH = strRedeemScript.length() > 0;
  604. const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str();
  605. // Parse the output.
  606. CScript script;
  607. CBitcoinAddress address;
  608. if (!isScript) {
  609. address = CBitcoinAddress(output);
  610. if (!address.IsValid()) {
  611. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
  612. }
  613. script = GetScriptForDestination(address.Get());
  614. } else {
  615. if (!IsHex(output)) {
  616. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey");
  617. }
  618. std::vector<unsigned char> vData(ParseHex(output));
  619. script = CScript(vData.begin(), vData.end());
  620. }
  621. // Watchonly and private keys
  622. if (watchOnly && keys.size()) {
  623. throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between watchonly and keys");
  624. }
  625. // Internal + Label
  626. if (internal && data.exists("label")) {
  627. throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between internal and label");
  628. }
  629. // Not having Internal + Script
  630. if (!internal && isScript) {
  631. throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set for hex scriptPubKey");
  632. }
  633. // Keys / PubKeys size check.
  634. if (!isP2SH && (keys.size() > 1 || pubKeys.size() > 1)) { // Address / scriptPubKey
  635. throw JSONRPCError(RPC_INVALID_PARAMETER, "More than private key given for one address");
  636. }
  637. // Invalid P2SH redeemScript
  638. if (isP2SH && !IsHex(strRedeemScript)) {
  639. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script");
  640. }
  641. // Process. //
  642. // P2SH
  643. if (isP2SH) {
  644. // Import redeem script.
  645. std::vector<unsigned char> vData(ParseHex(strRedeemScript));
  646. CScript redeemScript = CScript(vData.begin(), vData.end());
  647. // Invalid P2SH address
  648. if (!script.IsPayToScriptHash()) {
  649. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid P2SH address / script");
  650. }
  651. pwallet->MarkDirty();
  652. if (!pwallet->AddWatchOnly(redeemScript, timestamp)) {
  653. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
  654. }
  655. if (!pwallet->HaveCScript(redeemScript) && !pwallet->AddCScript(redeemScript)) {
  656. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
  657. }
  658. CBitcoinAddress redeemAddress = CBitcoinAddress(CScriptID(redeemScript));
  659. CScript redeemDestination = GetScriptForDestination(redeemAddress.Get());
  660. if (::IsMine(*pwallet, redeemDestination) == ISMINE_SPENDABLE) {
  661. throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
  662. }
  663. pwallet->MarkDirty();
  664. if (!pwallet->AddWatchOnly(redeemDestination, timestamp)) {
  665. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
  666. }
  667. // add to address book or update label
  668. if (address.IsValid()) {
  669. pwallet->SetAddressBook(address.Get(), label, "receive");
  670. }
  671. // Import private keys.
  672. if (keys.size()) {
  673. for (size_t i = 0; i < keys.size(); i++) {
  674. const std::string& privkey = keys[i].get_str();
  675. CBitcoinSecret vchSecret;
  676. bool fGood = vchSecret.SetString(privkey);
  677. if (!fGood) {
  678. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
  679. }
  680. CKey key = vchSecret.GetKey();
  681. if (!key.IsValid()) {
  682. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
  683. }
  684. CPubKey pubkey = key.GetPubKey();
  685. assert(key.VerifyPubKey(pubkey));
  686. CKeyID vchAddress = pubkey.GetID();
  687. pwallet->MarkDirty();
  688. pwallet->SetAddressBook(vchAddress, label, "receive");
  689. if (pwallet->HaveKey(vchAddress)) {
  690. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key");
  691. }
  692. pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
  693. if (!pwallet->AddKeyPubKey(key, pubkey)) {
  694. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
  695. }
  696. pwallet->UpdateTimeFirstKey(timestamp);
  697. }
  698. }
  699. success = true;
  700. } else {
  701. // Import public keys.
  702. if (pubKeys.size() && keys.size() == 0) {
  703. const std::string& strPubKey = pubKeys[0].get_str();
  704. if (!IsHex(strPubKey)) {
  705. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
  706. }
  707. std::vector<unsigned char> vData(ParseHex(strPubKey));
  708. CPubKey pubKey(vData.begin(), vData.end());
  709. if (!pubKey.IsFullyValid()) {
  710. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
  711. }
  712. CBitcoinAddress pubKeyAddress = CBitcoinAddress(pubKey.GetID());
  713. // Consistency check.
  714. if (!isScript && !(pubKeyAddress.Get() == address.Get())) {
  715. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
  716. }
  717. // Consistency check.
  718. if (isScript) {
  719. CBitcoinAddress scriptAddress;
  720. CTxDestination destination;
  721. if (ExtractDestination(script, destination)) {
  722. scriptAddress = CBitcoinAddress(destination);
  723. if (!(scriptAddress.Get() == pubKeyAddress.Get())) {
  724. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
  725. }
  726. }
  727. }
  728. CScript pubKeyScript = GetScriptForDestination(pubKeyAddress.Get());
  729. if (::IsMine(*pwallet, pubKeyScript) == ISMINE_SPENDABLE) {
  730. throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
  731. }
  732. pwallet->MarkDirty();
  733. if (!pwallet->AddWatchOnly(pubKeyScript, timestamp)) {
  734. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
  735. }
  736. // add to address book or update label
  737. if (pubKeyAddress.IsValid()) {
  738. pwallet->SetAddressBook(pubKeyAddress.Get(), label, "receive");
  739. }
  740. // TODO Is this necessary?
  741. CScript scriptRawPubKey = GetScriptForRawPubKey(pubKey);
  742. if (::IsMine(*pwallet, scriptRawPubKey) == ISMINE_SPENDABLE) {
  743. throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
  744. }
  745. pwallet->MarkDirty();
  746. if (!pwallet->AddWatchOnly(scriptRawPubKey, timestamp)) {
  747. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
  748. }
  749. success = true;
  750. }
  751. // Import private keys.
  752. if (keys.size()) {
  753. const std::string& strPrivkey = keys[0].get_str();
  754. // Checks.
  755. CBitcoinSecret vchSecret;
  756. bool fGood = vchSecret.SetString(strPrivkey);
  757. if (!fGood) {
  758. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
  759. }
  760. CKey key = vchSecret.GetKey();
  761. if (!key.IsValid()) {
  762. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
  763. }
  764. CPubKey pubKey = key.GetPubKey();
  765. assert(key.VerifyPubKey(pubKey));
  766. CBitcoinAddress pubKeyAddress = CBitcoinAddress(pubKey.GetID());
  767. // Consistency check.
  768. if (!isScript && !(pubKeyAddress.Get() == address.Get())) {
  769. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
  770. }
  771. // Consistency check.
  772. if (isScript) {
  773. CBitcoinAddress scriptAddress;
  774. CTxDestination destination;
  775. if (ExtractDestination(script, destination)) {
  776. scriptAddress = CBitcoinAddress(destination);
  777. if (!(scriptAddress.Get() == pubKeyAddress.Get())) {
  778. throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
  779. }
  780. }
  781. }
  782. CKeyID vchAddress = pubKey.GetID();
  783. pwallet->MarkDirty();
  784. pwallet->SetAddressBook(vchAddress, label, "receive");
  785. if (pwallet->HaveKey(vchAddress)) {
  786. throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
  787. }
  788. pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
  789. if (!pwallet->AddKeyPubKey(key, pubKey)) {
  790. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
  791. }
  792. pwallet->UpdateTimeFirstKey(timestamp);
  793. success = true;
  794. }
  795. // Import scriptPubKey only.
  796. if (pubKeys.size() == 0 && keys.size() == 0) {
  797. if (::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
  798. throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
  799. }
  800. pwallet->MarkDirty();
  801. if (!pwallet->AddWatchOnly(script, timestamp)) {
  802. throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
  803. }
  804. if (scriptPubKey.getType() == UniValue::VOBJ) {
  805. // add to address book or update label
  806. if (address.IsValid()) {
  807. pwallet->SetAddressBook(address.Get(), label, "receive");
  808. }
  809. }
  810. success = true;
  811. }
  812. }
  813. UniValue result = UniValue(UniValue::VOBJ);
  814. result.pushKV("success", UniValue(success));
  815. return result;
  816. } catch (const UniValue& e) {
  817. UniValue result = UniValue(UniValue::VOBJ);
  818. result.pushKV("success", UniValue(false));
  819. result.pushKV("error", e);
  820. return result;
  821. } catch (...) {
  822. UniValue result = UniValue(UniValue::VOBJ);
  823. result.pushKV("success", UniValue(false));
  824. result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields"));
  825. return result;
  826. }
  827. }
  828. int64_t GetImportTimestamp(const UniValue& data, int64_t now)
  829. {
  830. if (data.exists("timestamp")) {
  831. const UniValue& timestamp = data["timestamp"];
  832. if (timestamp.isNum()) {
  833. return timestamp.get_int64();
  834. } else if (timestamp.isStr() && timestamp.get_str() == "now") {
  835. return now;
  836. }
  837. throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
  838. }
  839. throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
  840. }
  841. UniValue importmulti(const JSONRPCRequest& mainRequest)
  842. {
  843. CWallet * const pwallet = GetWalletForJSONRPCRequest(mainRequest);
  844. if (!EnsureWalletIsAvailable(pwallet, mainRequest.fHelp)) {
  845. return NullUniValue;
  846. }
  847. // clang-format off
  848. if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2)
  849. throw std::runtime_error(
  850. "importmulti \"requests\" ( \"options\" )\n\n"
  851. "Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options). Requires a new wallet backup.\n\n"
  852. "Arguments:\n"
  853. "1. requests (array, required) Data to be imported\n"
  854. " [ (array of json objects)\n"
  855. " {\n"
  856. " \"scriptPubKey\": \"<script>\" | { \"address\":\"<address>\" }, (string / json, required) Type of scriptPubKey (string for script, json for address)\n"
  857. " \"timestamp\": timestamp | \"now\" , (integer / string, required) Creation time of the key in seconds since epoch (Jan 1 1970 GMT),\n"
  858. " or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n"
  859. " key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n"
  860. " \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n"
  861. " 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n"
  862. " creation time of all keys being imported by the importmulti call will be scanned.\n"
  863. " \"redeemscript\": \"<script>\" , (string, optional) Allowed only if the scriptPubKey is a P2SH address or a P2SH scriptPubKey\n"
  864. " \"pubkeys\": [\"<pubKey>\", ... ] , (array, optional) Array of strings giving pubkeys that must occur in the output or redeemscript\n"
  865. " \"keys\": [\"<key>\", ... ] , (array, optional) Array of strings giving private keys whose corresponding public keys must occur in the output or redeemscript\n"
  866. " \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be treated as not incoming payments\n"
  867. " \"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"
  868. " \"label\": <label> , (string, optional, default: '') Label to assign to the address (aka account name, for now), only allowed with internal=false\n"
  869. " }\n"
  870. " ,...\n"
  871. " ]\n"
  872. "2. options (json, optional)\n"
  873. " {\n"
  874. " \"rescan\": <false>, (boolean, optional, default: true) Stating if should rescan the blockchain after all imports\n"
  875. " }\n"
  876. "\nExamples:\n" +
  877. HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, "
  878. "{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
  879. HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") +
  880. "\nResponse is an array with the same size as the input that has the execution result :\n"
  881. " [{ \"success\": true } , { \"success\": false, \"error\": { \"code\": -1, \"message\": \"Internal Server Error\"} }, ... ]\n");
  882. // clang-format on
  883. RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ});
  884. const UniValue& requests = mainRequest.params[0];
  885. //Default options
  886. bool fRescan = true;
  887. if (!mainRequest.params[1].isNull()) {
  888. const UniValue& options = mainRequest.params[1];
  889. if (options.exists("rescan")) {
  890. fRescan = options["rescan"].get_bool();
  891. }
  892. }
  893. LOCK2(cs_main, pwallet->cs_wallet);
  894. EnsureWalletIsUnlocked(pwallet);
  895. // Verify all timestamps are present before importing any keys.
  896. const int64_t now = chainActive.Tip() ? chainActive.Tip()->GetMedianTimePast() : 0;
  897. for (const UniValue& data : requests.getValues()) {
  898. GetImportTimestamp(data, now);
  899. }
  900. bool fRunScan = false;
  901. const int64_t minimumTimestamp = 1;
  902. int64_t nLowestTimestamp = 0;
  903. if (fRescan && chainActive.Tip()) {
  904. nLowestTimestamp = chainActive.Tip()->GetBlockTime();
  905. } else {
  906. fRescan = false;
  907. }
  908. UniValue response(UniValue::VARR);
  909. for (const UniValue& data : requests.getValues()) {
  910. const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);
  911. const UniValue result = ProcessImport(pwallet, data, timestamp);
  912. response.push_back(result);
  913. if (!fRescan) {
  914. continue;
  915. }
  916. // If at least one request was successful then allow rescan.
  917. if (result["success"].get_bool()) {
  918. fRunScan = true;
  919. }
  920. // Get the lowest timestamp.
  921. if (timestamp < nLowestTimestamp) {
  922. nLowestTimestamp = timestamp;
  923. }
  924. }
  925. if (fRescan && fRunScan && requests.size()) {
  926. int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, true /* update */);
  927. pwallet->ReacceptWalletTransactions();
  928. if (scannedTime > nLowestTimestamp) {
  929. std::vector<UniValue> results = response.getValues();
  930. response.clear();
  931. response.setArray();
  932. size_t i = 0;
  933. for (const UniValue& request : requests.getValues()) {
  934. // If key creation date is within the successfully scanned
  935. // range, or if the import result already has an error set, let
  936. // the result stand unmodified. Otherwise replace the result
  937. // with an error message.
  938. if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists("error")) {
  939. response.push_back(results.at(i));
  940. } else {
  941. UniValue result = UniValue(UniValue::VOBJ);
  942. result.pushKV("success", UniValue(false));
  943. result.pushKV(
  944. "error",
  945. JSONRPCError(
  946. RPC_MISC_ERROR,
  947. strprintf("Rescan failed for key with creation timestamp %d. There was an error reading a "
  948. "block from time %d, which is after or within %d seconds of key creation, and "
  949. "could contain transactions pertaining to the key. As a result, transactions "
  950. "and coins using this key may not appear in the wallet. This error could be "
  951. "caused by pruning or data corruption (see bitcoind log for details) and could "
  952. "be dealt with by downloading and rescanning the relevant blocks (see -reindex "
  953. "and -rescan options).",
  954. GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));
  955. response.push_back(std::move(result));
  956. }
  957. ++i;
  958. }
  959. }
  960. }
  961. return response;
  962. }