BSHA3  0.17.99
P2P Blockchain, based on Bitcoin
rpcwallet.cpp
Go to the documentation of this file.
1 // Copyright (c) 2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #include <amount.h>
7 #include <chain.h>
8 #include <consensus/validation.h>
9 #include <core_io.h>
10 #include <httpserver.h>
11 #include <validation.h>
12 #include <key_io.h>
13 #include <net.h>
14 #include <outputtype.h>
15 #include <policy/feerate.h>
16 #include <policy/fees.h>
17 #include <policy/policy.h>
18 #include <policy/rbf.h>
19 #include <rpc/mining.h>
20 #include <rpc/rawtransaction.h>
21 #include <rpc/server.h>
22 #include <rpc/util.h>
23 #include <script/sign.h>
24 #include <shutdown.h>
25 #include <timedata.h>
26 #include <util.h>
27 #include <utilmoneystr.h>
28 #include <wallet/coincontrol.h>
29 #include <wallet/feebumper.h>
30 #include <wallet/rpcwallet.h>
31 #include <wallet/wallet.h>
32 #include <wallet/walletdb.h>
33 #include <wallet/walletutil.h>
34 
35 #include <stdint.h>
36 
37 #include <univalue.h>
38 
39 #include <functional>
40 
41 static const std::string WALLET_ENDPOINT_BASE = "/wallet/";
42 
43 bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest& request, std::string& wallet_name)
44 {
45  if (request.URI.substr(0, WALLET_ENDPOINT_BASE.size()) == WALLET_ENDPOINT_BASE) {
46  // wallet endpoint was used
47  wallet_name = urlDecode(request.URI.substr(WALLET_ENDPOINT_BASE.size()));
48  return true;
49  }
50  return false;
51 }
52 
53 std::shared_ptr<CWallet> GetWalletForJSONRPCRequest(const JSONRPCRequest& request)
54 {
55  std::string wallet_name;
56  if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
57  std::shared_ptr<CWallet> pwallet = GetWallet(wallet_name);
58  if (!pwallet) throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded");
59  return pwallet;
60  }
61 
62  std::vector<std::shared_ptr<CWallet>> wallets = GetWallets();
63  return wallets.size() == 1 || (request.fHelp && wallets.size() > 0) ? wallets[0] : nullptr;
64 }
65 
66 std::string HelpRequiringPassphrase(CWallet * const pwallet)
67 {
68  return pwallet && pwallet->IsCrypted()
69  ? "\nRequires wallet passphrase to be set with walletpassphrase call."
70  : "";
71 }
72 
73 bool EnsureWalletIsAvailable(CWallet * const pwallet, bool avoidException)
74 {
75  if (pwallet) return true;
76  if (avoidException) return false;
77  if (!HasWallets()) {
78  throw JSONRPCError(
79  RPC_METHOD_NOT_FOUND, "Method not found (wallet method is disabled because no wallet is loaded)");
80  }
82  "Wallet file not specified (must request wallet RPC through /wallet/<filename> uri-path).");
83 }
84 
85 void EnsureWalletIsUnlocked(CWallet * const pwallet)
86 {
87  if (pwallet->IsLocked()) {
88  throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
89  }
90 }
91 
92 static void WalletTxToJSON(const CWalletTx& wtx, UniValue& entry) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
93 {
94  int confirms = wtx.GetDepthInMainChain();
95  entry.pushKV("confirmations", confirms);
96  if (wtx.IsCoinBase())
97  entry.pushKV("generated", true);
98  if (confirms > 0)
99  {
100  entry.pushKV("blockhash", wtx.hashBlock.GetHex());
101  entry.pushKV("blockindex", wtx.nIndex);
102  entry.pushKV("blocktime", LookupBlockIndex(wtx.hashBlock)->GetBlockTime());
103  } else {
104  entry.pushKV("trusted", wtx.IsTrusted());
105  }
106  uint256 hash = wtx.GetHash();
107  entry.pushKV("txid", hash.GetHex());
108  UniValue conflicts(UniValue::VARR);
109  for (const uint256& conflict : wtx.GetConflicts())
110  conflicts.push_back(conflict.GetHex());
111  entry.pushKV("walletconflicts", conflicts);
112  entry.pushKV("time", wtx.GetTxTime());
113  entry.pushKV("timereceived", (int64_t)wtx.nTimeReceived);
114 
115  // Add opt-in RBF status
116  std::string rbfStatus = "no";
117  if (confirms <= 0) {
118  LOCK(mempool.cs);
119  RBFTransactionState rbfState = IsRBFOptIn(*wtx.tx, mempool);
120  if (rbfState == RBFTransactionState::UNKNOWN)
121  rbfStatus = "unknown";
122  else if (rbfState == RBFTransactionState::REPLACEABLE_BIP125)
123  rbfStatus = "yes";
124  }
125  entry.pushKV("bip125-replaceable", rbfStatus);
126 
127  for (const std::pair<const std::string, std::string>& item : wtx.mapValue)
128  entry.pushKV(item.first, item.second);
129 }
130 
131 static std::string LabelFromValue(const UniValue& value)
132 {
133  std::string label = value.get_str();
134  if (label == "*")
135  throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, "Invalid label name");
136  return label;
137 }
138 
139 static UniValue getnewaddress(const JSONRPCRequest& request)
140 {
141  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
142  CWallet* const pwallet = wallet.get();
143 
144  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
145  return NullUniValue;
146  }
147 
148  if (request.fHelp || request.params.size() > 2)
149  throw std::runtime_error(
150  "getnewaddress ( \"label\" \"address_type\" )\n"
151  "\nReturns a new BSHA3 address for receiving payments.\n"
152  "If 'label' is specified, it is added to the address book \n"
153  "so payments received with the address will be associated with 'label'.\n"
154  "\nArguments:\n"
155  "1. \"label\" (string, optional) The label name for the address to be linked to. If not provided, the default label \"\" is used. It can also be set to the empty string \"\" to represent the default label. The label does not need to exist, it will be created if there is no label by the given name.\n"
156  "2. \"address_type\" (string, optional) The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -addresstype.\n"
157  "\nResult:\n"
158  "\"address\" (string) The new bitcoin address\n"
159  "\nExamples:\n"
160  + HelpExampleCli("getnewaddress", "")
161  + HelpExampleRpc("getnewaddress", "")
162  );
163 
165  throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
166  }
167 
168  LOCK(pwallet->cs_wallet);
169 
170  // Parse the label first so we don't generate a key if there's an error
171  std::string label;
172  if (!request.params[0].isNull())
173  label = LabelFromValue(request.params[0]);
174 
175  OutputType output_type = pwallet->m_default_address_type;
176  if (!request.params[1].isNull()) {
177  if (!ParseOutputType(request.params[1].get_str(), output_type)) {
178  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[1].get_str()));
179  }
180  }
181 
182  if (!pwallet->IsLocked()) {
183  pwallet->TopUpKeyPool();
184  }
185 
186  // Generate a new key that is added to wallet
187  CPubKey newKey;
188  if (!pwallet->GetKeyFromPool(newKey)) {
189  throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
190  }
191  pwallet->LearnRelatedScripts(newKey, output_type);
192  CTxDestination dest = GetDestinationForKey(newKey, output_type);
193 
194  pwallet->SetAddressBook(dest, label, "receive");
195 
196  return EncodeDestination(dest);
197 }
198 
199 static UniValue getrawchangeaddress(const JSONRPCRequest& request)
200 {
201  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
202  CWallet* const pwallet = wallet.get();
203 
204  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
205  return NullUniValue;
206  }
207 
208  if (request.fHelp || request.params.size() > 1)
209  throw std::runtime_error(
210  "getrawchangeaddress ( \"address_type\" )\n"
211  "\nReturns a new BSHA3 address, for receiving change.\n"
212  "This is for use with raw transactions, NOT normal use.\n"
213  "\nArguments:\n"
214  "1. \"address_type\" (string, optional) The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -changetype.\n"
215  "\nResult:\n"
216  "\"address\" (string) The address\n"
217  "\nExamples:\n"
218  + HelpExampleCli("getrawchangeaddress", "")
219  + HelpExampleRpc("getrawchangeaddress", "")
220  );
221 
223  throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
224  }
225 
226  LOCK(pwallet->cs_wallet);
227 
228  if (!pwallet->IsLocked()) {
229  pwallet->TopUpKeyPool();
230  }
231 
233  if (!request.params[0].isNull()) {
234  if (!ParseOutputType(request.params[0].get_str(), output_type)) {
235  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[0].get_str()));
236  }
237  }
238 
239  CReserveKey reservekey(pwallet);
240  CPubKey vchPubKey;
241  if (!reservekey.GetReservedKey(vchPubKey, true))
242  throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
243 
244  reservekey.KeepKey();
245 
246  pwallet->LearnRelatedScripts(vchPubKey, output_type);
247  CTxDestination dest = GetDestinationForKey(vchPubKey, output_type);
248 
249  return EncodeDestination(dest);
250 }
251 
252 
253 static UniValue setlabel(const JSONRPCRequest& request)
254 {
255  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
256  CWallet* const pwallet = wallet.get();
257 
258  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
259  return NullUniValue;
260  }
261 
262  if (request.fHelp || request.params.size() != 2)
263  throw std::runtime_error(
264  "setlabel \"address\" \"label\"\n"
265  "\nSets the label associated with the given address.\n"
266  "\nArguments:\n"
267  "1. \"address\" (string, required) The bitcoin address to be associated with a label.\n"
268  "2. \"label\" (string, required) The label to assign to the address.\n"
269  "\nExamples:\n"
270  + HelpExampleCli("setlabel", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"tabby\"")
271  + HelpExampleRpc("setlabel", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"tabby\"")
272  );
273 
274  LOCK(pwallet->cs_wallet);
275 
276  CTxDestination dest = DecodeDestination(request.params[0].get_str());
277  if (!IsValidDestination(dest)) {
278  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BSHA3 address");
279  }
280 
281  std::string label = LabelFromValue(request.params[1]);
282 
283  if (IsMine(*pwallet, dest)) {
284  pwallet->SetAddressBook(dest, label, "receive");
285  } else {
286  pwallet->SetAddressBook(dest, label, "send");
287  }
288 
289  return NullUniValue;
290 }
291 
292 
293 static CTransactionRef SendMoney(CWallet * const pwallet, const CTxDestination &address, CAmount nValue, bool fSubtractFeeFromAmount, const CCoinControl& coin_control, mapValue_t mapValue)
294 {
295  CAmount curBalance = pwallet->GetBalance();
296 
297  // Check amount
298  if (nValue <= 0)
299  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount");
300 
301  if (nValue > curBalance)
302  throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds");
303 
304  if (pwallet->GetBroadcastTransactions() && !g_connman) {
305  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
306  }
307 
308  // Parse BSHA3 address
309  CScript scriptPubKey = GetScriptForDestination(address);
310 
311  // Create and send the transaction
312  CReserveKey reservekey(pwallet);
313  CAmount nFeeRequired;
314  std::string strError;
315  std::vector<CRecipient> vecSend;
316  int nChangePosRet = -1;
317  CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount};
318  vecSend.push_back(recipient);
319  CTransactionRef tx;
320  if (!pwallet->CreateTransaction(vecSend, tx, reservekey, nFeeRequired, nChangePosRet, strError, coin_control)) {
321  if (!fSubtractFeeFromAmount && nValue + nFeeRequired > curBalance)
322  strError = strprintf("Error: This transaction requires a transaction fee of at least %s", FormatMoney(nFeeRequired));
323  throw JSONRPCError(RPC_WALLET_ERROR, strError);
324  }
325  CValidationState state;
326  if (!pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */, reservekey, g_connman.get(), state)) {
327  strError = strprintf("Error: The transaction was rejected! Reason given: %s", FormatStateMessage(state));
328  throw JSONRPCError(RPC_WALLET_ERROR, strError);
329  }
330  return tx;
331 }
332 
333 static UniValue sendtoaddress(const JSONRPCRequest& request)
334 {
335  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
336  CWallet* const pwallet = wallet.get();
337 
338  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
339  return NullUniValue;
340  }
341 
342  if (request.fHelp || request.params.size() < 2 || request.params.size() > 8)
343  throw std::runtime_error(
344  "sendtoaddress \"address\" amount ( \"comment\" \"comment_to\" subtractfeefromamount replaceable conf_target \"estimate_mode\")\n"
345  "\nSend an amount to a given address.\n"
346  + HelpRequiringPassphrase(pwallet) +
347  "\nArguments:\n"
348  "1. \"address\" (string, required) The bitcoin address to send to.\n"
349  "2. \"amount\" (numeric or string, required) The amount in " + CURRENCY_UNIT + " to send. eg 0.1\n"
350  "3. \"comment\" (string, optional) A comment used to store what the transaction is for. \n"
351  " This is not part of the transaction, just kept in your wallet.\n"
352  "4. \"comment_to\" (string, optional) A comment to store the name of the person or organization \n"
353  " to which you're sending the transaction. This is not part of the \n"
354  " transaction, just kept in your wallet.\n"
355  "5. subtractfeefromamount (boolean, optional, default=false) The fee will be deducted from the amount being sent.\n"
356  " The recipient will receive less bitcoins than you enter in the amount field.\n"
357  "6. replaceable (boolean, optional) Allow this transaction to be replaced by a transaction with higher fees via BIP 125\n"
358  "7. conf_target (numeric, optional) Confirmation target (in blocks)\n"
359  "8. \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
360  " \"UNSET\"\n"
361  " \"ECONOMICAL\"\n"
362  " \"CONSERVATIVE\"\n"
363  "\nResult:\n"
364  "\"txid\" (string) The transaction id.\n"
365  "\nExamples:\n"
366  + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1")
367  + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1 \"donation\" \"seans outpost\"")
368  + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 0.1 \"\" \"\" true")
369  + HelpExampleRpc("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\", 0.1, \"donation\", \"seans outpost\"")
370  );
371 
372  // Make sure the results are valid at least up to the most recent block
373  // the user could have gotten from another RPC command prior to now
375 
376  LOCK2(cs_main, pwallet->cs_wallet);
377 
378  CTxDestination dest = DecodeDestination(request.params[0].get_str());
379  if (!IsValidDestination(dest)) {
380  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
381  }
382 
383  // Amount
384  CAmount nAmount = AmountFromValue(request.params[1]);
385  if (nAmount <= 0)
386  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
387 
388  // Wallet comments
389  mapValue_t mapValue;
390  if (!request.params[2].isNull() && !request.params[2].get_str().empty())
391  mapValue["comment"] = request.params[2].get_str();
392  if (!request.params[3].isNull() && !request.params[3].get_str().empty())
393  mapValue["to"] = request.params[3].get_str();
394 
395  bool fSubtractFeeFromAmount = false;
396  if (!request.params[4].isNull()) {
397  fSubtractFeeFromAmount = request.params[4].get_bool();
398  }
399 
400  CCoinControl coin_control;
401  if (!request.params[5].isNull()) {
402  coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
403  }
404 
405  if (!request.params[6].isNull()) {
406  coin_control.m_confirm_target = ParseConfirmTarget(request.params[6]);
407  }
408 
409  if (!request.params[7].isNull()) {
410  if (!FeeModeFromString(request.params[7].get_str(), coin_control.m_fee_mode)) {
411  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
412  }
413  }
414 
415 
416  EnsureWalletIsUnlocked(pwallet);
417 
418  CTransactionRef tx = SendMoney(pwallet, dest, nAmount, fSubtractFeeFromAmount, coin_control, std::move(mapValue));
419  return tx->GetHash().GetHex();
420 }
421 
422 static UniValue listaddressgroupings(const JSONRPCRequest& request)
423 {
424  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
425  CWallet* const pwallet = wallet.get();
426 
427  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
428  return NullUniValue;
429  }
430 
431  if (request.fHelp || request.params.size() != 0)
432  throw std::runtime_error(
433  "listaddressgroupings\n"
434  "\nLists groups of addresses which have had their common ownership\n"
435  "made public by common use as inputs or as the resulting change\n"
436  "in past transactions\n"
437  "\nResult:\n"
438  "[\n"
439  " [\n"
440  " [\n"
441  " \"address\", (string) The bitcoin address\n"
442  " amount, (numeric) The amount in " + CURRENCY_UNIT + "\n"
443  " \"label\" (string, optional) The label\n"
444  " ]\n"
445  " ,...\n"
446  " ]\n"
447  " ,...\n"
448  "]\n"
449  "\nExamples:\n"
450  + HelpExampleCli("listaddressgroupings", "")
451  + HelpExampleRpc("listaddressgroupings", "")
452  );
453 
454  // Make sure the results are valid at least up to the most recent block
455  // the user could have gotten from another RPC command prior to now
457 
458  LOCK2(cs_main, pwallet->cs_wallet);
459 
460  UniValue jsonGroupings(UniValue::VARR);
461  std::map<CTxDestination, CAmount> balances = pwallet->GetAddressBalances();
462  for (const std::set<CTxDestination>& grouping : pwallet->GetAddressGroupings()) {
463  UniValue jsonGrouping(UniValue::VARR);
464  for (const CTxDestination& address : grouping)
465  {
466  UniValue addressInfo(UniValue::VARR);
467  addressInfo.push_back(EncodeDestination(address));
468  addressInfo.push_back(ValueFromAmount(balances[address]));
469  {
470  if (pwallet->mapAddressBook.find(address) != pwallet->mapAddressBook.end()) {
471  addressInfo.push_back(pwallet->mapAddressBook.find(address)->second.name);
472  }
473  }
474  jsonGrouping.push_back(addressInfo);
475  }
476  jsonGroupings.push_back(jsonGrouping);
477  }
478  return jsonGroupings;
479 }
480 
481 static UniValue signmessage(const JSONRPCRequest& request)
482 {
483  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
484  CWallet* const pwallet = wallet.get();
485 
486  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
487  return NullUniValue;
488  }
489 
490  if (request.fHelp || request.params.size() != 2)
491  throw std::runtime_error(
492  "signmessage \"address\" \"message\"\n"
493  "\nSign a message with the private key of an address"
494  + HelpRequiringPassphrase(pwallet) + "\n"
495  "\nArguments:\n"
496  "1. \"address\" (string, required) The bitcoin address to use for the private key.\n"
497  "2. \"message\" (string, required) The message to create a signature of.\n"
498  "\nResult:\n"
499  "\"signature\" (string) The signature of the message encoded in base 64\n"
500  "\nExamples:\n"
501  "\nUnlock the wallet for 30 seconds\n"
502  + HelpExampleCli("walletpassphrase", "\"mypassphrase\" 30") +
503  "\nCreate the signature\n"
504  + HelpExampleCli("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"my message\"") +
505  "\nVerify the signature\n"
506  + HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
507  "\nAs a JSON-RPC call\n"
508  + HelpExampleRpc("signmessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", \"my message\"")
509  );
510 
511  LOCK2(cs_main, pwallet->cs_wallet);
512 
513  EnsureWalletIsUnlocked(pwallet);
514 
515  std::string strAddress = request.params[0].get_str();
516  std::string strMessage = request.params[1].get_str();
517 
518  CTxDestination dest = DecodeDestination(strAddress);
519  if (!IsValidDestination(dest)) {
520  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid address");
521  }
522 
523  const CKeyID *keyID = boost::get<CKeyID>(&dest);
524  if (!keyID) {
525  throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to key");
526  }
527 
528  CKey key;
529  if (!pwallet->GetKey(*keyID, key)) {
530  throw JSONRPCError(RPC_WALLET_ERROR, "Private key not available");
531  }
532 
533  CHashWriter ss(SER_GETHASH, 0);
534  ss << strMessageMagic;
535  ss << strMessage;
536 
537  std::vector<unsigned char> vchSig;
538  if (!key.SignCompact(ss.GetHash(), vchSig))
539  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
540 
541  return EncodeBase64(vchSig.data(), vchSig.size());
542 }
543 
544 static UniValue getreceivedbyaddress(const JSONRPCRequest& request)
545 {
546  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
547  CWallet* const pwallet = wallet.get();
548 
549  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
550  return NullUniValue;
551  }
552 
553  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
554  throw std::runtime_error(
555  "getreceivedbyaddress \"address\" ( minconf )\n"
556  "\nReturns the total amount received by the given address in transactions with at least minconf confirmations.\n"
557  "\nArguments:\n"
558  "1. \"address\" (string, required) The bitcoin address for transactions.\n"
559  "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
560  "\nResult:\n"
561  "amount (numeric) The total amount in " + CURRENCY_UNIT + " received at this address.\n"
562  "\nExamples:\n"
563  "\nThe amount from transactions with at least 1 confirmation\n"
564  + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\"") +
565  "\nThe amount including unconfirmed transactions, zero confirmations\n"
566  + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" 0") +
567  "\nThe amount with at least 6 confirmations\n"
568  + HelpExampleCli("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" 6") +
569  "\nAs a JSON-RPC call\n"
570  + HelpExampleRpc("getreceivedbyaddress", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\", 6")
571  );
572 
573  // Make sure the results are valid at least up to the most recent block
574  // the user could have gotten from another RPC command prior to now
576 
577  LOCK2(cs_main, pwallet->cs_wallet);
578 
579  // BSHA3 address
580  CTxDestination dest = DecodeDestination(request.params[0].get_str());
581  if (!IsValidDestination(dest)) {
582  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid BSHA3 address");
583  }
584  CScript scriptPubKey = GetScriptForDestination(dest);
585  if (!IsMine(*pwallet, scriptPubKey)) {
586  throw JSONRPCError(RPC_WALLET_ERROR, "Address not found in wallet");
587  }
588 
589  // Minimum confirmations
590  int nMinDepth = 1;
591  if (!request.params[1].isNull())
592  nMinDepth = request.params[1].get_int();
593 
594  // Tally
595  CAmount nAmount = 0;
596  for (const std::pair<const uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
597  const CWalletTx& wtx = pairWtx.second;
598  if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
599  continue;
600 
601  for (const CTxOut& txout : wtx.tx->vout)
602  if (txout.scriptPubKey == scriptPubKey)
603  if (wtx.GetDepthInMainChain() >= nMinDepth)
604  nAmount += txout.nValue;
605  }
606 
607  return ValueFromAmount(nAmount);
608 }
609 
610 
611 static UniValue getreceivedbylabel(const JSONRPCRequest& request)
612 {
613  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
614  CWallet* const pwallet = wallet.get();
615 
616  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
617  return NullUniValue;
618  }
619 
620  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
621  throw std::runtime_error(
622  "getreceivedbylabel \"label\" ( minconf )\n"
623  "\nReturns the total amount received by addresses with <label> in transactions with at least [minconf] confirmations.\n"
624  "\nArguments:\n"
625  "1. \"label\" (string, required) The selected label, may be the default label using \"\".\n"
626  "2. minconf (numeric, optional, default=1) Only include transactions confirmed at least this many times.\n"
627  "\nResult:\n"
628  "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this label.\n"
629  "\nExamples:\n"
630  "\nAmount received by the default label with at least 1 confirmation\n"
631  + HelpExampleCli("getreceivedbylabel", "\"\"") +
632  "\nAmount received at the tabby label including unconfirmed amounts with zero confirmations\n"
633  + HelpExampleCli("getreceivedbylabel", "\"tabby\" 0") +
634  "\nThe amount with at least 6 confirmations\n"
635  + HelpExampleCli("getreceivedbylabel", "\"tabby\" 6") +
636  "\nAs a JSON-RPC call\n"
637  + HelpExampleRpc("getreceivedbylabel", "\"tabby\", 6")
638  );
639 
640  // Make sure the results are valid at least up to the most recent block
641  // the user could have gotten from another RPC command prior to now
643 
644  LOCK2(cs_main, pwallet->cs_wallet);
645 
646  // Minimum confirmations
647  int nMinDepth = 1;
648  if (!request.params[1].isNull())
649  nMinDepth = request.params[1].get_int();
650 
651  // Get the set of pub keys assigned to label
652  std::string label = LabelFromValue(request.params[0]);
653  std::set<CTxDestination> setAddress = pwallet->GetLabelAddresses(label);
654 
655  // Tally
656  CAmount nAmount = 0;
657  for (const std::pair<const uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
658  const CWalletTx& wtx = pairWtx.second;
659  if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
660  continue;
661 
662  for (const CTxOut& txout : wtx.tx->vout)
663  {
664  CTxDestination address;
665  if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*pwallet, address) && setAddress.count(address)) {
666  if (wtx.GetDepthInMainChain() >= nMinDepth)
667  nAmount += txout.nValue;
668  }
669  }
670  }
671 
672  return ValueFromAmount(nAmount);
673 }
674 
675 
676 static UniValue getbalance(const JSONRPCRequest& request)
677 {
678  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
679  CWallet* const pwallet = wallet.get();
680 
681  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
682  return NullUniValue;
683  }
684 
685  if (request.fHelp || (request.params.size() > 3 ))
686  throw std::runtime_error(
687  "getbalance ( \"(dummy)\" minconf include_watchonly )\n"
688  "\nReturns the total available balance.\n"
689  "The available balance is what the wallet considers currently spendable, and is\n"
690  "thus affected by options which limit spendability such as -spendzeroconfchange.\n"
691  "\nArguments:\n"
692  "1. (dummy) (string, optional) Remains for backward compatibility. Must be excluded or set to \"*\".\n"
693  "2. minconf (numeric, optional, default=0) Only include transactions confirmed at least this many times.\n"
694  "3. include_watchonly (bool, optional, default=false) Also include balance in watch-only addresses (see 'importaddress')\n"
695  "\nResult:\n"
696  "amount (numeric) The total amount in " + CURRENCY_UNIT + " received for this wallet.\n"
697  "\nExamples:\n"
698  "\nThe total amount in the wallet with 1 or more confirmations\n"
699  + HelpExampleCli("getbalance", "") +
700  "\nThe total amount in the wallet at least 6 blocks confirmed\n"
701  + HelpExampleCli("getbalance", "\"*\" 6") +
702  "\nAs a JSON-RPC call\n"
703  + HelpExampleRpc("getbalance", "\"*\", 6")
704  );
705 
706  // Make sure the results are valid at least up to the most recent block
707  // the user could have gotten from another RPC command prior to now
709 
710  LOCK2(cs_main, pwallet->cs_wallet);
711 
712  const UniValue& dummy_value = request.params[0];
713  if (!dummy_value.isNull() && dummy_value.get_str() != "*") {
714  throw JSONRPCError(RPC_METHOD_DEPRECATED, "dummy first argument must be excluded or set to \"*\".");
715  }
716 
717  int min_depth = 0;
718  if (!request.params[1].isNull()) {
719  min_depth = request.params[1].get_int();
720  }
721 
723  if (!request.params[2].isNull() && request.params[2].get_bool()) {
725  }
726 
727  return ValueFromAmount(pwallet->GetBalance(filter, min_depth));
728 }
729 
730 static UniValue getunconfirmedbalance(const JSONRPCRequest &request)
731 {
732  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
733  CWallet* const pwallet = wallet.get();
734 
735  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
736  return NullUniValue;
737  }
738 
739  if (request.fHelp || request.params.size() > 0)
740  throw std::runtime_error(
741  "getunconfirmedbalance\n"
742  "Returns the server's total unconfirmed balance\n");
743 
744  // Make sure the results are valid at least up to the most recent block
745  // the user could have gotten from another RPC command prior to now
747 
748  LOCK2(cs_main, pwallet->cs_wallet);
749 
750  return ValueFromAmount(pwallet->GetUnconfirmedBalance());
751 }
752 
753 
754 static UniValue sendmany(const JSONRPCRequest& request)
755 {
756  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
757  CWallet* const pwallet = wallet.get();
758 
759  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
760  return NullUniValue;
761  }
762 
763  if (request.fHelp || request.params.size() < 2 || request.params.size() > 8)
764  throw std::runtime_error(
765  "sendmany \"\" {\"address\":amount,...} ( minconf \"comment\" [\"address\",...] replaceable conf_target \"estimate_mode\")\n"
766  "\nSend multiple times. Amounts are double-precision floating point numbers.\n"
767  + HelpRequiringPassphrase(pwallet) + "\n"
768  "\nArguments:\n"
769  "1. \"dummy\" (string, required) Must be set to \"\" for backwards compatibility.\n"
770  "2. \"amounts\" (string, required) A json object with addresses and amounts\n"
771  " {\n"
772  " \"address\":amount (numeric or string) The bitcoin address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value\n"
773  " ,...\n"
774  " }\n"
775  "3. minconf (numeric, optional, default=1) Only use the balance confirmed at least this many times.\n"
776  "4. \"comment\" (string, optional) A comment\n"
777  "5. subtractfeefrom (array, optional) A json array with addresses.\n"
778  " The fee will be equally deducted from the amount of each selected address.\n"
779  " Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
780  " If no addresses are specified here, the sender pays the fee.\n"
781  " [\n"
782  " \"address\" (string) Subtract fee from this address\n"
783  " ,...\n"
784  " ]\n"
785  "6. replaceable (boolean, optional) Allow this transaction to be replaced by a transaction with higher fees via BIP 125\n"
786  "7. conf_target (numeric, optional) Confirmation target (in blocks)\n"
787  "8. \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
788  " \"UNSET\"\n"
789  " \"ECONOMICAL\"\n"
790  " \"CONSERVATIVE\"\n"
791  "\nResult:\n"
792  "\"txid\" (string) The transaction id for the send. Only 1 transaction is created regardless of \n"
793  " the number of addresses.\n"
794  "\nExamples:\n"
795  "\nSend two amounts to two different addresses:\n"
796  + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\"") +
797  "\nSend two amounts to two different addresses setting the confirmation and comment:\n"
798  + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 6 \"testing\"") +
799  "\nSend two amounts to two different addresses, subtract fee from amount:\n"
800  + HelpExampleCli("sendmany", "\"\" \"{\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\":0.01,\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\":0.02}\" 1 \"\" \"[\\\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\\\",\\\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\\\"]\"") +
801  "\nAs a JSON-RPC call\n"
802  + HelpExampleRpc("sendmany", "\"\", {\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\":0.01,\"1353tsE8YMTA4EuV7dgUXGjNFf9KpVvKHz\":0.02}, 6, \"testing\"")
803  );
804 
805  // Make sure the results are valid at least up to the most recent block
806  // the user could have gotten from another RPC command prior to now
808 
809  LOCK2(cs_main, pwallet->cs_wallet);
810 
811  if (pwallet->GetBroadcastTransactions() && !g_connman) {
812  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
813  }
814 
815  if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
816  throw JSONRPCError(RPC_INVALID_PARAMETER, "Dummy value must be set to \"\"");
817  }
818  UniValue sendTo = request.params[1].get_obj();
819  int nMinDepth = 1;
820  if (!request.params[2].isNull())
821  nMinDepth = request.params[2].get_int();
822 
823  mapValue_t mapValue;
824  if (!request.params[3].isNull() && !request.params[3].get_str().empty())
825  mapValue["comment"] = request.params[3].get_str();
826 
827  UniValue subtractFeeFromAmount(UniValue::VARR);
828  if (!request.params[4].isNull())
829  subtractFeeFromAmount = request.params[4].get_array();
830 
831  CCoinControl coin_control;
832  if (!request.params[5].isNull()) {
833  coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
834  }
835 
836  if (!request.params[6].isNull()) {
837  coin_control.m_confirm_target = ParseConfirmTarget(request.params[6]);
838  }
839 
840  if (!request.params[7].isNull()) {
841  if (!FeeModeFromString(request.params[7].get_str(), coin_control.m_fee_mode)) {
842  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
843  }
844  }
845 
846  std::set<CTxDestination> destinations;
847  std::vector<CRecipient> vecSend;
848 
849  CAmount totalAmount = 0;
850  std::vector<std::string> keys = sendTo.getKeys();
851  for (const std::string& name_ : keys) {
852  CTxDestination dest = DecodeDestination(name_);
853  if (!IsValidDestination(dest)) {
854  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid BSHA3 address: ") + name_);
855  }
856 
857  if (destinations.count(dest)) {
858  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
859  }
860  destinations.insert(dest);
861 
862  CScript scriptPubKey = GetScriptForDestination(dest);
863  CAmount nAmount = AmountFromValue(sendTo[name_]);
864  if (nAmount <= 0)
865  throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount for send");
866  totalAmount += nAmount;
867 
868  bool fSubtractFeeFromAmount = false;
869  for (unsigned int idx = 0; idx < subtractFeeFromAmount.size(); idx++) {
870  const UniValue& addr = subtractFeeFromAmount[idx];
871  if (addr.get_str() == name_)
872  fSubtractFeeFromAmount = true;
873  }
874 
875  CRecipient recipient = {scriptPubKey, nAmount, fSubtractFeeFromAmount};
876  vecSend.push_back(recipient);
877  }
878 
879  EnsureWalletIsUnlocked(pwallet);
880 
881  // Check funds
882  if (totalAmount > pwallet->GetLegacyBalance(ISMINE_SPENDABLE, nMinDepth)) {
883  throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Wallet has insufficient funds");
884  }
885 
886  // Shuffle recipient list
887  std::shuffle(vecSend.begin(), vecSend.end(), FastRandomContext());
888 
889  // Send
890  CReserveKey keyChange(pwallet);
891  CAmount nFeeRequired = 0;
892  int nChangePosRet = -1;
893  std::string strFailReason;
894  CTransactionRef tx;
895  bool fCreated = pwallet->CreateTransaction(vecSend, tx, keyChange, nFeeRequired, nChangePosRet, strFailReason, coin_control);
896  if (!fCreated)
897  throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, strFailReason);
898  CValidationState state;
899  if (!pwallet->CommitTransaction(tx, std::move(mapValue), {} /* orderForm */, keyChange, g_connman.get(), state)) {
900  strFailReason = strprintf("Transaction commit failed:: %s", FormatStateMessage(state));
901  throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
902  }
903 
904  return tx->GetHash().GetHex();
905 }
906 
907 static UniValue addmultisigaddress(const JSONRPCRequest& request)
908 {
909  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
910  CWallet* const pwallet = wallet.get();
911 
912  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
913  return NullUniValue;
914  }
915 
916  if (request.fHelp || request.params.size() < 2 || request.params.size() > 4) {
917  std::string msg = "addmultisigaddress nrequired [\"key\",...] ( \"label\" \"address_type\" )\n"
918  "\nAdd a nrequired-to-sign multisignature address to the wallet. Requires a new wallet backup.\n"
919  "Each key is a BSHA3 address or hex-encoded public key.\n"
920  "This functionality is only intended for use with non-watchonly addresses.\n"
921  "See `importaddress` for watchonly p2sh address support.\n"
922  "If 'label' is specified, assign address to that label.\n"
923 
924  "\nArguments:\n"
925  "1. nrequired (numeric, required) The number of required signatures out of the n keys or addresses.\n"
926  "2. \"keys\" (string, required) A json array of bitcoin addresses or hex-encoded public keys\n"
927  " [\n"
928  " \"address\" (string) bitcoin address or hex-encoded public key\n"
929  " ...,\n"
930  " ]\n"
931  "3. \"label\" (string, optional) A label to assign the addresses to.\n"
932  "4. \"address_type\" (string, optional) The address type to use. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -addresstype.\n"
933 
934  "\nResult:\n"
935  "{\n"
936  " \"address\":\"multisigaddress\", (string) The value of the new multisig address.\n"
937  " \"redeemScript\":\"script\" (string) The string value of the hex-encoded redemption script.\n"
938  "}\n"
939  "\nExamples:\n"
940  "\nAdd a multisig address from 2 addresses\n"
941  + HelpExampleCli("addmultisigaddress", "2 \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"") +
942  "\nAs a JSON-RPC call\n"
943  + HelpExampleRpc("addmultisigaddress", "2, \"[\\\"16sSauSf5pF2UkUwvKGq4qjNRzBZYqgEL5\\\",\\\"171sgjn4YtPu27adkKGrdDwzRTxnRkBfKV\\\"]\"")
944  ;
945  throw std::runtime_error(msg);
946  }
947 
948  LOCK2(cs_main, pwallet->cs_wallet);
949 
950  std::string label;
951  if (!request.params[2].isNull())
952  label = LabelFromValue(request.params[2]);
953 
954  int required = request.params[0].get_int();
955 
956  // Get the public keys
957  const UniValue& keys_or_addrs = request.params[1].get_array();
958  std::vector<CPubKey> pubkeys;
959  for (unsigned int i = 0; i < keys_or_addrs.size(); ++i) {
960  if (IsHex(keys_or_addrs[i].get_str()) && (keys_or_addrs[i].get_str().length() == 66 || keys_or_addrs[i].get_str().length() == 130)) {
961  pubkeys.push_back(HexToPubKey(keys_or_addrs[i].get_str()));
962  } else {
963  pubkeys.push_back(AddrToPubKey(pwallet, keys_or_addrs[i].get_str()));
964  }
965  }
966 
967  OutputType output_type = pwallet->m_default_address_type;
968  if (!request.params[3].isNull()) {
969  if (!ParseOutputType(request.params[3].get_str(), output_type)) {
970  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown address type '%s'", request.params[3].get_str()));
971  }
972  }
973 
974  // Construct using pay-to-script-hash:
975  CScript inner = CreateMultisigRedeemscript(required, pubkeys);
976  CTxDestination dest = AddAndGetDestinationForScript(*pwallet, inner, output_type);
977  pwallet->SetAddressBook(dest, label, "send");
978 
979  UniValue result(UniValue::VOBJ);
980  result.pushKV("address", EncodeDestination(dest));
981  result.pushKV("redeemScript", HexStr(inner.begin(), inner.end()));
982  return result;
983 }
984 
985 struct tallyitem
986 {
988  int nConf;
989  std::vector<uint256> txids;
992  {
993  nAmount = 0;
994  nConf = std::numeric_limits<int>::max();
995  fIsWatchonly = false;
996  }
997 };
998 
999 static UniValue ListReceived(CWallet * const pwallet, const UniValue& params, bool by_label) EXCLUSIVE_LOCKS_REQUIRED(cs_main, pwallet->cs_wallet)
1001  // Minimum confirmations
1002  int nMinDepth = 1;
1003  if (!params[0].isNull())
1004  nMinDepth = params[0].get_int();
1005 
1006  // Whether to include empty labels
1007  bool fIncludeEmpty = false;
1008  if (!params[1].isNull())
1009  fIncludeEmpty = params[1].get_bool();
1010 
1012  if(!params[2].isNull())
1013  if(params[2].get_bool())
1015 
1016  bool has_filtered_address = false;
1018  if (!by_label && params.size() > 3) {
1019  if (!IsValidDestinationString(params[3].get_str())) {
1020  throw JSONRPCError(RPC_WALLET_ERROR, "address_filter parameter was invalid");
1021  }
1022  filtered_address = DecodeDestination(params[3].get_str());
1023  has_filtered_address = true;
1024  }
1025 
1026  // Tally
1027  std::map<CTxDestination, tallyitem> mapTally;
1028  for (const std::pair<const uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
1029  const CWalletTx& wtx = pairWtx.second;
1030 
1031  if (wtx.IsCoinBase() || !CheckFinalTx(*wtx.tx))
1032  continue;
1033 
1034  int nDepth = wtx.GetDepthInMainChain();
1035  if (nDepth < nMinDepth)
1036  continue;
1037 
1038  for (const CTxOut& txout : wtx.tx->vout)
1039  {
1040  CTxDestination address;
1041  if (!ExtractDestination(txout.scriptPubKey, address))
1042  continue;
1043 
1044  if (has_filtered_address && !(filtered_address == address)) {
1045  continue;
1046  }
1047 
1048  isminefilter mine = IsMine(*pwallet, address);
1049  if(!(mine & filter))
1050  continue;
1051 
1052  tallyitem& item = mapTally[address];
1053  item.nAmount += txout.nValue;
1054  item.nConf = std::min(item.nConf, nDepth);
1055  item.txids.push_back(wtx.GetHash());
1056  if (mine & ISMINE_WATCH_ONLY)
1057  item.fIsWatchonly = true;
1058  }
1059  }
1060 
1061  // Reply
1063  std::map<std::string, tallyitem> label_tally;
1064 
1065  // Create mapAddressBook iterator
1066  // If we aren't filtering, go from begin() to end()
1067  auto start = pwallet->mapAddressBook.begin();
1068  auto end = pwallet->mapAddressBook.end();
1069  // If we are filtering, find() the applicable entry
1071  start = pwallet->mapAddressBook.find(filtered_address);
1072  if (start != end) {
1073  end = std::next(start);
1074  }
1075  }
1076 
1077  for (auto item_it = start; item_it != end; ++item_it)
1078  {
1079  const CTxDestination& address = item_it->first;
1080  const std::string& label = item_it->second.name;
1081  auto it = mapTally.find(address);
1082  if (it == mapTally.end() && !fIncludeEmpty)
1083  continue;
1084 
1085  CAmount nAmount = 0;
1086  int nConf = std::numeric_limits<int>::max();
1087  bool fIsWatchonly = false;
1088  if (it != mapTally.end())
1089  {
1090  nAmount = (*it).second.nAmount;
1091  nConf = (*it).second.nConf;
1092  fIsWatchonly = (*it).second.fIsWatchonly;
1093  }
1094 
1095  if (by_label)
1096  {
1097  tallyitem& _item = label_tally[label];
1098  _item.nAmount += nAmount;
1099  _item.nConf = std::min(_item.nConf, nConf);
1100  _item.fIsWatchonly = fIsWatchonly;
1101  }
1102  else
1103  {
1104  UniValue obj(UniValue::VOBJ);
1105  if(fIsWatchonly)
1106  obj.pushKV("involvesWatchonly", true);
1107  obj.pushKV("address", EncodeDestination(address));
1108  obj.pushKV("amount", ValueFromAmount(nAmount));
1109  obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
1110  obj.pushKV("label", label);
1111  UniValue transactions(UniValue::VARR);
1112  if (it != mapTally.end())
1113  {
1114  for (const uint256& _item : (*it).second.txids)
1115  {
1116  transactions.push_back(_item.GetHex());
1117  }
1118  }
1119  obj.pushKV("txids", transactions);
1120  ret.push_back(obj);
1121  }
1122  }
1123 
1124  if (by_label)
1125  {
1126  for (const auto& entry : label_tally)
1127  {
1128  CAmount nAmount = entry.second.nAmount;
1129  int nConf = entry.second.nConf;
1130  UniValue obj(UniValue::VOBJ);
1131  if (entry.second.fIsWatchonly)
1132  obj.pushKV("involvesWatchonly", true);
1133  obj.pushKV("amount", ValueFromAmount(nAmount));
1134  obj.pushKV("confirmations", (nConf == std::numeric_limits<int>::max() ? 0 : nConf));
1135  obj.pushKV("label", entry.first);
1136  ret.push_back(obj);
1137  }
1138  }
1139 
1140  return ret;
1141 }
1142 
1143 static UniValue listreceivedbyaddress(const JSONRPCRequest& request)
1144 {
1145  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1146  CWallet* const pwallet = wallet.get();
1147 
1148  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1149  return NullUniValue;
1150  }
1151 
1152  if (request.fHelp || request.params.size() > 4)
1153  throw std::runtime_error(
1154  "listreceivedbyaddress ( minconf include_empty include_watchonly address_filter )\n"
1155  "\nList balances by receiving address.\n"
1156  "\nArguments:\n"
1157  "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
1158  "2. include_empty (bool, optional, default=false) Whether to include addresses that haven't received any payments.\n"
1159  "3. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n"
1160  "4. address_filter (string, optional) If present, only return information on this address.\n"
1161  "\nResult:\n"
1162  "[\n"
1163  " {\n"
1164  " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
1165  " \"address\" : \"receivingaddress\", (string) The receiving address\n"
1166  " \"amount\" : x.xxx, (numeric) The total amount in " + CURRENCY_UNIT + " received by the address\n"
1167  " \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
1168  " \"label\" : \"label\", (string) The label of the receiving address. The default label is \"\".\n"
1169  " \"txids\": [\n"
1170  " \"txid\", (string) The ids of transactions received with the address \n"
1171  " ...\n"
1172  " ]\n"
1173  " }\n"
1174  " ,...\n"
1175  "]\n"
1176 
1177  "\nExamples:\n"
1178  + HelpExampleCli("listreceivedbyaddress", "")
1179  + HelpExampleCli("listreceivedbyaddress", "6 true")
1180  + HelpExampleRpc("listreceivedbyaddress", "6, true, true")
1181  + HelpExampleRpc("listreceivedbyaddress", "6, true, true, \"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\"")
1182  );
1183 
1184  // Make sure the results are valid at least up to the most recent block
1185  // the user could have gotten from another RPC command prior to now
1186  pwallet->BlockUntilSyncedToCurrentChain();
1187 
1188  LOCK2(cs_main, pwallet->cs_wallet);
1189 
1190  return ListReceived(pwallet, request.params, false);
1191 }
1192 
1193 static UniValue listreceivedbylabel(const JSONRPCRequest& request)
1194 {
1195  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1196  CWallet* const pwallet = wallet.get();
1197 
1198  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1199  return NullUniValue;
1200  }
1201 
1202  if (request.fHelp || request.params.size() > 3)
1203  throw std::runtime_error(
1204  "listreceivedbylabel ( minconf include_empty include_watchonly)\n"
1205  "\nList received transactions by label.\n"
1206  "\nArguments:\n"
1207  "1. minconf (numeric, optional, default=1) The minimum number of confirmations before payments are included.\n"
1208  "2. include_empty (bool, optional, default=false) Whether to include labels that haven't received any payments.\n"
1209  "3. include_watchonly (bool, optional, default=false) Whether to include watch-only addresses (see 'importaddress').\n"
1210 
1211  "\nResult:\n"
1212  "[\n"
1213  " {\n"
1214  " \"involvesWatchonly\" : true, (bool) Only returned if imported addresses were involved in transaction\n"
1215  " \"amount\" : x.xxx, (numeric) The total amount received by addresses with this label\n"
1216  " \"confirmations\" : n, (numeric) The number of confirmations of the most recent transaction included\n"
1217  " \"label\" : \"label\" (string) The label of the receiving address. The default label is \"\".\n"
1218  " }\n"
1219  " ,...\n"
1220  "]\n"
1221 
1222  "\nExamples:\n"
1223  + HelpExampleCli("listreceivedbylabel", "")
1224  + HelpExampleCli("listreceivedbylabel", "6 true")
1225  + HelpExampleRpc("listreceivedbylabel", "6, true, true")
1226  );
1227 
1228  // Make sure the results are valid at least up to the most recent block
1229  // the user could have gotten from another RPC command prior to now
1230  pwallet->BlockUntilSyncedToCurrentChain();
1231 
1232  LOCK2(cs_main, pwallet->cs_wallet);
1233 
1234  return ListReceived(pwallet, request.params, true);
1235 }
1236 
1237 static void MaybePushAddress(UniValue & entry, const CTxDestination &dest)
1238 {
1239  if (IsValidDestination(dest)) {
1240  entry.pushKV("address", EncodeDestination(dest));
1241  }
1242 }
1243 
1254 static void ListTransactions(CWallet* const pwallet, const CWalletTx& wtx, int nMinDepth, bool fLong, UniValue& ret, const isminefilter& filter) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
1255 {
1256  CAmount nFee;
1257  std::list<COutputEntry> listReceived;
1258  std::list<COutputEntry> listSent;
1259 
1260  wtx.GetAmounts(listReceived, listSent, nFee, filter);
1261 
1262  bool involvesWatchonly = wtx.IsFromMe(ISMINE_WATCH_ONLY);
1263 
1264  // Sent
1265  if ((!listSent.empty() || nFee != 0))
1266  {
1267  for (const COutputEntry& s : listSent)
1268  {
1269  UniValue entry(UniValue::VOBJ);
1270  if (involvesWatchonly || (::IsMine(*pwallet, s.destination) & ISMINE_WATCH_ONLY)) {
1271  entry.pushKV("involvesWatchonly", true);
1272  }
1273  MaybePushAddress(entry, s.destination);
1274  entry.pushKV("category", "send");
1275  entry.pushKV("amount", ValueFromAmount(-s.amount));
1276  if (pwallet->mapAddressBook.count(s.destination)) {
1277  entry.pushKV("label", pwallet->mapAddressBook[s.destination].name);
1278  }
1279  entry.pushKV("vout", s.vout);
1280  entry.pushKV("fee", ValueFromAmount(-nFee));
1281  if (fLong)
1282  WalletTxToJSON(wtx, entry);
1283  entry.pushKV("abandoned", wtx.isAbandoned());
1284  ret.push_back(entry);
1285  }
1286  }
1287 
1288  // Received
1289  if (listReceived.size() > 0 && wtx.GetDepthInMainChain() >= nMinDepth)
1290  {
1291  for (const COutputEntry& r : listReceived)
1292  {
1293  std::string label;
1294  if (pwallet->mapAddressBook.count(r.destination)) {
1295  label = pwallet->mapAddressBook[r.destination].name;
1296  }
1297  UniValue entry(UniValue::VOBJ);
1298  if (involvesWatchonly || (::IsMine(*pwallet, r.destination) & ISMINE_WATCH_ONLY)) {
1299  entry.pushKV("involvesWatchonly", true);
1300  }
1301  MaybePushAddress(entry, r.destination);
1302  if (wtx.IsCoinBase())
1303  {
1304  if (wtx.GetDepthInMainChain() < 1)
1305  entry.pushKV("category", "orphan");
1306  else if (wtx.IsImmatureCoinBase())
1307  entry.pushKV("category", "immature");
1308  else
1309  entry.pushKV("category", "generate");
1310  }
1311  else
1312  {
1313  entry.pushKV("category", "receive");
1314  }
1315  entry.pushKV("amount", ValueFromAmount(r.amount));
1316  if (pwallet->mapAddressBook.count(r.destination)) {
1317  entry.pushKV("label", label);
1318  }
1319  entry.pushKV("vout", r.vout);
1320  if (fLong)
1321  WalletTxToJSON(wtx, entry);
1322  ret.push_back(entry);
1323  }
1324  }
1325 }
1326 
1328 {
1329  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1330  CWallet* const pwallet = wallet.get();
1331 
1332  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1333  return NullUniValue;
1334  }
1335 
1336  if (request.fHelp || request.params.size() > 4)
1337  throw std::runtime_error(
1338  "listtransactions (dummy count skip include_watchonly)\n"
1339  "\nReturns up to 'count' most recent transactions skipping the first 'from' transactions.\n"
1340  "\nArguments:\n"
1341  "1. \"dummy\" (string, optional) If set, should be \"*\" for backwards compatibility.\n"
1342  "2. count (numeric, optional, default=10) The number of transactions to return\n"
1343  "3. skip (numeric, optional, default=0) The number of transactions to skip\n"
1344  "4. include_watchonly (bool, optional, default=false) Include transactions to watch-only addresses (see 'importaddress')\n"
1345  "\nResult:\n"
1346  "[\n"
1347  " {\n"
1348  " \"address\":\"address\", (string) The bitcoin address of the transaction.\n"
1349  " \"category\":\"send|receive\", (string) The transaction category.\n"
1350  " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and is positive\n"
1351  " for the 'receive' category,\n"
1352  " \"label\": \"label\", (string) A comment for the address/transaction, if any\n"
1353  " \"vout\": n, (numeric) the vout value\n"
1354  " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
1355  " 'send' category of transactions.\n"
1356  " \"confirmations\": n, (numeric) The number of confirmations for the transaction. Negative confirmations indicate the\n"
1357  " transaction conflicts with the block chain\n"
1358  " \"trusted\": xxx, (bool) Whether we consider the outputs of this unconfirmed transaction safe to spend.\n"
1359  " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction.\n"
1360  " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it.\n"
1361  " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
1362  " \"txid\": \"transactionid\", (string) The transaction id.\n"
1363  " \"time\": xxx, (numeric) The transaction time in seconds since epoch (midnight Jan 1 1970 GMT).\n"
1364  " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (midnight Jan 1 1970 GMT).\n"
1365  " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
1366  " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
1367  " may be unknown for unconfirmed transactions not in the mempool\n"
1368  " \"abandoned\": xxx (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
1369  " 'send' category of transactions.\n"
1370  " }\n"
1371  "]\n"
1372 
1373  "\nExamples:\n"
1374  "\nList the most recent 10 transactions in the systems\n"
1375  + HelpExampleCli("listtransactions", "") +
1376  "\nList transactions 100 to 120\n"
1377  + HelpExampleCli("listtransactions", "\"*\" 20 100") +
1378  "\nAs a JSON-RPC call\n"
1379  + HelpExampleRpc("listtransactions", "\"*\", 20, 100")
1380  );
1381 
1382  // Make sure the results are valid at least up to the most recent block
1383  // the user could have gotten from another RPC command prior to now
1384  pwallet->BlockUntilSyncedToCurrentChain();
1385 
1386  if (!request.params[0].isNull() && request.params[0].get_str() != "*") {
1387  throw JSONRPCError(RPC_INVALID_PARAMETER, "Dummy value must be set to \"*\"");
1388  }
1389  int nCount = 10;
1390  if (!request.params[1].isNull())
1391  nCount = request.params[1].get_int();
1392  int nFrom = 0;
1393  if (!request.params[2].isNull())
1394  nFrom = request.params[2].get_int();
1396  if(!request.params[3].isNull())
1397  if(request.params[3].get_bool())
1399 
1400  if (nCount < 0)
1401  throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative count");
1402  if (nFrom < 0)
1403  throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative from");
1404 
1406 
1407  {
1408  LOCK2(cs_main, pwallet->cs_wallet);
1409 
1410  const CWallet::TxItems & txOrdered = pwallet->wtxOrdered;
1411 
1412  // iterate backwards until we have nCount items to return:
1413  for (CWallet::TxItems::const_reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it)
1414  {
1415  CWalletTx *const pwtx = (*it).second;
1416  ListTransactions(pwallet, *pwtx, 0, true, ret, filter);
1417  if ((int)ret.size() >= (nCount+nFrom)) break;
1418  }
1419  }
1420 
1421  // ret is newest to oldest
1422 
1423  if (nFrom > (int)ret.size())
1424  nFrom = ret.size();
1425  if ((nFrom + nCount) > (int)ret.size())
1426  nCount = ret.size() - nFrom;
1427 
1428  std::vector<UniValue> arrTmp = ret.getValues();
1429 
1430  std::vector<UniValue>::iterator first = arrTmp.begin();
1431  std::advance(first, nFrom);
1432  std::vector<UniValue>::iterator last = arrTmp.begin();
1433  std::advance(last, nFrom+nCount);
1434 
1435  if (last != arrTmp.end()) arrTmp.erase(last, arrTmp.end());
1436  if (first != arrTmp.begin()) arrTmp.erase(arrTmp.begin(), first);
1437 
1438  std::reverse(arrTmp.begin(), arrTmp.end()); // Return oldest to newest
1439 
1440  ret.clear();
1441  ret.setArray();
1442  ret.push_backV(arrTmp);
1443 
1444  return ret;
1445 }
1446 
1447 static UniValue listsinceblock(const JSONRPCRequest& request)
1448 {
1449  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1450  CWallet* const pwallet = wallet.get();
1451 
1452  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1453  return NullUniValue;
1454  }
1455 
1456  if (request.fHelp || request.params.size() > 4)
1457  throw std::runtime_error(
1458  "listsinceblock ( \"blockhash\" target_confirmations include_watchonly include_removed )\n"
1459  "\nGet all transactions in blocks since block [blockhash], or all transactions if omitted.\n"
1460  "If \"blockhash\" is no longer a part of the main chain, transactions from the fork point onward are included.\n"
1461  "Additionally, if include_removed is set, transactions affecting the wallet which were removed are returned in the \"removed\" array.\n"
1462  "\nArguments:\n"
1463  "1. \"blockhash\" (string, optional) The block hash to list transactions since\n"
1464  "2. target_confirmations: (numeric, optional, default=1) Return the nth block hash from the main chain. e.g. 1 would mean the best block hash. Note: this is not used as a filter, but only affects [lastblock] in the return value\n"
1465  "3. include_watchonly: (bool, optional, default=false) Include transactions to watch-only addresses (see 'importaddress')\n"
1466  "4. include_removed: (bool, optional, default=true) Show transactions that were removed due to a reorg in the \"removed\" array\n"
1467  " (not guaranteed to work on pruned nodes)\n"
1468  "\nResult:\n"
1469  "{\n"
1470  " \"transactions\": [\n"
1471  " \"address\":\"address\", (string) The bitcoin address of the transaction. Not present for move transactions (category = move).\n"
1472  " \"category\":\"send|receive\", (string) The transaction category. 'send' has negative amounts, 'receive' has positive amounts.\n"
1473  " \"amount\": x.xxx, (numeric) The amount in " + CURRENCY_UNIT + ". This is negative for the 'send' category, and for the 'move' category for moves \n"
1474  " outbound. It is positive for the 'receive' category, and for the 'move' category for inbound funds.\n"
1475  " \"vout\" : n, (numeric) the vout value\n"
1476  " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the 'send' category of transactions.\n"
1477  " \"confirmations\": n, (numeric) The number of confirmations for the transaction. Available for 'send' and 'receive' category of transactions.\n"
1478  " When it's < 0, it means the transaction conflicted that many blocks ago.\n"
1479  " \"blockhash\": \"hashvalue\", (string) The block hash containing the transaction. Available for 'send' and 'receive' category of transactions.\n"
1480  " \"blockindex\": n, (numeric) The index of the transaction in the block that includes it. Available for 'send' and 'receive' category of transactions.\n"
1481  " \"blocktime\": xxx, (numeric) The block time in seconds since epoch (1 Jan 1970 GMT).\n"
1482  " \"txid\": \"transactionid\", (string) The transaction id. Available for 'send' and 'receive' category of transactions.\n"
1483  " \"time\": xxx, (numeric) The transaction time in seconds since epoch (Jan 1 1970 GMT).\n"
1484  " \"timereceived\": xxx, (numeric) The time received in seconds since epoch (Jan 1 1970 GMT). Available for 'send' and 'receive' category of transactions.\n"
1485  " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
1486  " may be unknown for unconfirmed transactions not in the mempool\n"
1487  " \"abandoned\": xxx, (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the 'send' category of transactions.\n"
1488  " \"comment\": \"...\", (string) If a comment is associated with the transaction.\n"
1489  " \"label\" : \"label\" (string) A comment for the address/transaction, if any\n"
1490  " \"to\": \"...\", (string) If a comment to is associated with the transaction.\n"
1491  " ],\n"
1492  " \"removed\": [\n"
1493  " <structure is the same as \"transactions\" above, only present if include_removed=true>\n"
1494  " Note: transactions that were re-added in the active chain will appear as-is in this array, and may thus have a positive confirmation count.\n"
1495  " ],\n"
1496  " \"lastblock\": \"lastblockhash\" (string) The hash of the block (target_confirmations-1) from the best block on the main chain. This is typically used to feed back into listsinceblock the next time you call it. So you would generally use a target_confirmations of say 6, so you will be continually re-notified of transactions until they've reached 6 confirmations plus any new ones\n"
1497  "}\n"
1498  "\nExamples:\n"
1499  + HelpExampleCli("listsinceblock", "")
1500  + HelpExampleCli("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\" 6")
1501  + HelpExampleRpc("listsinceblock", "\"000000000000000bacf66f7497b7dc45ef753ee9a7d38571037cdb1a57f663ad\", 6")
1502  );
1503 
1504  // Make sure the results are valid at least up to the most recent block
1505  // the user could have gotten from another RPC command prior to now
1506  pwallet->BlockUntilSyncedToCurrentChain();
1507 
1508  LOCK2(cs_main, pwallet->cs_wallet);
1509 
1510  const CBlockIndex* pindex = nullptr; // Block index of the specified block or the common ancestor, if the block provided was in a deactivated chain.
1511  const CBlockIndex* paltindex = nullptr; // Block index of the specified block, even if it's in a deactivated chain.
1512  int target_confirms = 1;
1514 
1515  if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
1516  uint256 blockId(ParseHashV(request.params[0], "blockhash"));
1517 
1518  paltindex = pindex = LookupBlockIndex(blockId);
1519  if (!pindex) {
1520  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
1521  }
1522  if (chainActive[pindex->nHeight] != pindex) {
1523  // the block being asked for is a part of a deactivated chain;
1524  // we don't want to depend on its perceived height in the block
1525  // chain, we want to instead use the last common ancestor
1526  pindex = chainActive.FindFork(pindex);
1527  }
1528  }
1529 
1530  if (!request.params[1].isNull()) {
1531  target_confirms = request.params[1].get_int();
1532 
1533  if (target_confirms < 1) {
1534  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
1535  }
1536  }
1537 
1538  if (!request.params[2].isNull() && request.params[2].get_bool()) {
1540  }
1541 
1542  bool include_removed = (request.params[3].isNull() || request.params[3].get_bool());
1543 
1544  int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1;
1545 
1546  UniValue transactions(UniValue::VARR);
1547 
1548  for (const std::pair<const uint256, CWalletTx>& pairWtx : pwallet->mapWallet) {
1549  CWalletTx tx = pairWtx.second;
1550 
1551  if (depth == -1 || tx.GetDepthInMainChain() < depth) {
1552  ListTransactions(pwallet, tx, 0, true, transactions, filter);
1553  }
1554  }
1555 
1556  // when a reorg'd block is requested, we also list any relevant transactions
1557  // in the blocks of the chain that was detached
1558  UniValue removed(UniValue::VARR);
1559  while (include_removed && paltindex && paltindex != pindex) {
1560  CBlock block;
1561  if (!ReadBlockFromDisk(block, paltindex, Params().GetConsensus())) {
1562  throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
1563  }
1564  for (const CTransactionRef& tx : block.vtx) {
1565  auto it = pwallet->mapWallet.find(tx->GetHash());
1566  if (it != pwallet->mapWallet.end()) {
1567  // We want all transactions regardless of confirmation count to appear here,
1568  // even negative confirmation ones, hence the big negative.
1569  ListTransactions(pwallet, it->second, -100000000, true, removed, filter);
1570  }
1571  }
1572  paltindex = paltindex->pprev;
1573  }
1574 
1575  CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms];
1576  uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256();
1577 
1579  ret.pushKV("transactions", transactions);
1580  if (include_removed) ret.pushKV("removed", removed);
1581  ret.pushKV("lastblock", lastblock.GetHex());
1582 
1583  return ret;
1584 }
1585 
1586 static UniValue gettransaction(const JSONRPCRequest& request)
1587 {
1588  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1589  CWallet* const pwallet = wallet.get();
1590 
1591  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1592  return NullUniValue;
1593  }
1594 
1595  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
1596  throw std::runtime_error(
1597  "gettransaction \"txid\" ( include_watchonly )\n"
1598  "\nGet detailed information about in-wallet transaction <txid>\n"
1599  "\nArguments:\n"
1600  "1. \"txid\" (string, required) The transaction id\n"
1601  "2. \"include_watchonly\" (bool, optional, default=false) Whether to include watch-only addresses in balance calculation and details[]\n"
1602  "\nResult:\n"
1603  "{\n"
1604  " \"amount\" : x.xxx, (numeric) The transaction amount in " + CURRENCY_UNIT + "\n"
1605  " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
1606  " 'send' category of transactions.\n"
1607  " \"confirmations\" : n, (numeric) The number of confirmations\n"
1608  " \"blockhash\" : \"hash\", (string) The block hash\n"
1609  " \"blockindex\" : xx, (numeric) The index of the transaction in the block that includes it\n"
1610  " \"blocktime\" : ttt, (numeric) The time in seconds since epoch (1 Jan 1970 GMT)\n"
1611  " \"txid\" : \"transactionid\", (string) The transaction id.\n"
1612  " \"time\" : ttt, (numeric) The transaction time in seconds since epoch (1 Jan 1970 GMT)\n"
1613  " \"timereceived\" : ttt, (numeric) The time received in seconds since epoch (1 Jan 1970 GMT)\n"
1614  " \"bip125-replaceable\": \"yes|no|unknown\", (string) Whether this transaction could be replaced due to BIP125 (replace-by-fee);\n"
1615  " may be unknown for unconfirmed transactions not in the mempool\n"
1616  " \"details\" : [\n"
1617  " {\n"
1618  " \"address\" : \"address\", (string) The bitcoin address involved in the transaction\n"
1619  " \"category\" : \"send|receive\", (string) The category, either 'send' or 'receive'\n"
1620  " \"amount\" : x.xxx, (numeric) The amount in " + CURRENCY_UNIT + "\n"
1621  " \"label\" : \"label\", (string) A comment for the address/transaction, if any\n"
1622  " \"vout\" : n, (numeric) the vout value\n"
1623  " \"fee\": x.xxx, (numeric) The amount of the fee in " + CURRENCY_UNIT + ". This is negative and only available for the \n"
1624  " 'send' category of transactions.\n"
1625  " \"abandoned\": xxx (bool) 'true' if the transaction has been abandoned (inputs are respendable). Only available for the \n"
1626  " 'send' category of transactions.\n"
1627  " }\n"
1628  " ,...\n"
1629  " ],\n"
1630  " \"hex\" : \"data\" (string) Raw data for transaction\n"
1631  "}\n"
1632 
1633  "\nExamples:\n"
1634  + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
1635  + HelpExampleCli("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\" true")
1636  + HelpExampleRpc("gettransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
1637  );
1638 
1639  // Make sure the results are valid at least up to the most recent block
1640  // the user could have gotten from another RPC command prior to now
1641  pwallet->BlockUntilSyncedToCurrentChain();
1642 
1643  LOCK2(cs_main, pwallet->cs_wallet);
1644 
1645  uint256 hash(ParseHashV(request.params[0], "txid"));
1646 
1648  if(!request.params[1].isNull())
1649  if(request.params[1].get_bool())
1651 
1652  UniValue entry(UniValue::VOBJ);
1653  auto it = pwallet->mapWallet.find(hash);
1654  if (it == pwallet->mapWallet.end()) {
1655  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
1656  }
1657  const CWalletTx& wtx = it->second;
1658 
1659  CAmount nCredit = wtx.GetCredit(filter);
1660  CAmount nDebit = wtx.GetDebit(filter);
1661  CAmount nNet = nCredit - nDebit;
1662  CAmount nFee = (wtx.IsFromMe(filter) ? wtx.tx->GetValueOut() - nDebit : 0);
1663 
1664  entry.pushKV("amount", ValueFromAmount(nNet - nFee));
1665  if (wtx.IsFromMe(filter))
1666  entry.pushKV("fee", ValueFromAmount(nFee));
1667 
1668  WalletTxToJSON(wtx, entry);
1669 
1670  UniValue details(UniValue::VARR);
1671  ListTransactions(pwallet, wtx, 0, false, details, filter);
1672  entry.pushKV("details", details);
1673 
1674  std::string strHex = EncodeHexTx(*wtx.tx, RPCSerializationFlags());
1675  entry.pushKV("hex", strHex);
1676 
1677  return entry;
1678 }
1679 
1680 static UniValue abandontransaction(const JSONRPCRequest& request)
1681 {
1682  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1683  CWallet* const pwallet = wallet.get();
1684 
1685  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1686  return NullUniValue;
1687  }
1688 
1689  if (request.fHelp || request.params.size() != 1) {
1690  throw std::runtime_error(
1691  "abandontransaction \"txid\"\n"
1692  "\nMark in-wallet transaction <txid> as abandoned\n"
1693  "This will mark this transaction and all its in-wallet descendants as abandoned which will allow\n"
1694  "for their inputs to be respent. It can be used to replace \"stuck\" or evicted transactions.\n"
1695  "It only works on transactions which are not included in a block and are not currently in the mempool.\n"
1696  "It has no effect on transactions which are already abandoned.\n"
1697  "\nArguments:\n"
1698  "1. \"txid\" (string, required) The transaction id\n"
1699  "\nResult:\n"
1700  "\nExamples:\n"
1701  + HelpExampleCli("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
1702  + HelpExampleRpc("abandontransaction", "\"1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d\"")
1703  );
1704  }
1705 
1706  // Make sure the results are valid at least up to the most recent block
1707  // the user could have gotten from another RPC command prior to now
1708  pwallet->BlockUntilSyncedToCurrentChain();
1709 
1710  LOCK2(cs_main, pwallet->cs_wallet);
1711 
1712  uint256 hash(ParseHashV(request.params[0], "txid"));
1713 
1714  if (!pwallet->mapWallet.count(hash)) {
1715  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid or non-wallet transaction id");
1716  }
1717  if (!pwallet->AbandonTransaction(hash)) {
1718  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not eligible for abandonment");
1719  }
1720 
1721  return NullUniValue;
1722 }
1723 
1724 
1725 static UniValue backupwallet(const JSONRPCRequest& request)
1726 {
1727  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1728  CWallet* const pwallet = wallet.get();
1729 
1730  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1731  return NullUniValue;
1732  }
1733 
1734  if (request.fHelp || request.params.size() != 1)
1735  throw std::runtime_error(
1736  "backupwallet \"destination\"\n"
1737  "\nSafely copies current wallet file to destination, which can be a directory or a path with filename.\n"
1738  "\nArguments:\n"
1739  "1. \"destination\" (string) The destination directory or file\n"
1740  "\nExamples:\n"
1741  + HelpExampleCli("backupwallet", "\"backup.dat\"")
1742  + HelpExampleRpc("backupwallet", "\"backup.dat\"")
1743  );
1744 
1745  // Make sure the results are valid at least up to the most recent block
1746  // the user could have gotten from another RPC command prior to now
1747  pwallet->BlockUntilSyncedToCurrentChain();
1748 
1749  LOCK2(cs_main, pwallet->cs_wallet);
1750 
1751  std::string strDest = request.params[0].get_str();
1752  if (!pwallet->BackupWallet(strDest)) {
1753  throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!");
1754  }
1755 
1756  return NullUniValue;
1757 }
1758 
1759 
1760 static UniValue keypoolrefill(const JSONRPCRequest& request)
1761 {
1762  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1763  CWallet* const pwallet = wallet.get();
1764 
1765  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1766  return NullUniValue;
1767  }
1768 
1769  if (request.fHelp || request.params.size() > 1)
1770  throw std::runtime_error(
1771  "keypoolrefill ( newsize )\n"
1772  "\nFills the keypool."
1773  + HelpRequiringPassphrase(pwallet) + "\n"
1774  "\nArguments\n"
1775  "1. newsize (numeric, optional, default=100) The new keypool size\n"
1776  "\nExamples:\n"
1777  + HelpExampleCli("keypoolrefill", "")
1778  + HelpExampleRpc("keypoolrefill", "")
1779  );
1780 
1782  throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
1783  }
1784 
1785  LOCK2(cs_main, pwallet->cs_wallet);
1786 
1787  // 0 is interpreted by TopUpKeyPool() as the default keypool size given by -keypool
1788  unsigned int kpSize = 0;
1789  if (!request.params[0].isNull()) {
1790  if (request.params[0].get_int() < 0)
1791  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected valid size.");
1792  kpSize = (unsigned int)request.params[0].get_int();
1793  }
1794 
1795  EnsureWalletIsUnlocked(pwallet);
1796  pwallet->TopUpKeyPool(kpSize);
1797 
1798  if (pwallet->GetKeyPoolSize() < kpSize) {
1799  throw JSONRPCError(RPC_WALLET_ERROR, "Error refreshing keypool.");
1800  }
1801 
1802  return NullUniValue;
1803 }
1804 
1805 
1806 static UniValue walletpassphrase(const JSONRPCRequest& request)
1807 {
1808  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1809  CWallet* const pwallet = wallet.get();
1810 
1811  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1812  return NullUniValue;
1813  }
1814 
1815  if (request.fHelp || request.params.size() != 2) {
1816  throw std::runtime_error(
1817  "walletpassphrase \"passphrase\" timeout\n"
1818  "\nStores the wallet decryption key in memory for 'timeout' seconds.\n"
1819  "This is needed prior to performing transactions related to private keys such as sending bitcoins\n"
1820  "\nArguments:\n"
1821  "1. \"passphrase\" (string, required) The wallet passphrase\n"
1822  "2. timeout (numeric, required) The time to keep the decryption key in seconds; capped at 100000000 (~3 years).\n"
1823  "\nNote:\n"
1824  "Issuing the walletpassphrase command while the wallet is already unlocked will set a new unlock\n"
1825  "time that overrides the old one.\n"
1826  "\nExamples:\n"
1827  "\nUnlock the wallet for 60 seconds\n"
1828  + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 60") +
1829  "\nLock the wallet again (before 60 seconds)\n"
1830  + HelpExampleCli("walletlock", "") +
1831  "\nAs a JSON-RPC call\n"
1832  + HelpExampleRpc("walletpassphrase", "\"my pass phrase\", 60")
1833  );
1834  }
1835 
1836  LOCK2(cs_main, pwallet->cs_wallet);
1837 
1838  if (!pwallet->IsCrypted()) {
1839  throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrase was called.");
1840  }
1841 
1842  // Note that the walletpassphrase is stored in request.params[0] which is not mlock()ed
1843  SecureString strWalletPass;
1844  strWalletPass.reserve(100);
1845  // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
1846  // Alternately, find a way to make request.params[0] mlock()'d to begin with.
1847  strWalletPass = request.params[0].get_str().c_str();
1848 
1849  // Get the timeout
1850  int64_t nSleepTime = request.params[1].get_int64();
1851  // Timeout cannot be negative, otherwise it will relock immediately
1852  if (nSleepTime < 0) {
1853  throw JSONRPCError(RPC_INVALID_PARAMETER, "Timeout cannot be negative.");
1854  }
1855  // Clamp timeout
1856  constexpr int64_t MAX_SLEEP_TIME = 100000000; // larger values trigger a macos/libevent bug?
1857  if (nSleepTime > MAX_SLEEP_TIME) {
1858  nSleepTime = MAX_SLEEP_TIME;
1859  }
1860 
1861  if (strWalletPass.length() > 0)
1862  {
1863  if (!pwallet->Unlock(strWalletPass)) {
1864  throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
1865  }
1866  }
1867  else
1868  throw std::runtime_error(
1869  "walletpassphrase <passphrase> <timeout>\n"
1870  "Stores the wallet decryption key in memory for <timeout> seconds.");
1871 
1872  pwallet->TopUpKeyPool();
1873 
1874  pwallet->nRelockTime = GetTime() + nSleepTime;
1875 
1876  // Keep a weak pointer to the wallet so that it is possible to unload the
1877  // wallet before the following callback is called. If a valid shared pointer
1878  // is acquired in the callback then the wallet is still loaded.
1879  std::weak_ptr<CWallet> weak_wallet = wallet;
1880  RPCRunLater(strprintf("lockwallet(%s)", pwallet->GetName()), [weak_wallet] {
1881  if (auto shared_wallet = weak_wallet.lock()) {
1882  LOCK(shared_wallet->cs_wallet);
1883  shared_wallet->Lock();
1884  shared_wallet->nRelockTime = 0;
1885  }
1886  }, nSleepTime);
1887 
1888  return NullUniValue;
1889 }
1890 
1891 
1892 static UniValue walletpassphrasechange(const JSONRPCRequest& request)
1893 {
1894  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1895  CWallet* const pwallet = wallet.get();
1896 
1897  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1898  return NullUniValue;
1899  }
1900 
1901  if (request.fHelp || request.params.size() != 2) {
1902  throw std::runtime_error(
1903  "walletpassphrasechange \"oldpassphrase\" \"newpassphrase\"\n"
1904  "\nChanges the wallet passphrase from 'oldpassphrase' to 'newpassphrase'.\n"
1905  "\nArguments:\n"
1906  "1. \"oldpassphrase\" (string) The current passphrase\n"
1907  "2. \"newpassphrase\" (string) The new passphrase\n"
1908  "\nExamples:\n"
1909  + HelpExampleCli("walletpassphrasechange", "\"old one\" \"new one\"")
1910  + HelpExampleRpc("walletpassphrasechange", "\"old one\", \"new one\"")
1911  );
1912  }
1913 
1914  LOCK2(cs_main, pwallet->cs_wallet);
1915 
1916  if (!pwallet->IsCrypted()) {
1917  throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletpassphrasechange was called.");
1918  }
1919 
1920  // TODO: get rid of these .c_str() calls by implementing SecureString::operator=(std::string)
1921  // Alternately, find a way to make request.params[0] mlock()'d to begin with.
1922  SecureString strOldWalletPass;
1923  strOldWalletPass.reserve(100);
1924  strOldWalletPass = request.params[0].get_str().c_str();
1925 
1926  SecureString strNewWalletPass;
1927  strNewWalletPass.reserve(100);
1928  strNewWalletPass = request.params[1].get_str().c_str();
1929 
1930  if (strOldWalletPass.length() < 1 || strNewWalletPass.length() < 1)
1931  throw std::runtime_error(
1932  "walletpassphrasechange <oldpassphrase> <newpassphrase>\n"
1933  "Changes the wallet passphrase from <oldpassphrase> to <newpassphrase>.");
1934 
1935  if (!pwallet->ChangeWalletPassphrase(strOldWalletPass, strNewWalletPass)) {
1936  throw JSONRPCError(RPC_WALLET_PASSPHRASE_INCORRECT, "Error: The wallet passphrase entered was incorrect.");
1937  }
1938 
1939  return NullUniValue;
1940 }
1941 
1942 
1943 static UniValue walletlock(const JSONRPCRequest& request)
1944 {
1945  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1946  CWallet* const pwallet = wallet.get();
1947 
1948  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1949  return NullUniValue;
1950  }
1951 
1952  if (request.fHelp || request.params.size() != 0) {
1953  throw std::runtime_error(
1954  "walletlock\n"
1955  "\nRemoves the wallet encryption key from memory, locking the wallet.\n"
1956  "After calling this method, you will need to call walletpassphrase again\n"
1957  "before being able to call any methods which require the wallet to be unlocked.\n"
1958  "\nExamples:\n"
1959  "\nSet the passphrase for 2 minutes to perform a transaction\n"
1960  + HelpExampleCli("walletpassphrase", "\"my pass phrase\" 120") +
1961  "\nPerform a send (requires passphrase set)\n"
1962  + HelpExampleCli("sendtoaddress", "\"1M72Sfpbz1BPpXFHz9m3CdqATR44Jvaydd\" 1.0") +
1963  "\nClear the passphrase since we are done before 2 minutes is up\n"
1964  + HelpExampleCli("walletlock", "") +
1965  "\nAs a JSON-RPC call\n"
1966  + HelpExampleRpc("walletlock", "")
1967  );
1968  }
1969 
1970  LOCK2(cs_main, pwallet->cs_wallet);
1971 
1972  if (!pwallet->IsCrypted()) {
1973  throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an unencrypted wallet, but walletlock was called.");
1974  }
1975 
1976  pwallet->Lock();
1977  pwallet->nRelockTime = 0;
1978 
1979  return NullUniValue;
1980 }
1981 
1982 
1983 static UniValue encryptwallet(const JSONRPCRequest& request)
1984 {
1985  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
1986  CWallet* const pwallet = wallet.get();
1987 
1988  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
1989  return NullUniValue;
1990  }
1991 
1992  if (request.fHelp || request.params.size() != 1) {
1993  throw std::runtime_error(
1994  "encryptwallet \"passphrase\"\n"
1995  "\nEncrypts the wallet with 'passphrase'. This is for first time encryption.\n"
1996  "After this, any calls that interact with private keys such as sending or signing \n"
1997  "will require the passphrase to be set prior the making these calls.\n"
1998  "Use the walletpassphrase call for this, and then walletlock call.\n"
1999  "If the wallet is already encrypted, use the walletpassphrasechange call.\n"
2000  "\nArguments:\n"
2001  "1. \"passphrase\" (string) The pass phrase to encrypt the wallet with. It must be at least 1 character, but should be long.\n"
2002  "\nExamples:\n"
2003  "\nEncrypt your wallet\n"
2004  + HelpExampleCli("encryptwallet", "\"my pass phrase\"") +
2005  "\nNow set the passphrase to use the wallet, such as for signing or sending bitcoin\n"
2006  + HelpExampleCli("walletpassphrase", "\"my pass phrase\"") +
2007  "\nNow we can do something like sign\n"
2008  + HelpExampleCli("signmessage", "\"address\" \"test message\"") +
2009  "\nNow lock the wallet again by removing the passphrase\n"
2010  + HelpExampleCli("walletlock", "") +
2011  "\nAs a JSON-RPC call\n"
2012  + HelpExampleRpc("encryptwallet", "\"my pass phrase\"")
2013  );
2014  }
2015 
2016  LOCK2(cs_main, pwallet->cs_wallet);
2017 
2018  if (pwallet->IsCrypted()) {
2019  throw JSONRPCError(RPC_WALLET_WRONG_ENC_STATE, "Error: running with an encrypted wallet, but encryptwallet was called.");
2020  }
2021 
2022  // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
2023  // Alternately, find a way to make request.params[0] mlock()'d to begin with.
2024  SecureString strWalletPass;
2025  strWalletPass.reserve(100);
2026  strWalletPass = request.params[0].get_str().c_str();
2027 
2028  if (strWalletPass.length() < 1)
2029  throw std::runtime_error(
2030  "encryptwallet <passphrase>\n"
2031  "Encrypts the wallet with <passphrase>.");
2032 
2033  if (!pwallet->EncryptWallet(strWalletPass)) {
2034  throw JSONRPCError(RPC_WALLET_ENCRYPTION_FAILED, "Error: Failed to encrypt the wallet.");
2035  }
2036 
2037  return "wallet encrypted; The keypool has been flushed and a new HD seed was generated (if you are using HD). You need to make a new backup.";
2038 }
2039 
2040 static UniValue lockunspent(const JSONRPCRequest& request)
2041 {
2042  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
2043  CWallet* const pwallet = wallet.get();
2044 
2045  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
2046  return NullUniValue;
2047  }
2048 
2049  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2)
2050  throw std::runtime_error(
2051  "lockunspent unlock ([{\"txid\":\"txid\",\"vout\":n},...])\n"
2052  "\nUpdates list of temporarily unspendable outputs.\n"
2053  "Temporarily lock (unlock=false) or unlock (unlock=true) specified transaction outputs.\n"
2054  "If no transaction outputs are specified when unlocking then all current locked transaction outputs are unlocked.\n"
2055  "A locked transaction output will not be chosen by automatic coin selection, when spending bitcoins.\n"
2056  "Locks are stored in memory only. Nodes start with zero locked outputs, and the locked output list\n"
2057  "is always cleared (by virtue of process exit) when a node stops or fails.\n"
2058  "Also see the listunspent call\n"
2059  "\nArguments:\n"
2060  "1. unlock (boolean, required) Whether to unlock (true) or lock (false) the specified transactions\n"
2061  "2. \"transactions\" (string, optional) A json array of objects. Each object the txid (string) vout (numeric)\n"
2062  " [ (json array of json objects)\n"
2063  " {\n"
2064  " \"txid\":\"id\", (string) The transaction id\n"
2065  " \"vout\": n (numeric) The output number\n"
2066  " }\n"
2067  " ,...\n"
2068  " ]\n"
2069 
2070  "\nResult:\n"
2071  "true|false (boolean) Whether the command was successful or not\n"
2072 
2073  "\nExamples:\n"
2074  "\nList the unspent transactions\n"
2075  + HelpExampleCli("listunspent", "") +
2076  "\nLock an unspent transaction\n"
2077  + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
2078  "\nList the locked transactions\n"
2079  + HelpExampleCli("listlockunspent", "") +
2080  "\nUnlock the transaction again\n"
2081  + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
2082  "\nAs a JSON-RPC call\n"
2083  + HelpExampleRpc("lockunspent", "false, \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"")
2084  );
2085 
2086  // Make sure the results are valid at least up to the most recent block
2087  // the user could have gotten from another RPC command prior to now
2088  pwallet->BlockUntilSyncedToCurrentChain();
2089 
2090  LOCK2(cs_main, pwallet->cs_wallet);
2091 
2093 
2094  bool fUnlock = request.params[0].get_bool();
2095 
2096  if (request.params[1].isNull()) {
2097  if (fUnlock)
2098  pwallet->UnlockAllCoins();
2099  return true;
2100  }
2101 
2103 
2104  const UniValue& output_params = request.params[1];
2105 
2106  // Create and validate the COutPoints first.
2107 
2108  std::vector<COutPoint> outputs;
2109  outputs.reserve(output_params.size());
2110 
2111  for (unsigned int idx = 0; idx < output_params.size(); idx++) {
2112  const UniValue& o = output_params[idx].get_obj();
2113 
2114  RPCTypeCheckObj(o,
2115  {
2116  {"txid", UniValueType(UniValue::VSTR)},
2117  {"vout", UniValueType(UniValue::VNUM)},
2118  });
2119 
2120  const uint256 txid(ParseHashO(o, "txid"));
2121  const int nOutput = find_value(o, "vout").get_int();
2122  if (nOutput < 0) {
2123  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
2124  }
2125 
2126  const COutPoint outpt(txid, nOutput);
2127 
2128  const auto it = pwallet->mapWallet.find(outpt.hash);
2129  if (it == pwallet->mapWallet.end()) {
2130  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, unknown transaction");
2131  }
2132 
2133  const CWalletTx& trans = it->second;
2134 
2135  if (outpt.n >= trans.tx->vout.size()) {
2136  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout index out of bounds");
2137  }
2138 
2139  if (pwallet->IsSpent(outpt.hash, outpt.n)) {
2140  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected unspent output");
2141  }
2142 
2143  const bool is_locked = pwallet->IsLockedCoin(outpt.hash, outpt.n);
2144 
2145  if (fUnlock && !is_locked) {
2146  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected locked output");
2147  }
2148 
2149  if (!fUnlock && is_locked) {
2150  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output already locked");
2151  }
2152 
2153  outputs.push_back(outpt);
2154  }
2155 
2156  // Atomically set (un)locked status for the outputs.
2157  for (const COutPoint& outpt : outputs) {
2158  if (fUnlock) pwallet->UnlockCoin(outpt);
2159  else pwallet->LockCoin(outpt);
2160  }
2161 
2162  return true;
2163 }
2164 
2165 static UniValue listlockunspent(const JSONRPCRequest& request)
2166 {
2167  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
2168  CWallet* const pwallet = wallet.get();
2169 
2170  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
2171  return NullUniValue;
2172  }
2173 
2174  if (request.fHelp || request.params.size() > 0)
2175  throw std::runtime_error(
2176  "listlockunspent\n"
2177  "\nReturns list of temporarily unspendable outputs.\n"
2178  "See the lockunspent call to lock and unlock transactions for spending.\n"
2179  "\nResult:\n"
2180  "[\n"
2181  " {\n"
2182  " \"txid\" : \"transactionid\", (string) The transaction id locked\n"
2183  " \"vout\" : n (numeric) The vout value\n"
2184  " }\n"
2185  " ,...\n"
2186  "]\n"
2187  "\nExamples:\n"
2188  "\nList the unspent transactions\n"
2189  + HelpExampleCli("listunspent", "") +
2190  "\nLock an unspent transaction\n"
2191  + HelpExampleCli("lockunspent", "false \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
2192  "\nList the locked transactions\n"
2193  + HelpExampleCli("listlockunspent", "") +
2194  "\nUnlock the transaction again\n"
2195  + HelpExampleCli("lockunspent", "true \"[{\\\"txid\\\":\\\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\\\",\\\"vout\\\":1}]\"") +
2196  "\nAs a JSON-RPC call\n"
2197  + HelpExampleRpc("listlockunspent", "")
2198  );
2199 
2200  LOCK2(cs_main, pwallet->cs_wallet);
2201 
2202  std::vector<COutPoint> vOutpts;
2203  pwallet->ListLockedCoins(vOutpts);
2204 
2206 
2207  for (const COutPoint& outpt : vOutpts) {
2209 
2210  o.pushKV("txid", outpt.hash.GetHex());
2211  o.pushKV("vout", (int)outpt.n);
2212  ret.push_back(o);
2213  }
2214 
2215  return ret;
2216 }
2217 
2218 static UniValue settxfee(const JSONRPCRequest& request)
2219 {
2220  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
2221  CWallet* const pwallet = wallet.get();
2222 
2223  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
2224  return NullUniValue;
2225  }
2226 
2227  if (request.fHelp || request.params.size() < 1 || request.params.size() > 1) {
2228  throw std::runtime_error(
2229  "settxfee amount\n"
2230  "\nSet the transaction fee per kB for this wallet. Overrides the global -paytxfee command line parameter.\n"
2231  "\nArguments:\n"
2232  "1. amount (numeric or string, required) The transaction fee in " + CURRENCY_UNIT + "/kB\n"
2233  "\nResult\n"
2234  "true|false (boolean) Returns true if successful\n"
2235  "\nExamples:\n"
2236  + HelpExampleCli("settxfee", "0.00001")
2237  + HelpExampleRpc("settxfee", "0.00001")
2238  );
2239  }
2240 
2241  LOCK2(cs_main, pwallet->cs_wallet);
2242 
2243  CAmount nAmount = AmountFromValue(request.params[0]);
2244  CFeeRate tx_fee_rate(nAmount, 1000);
2245  if (tx_fee_rate == 0) {
2246  // automatic selection
2247  } else if (tx_fee_rate < ::minRelayTxFee) {
2248  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be less than min relay tx fee (%s)", ::minRelayTxFee.ToString()));
2249  } else if (tx_fee_rate < pwallet->m_min_fee) {
2250  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be less than wallet min fee (%s)", pwallet->m_min_fee.ToString()));
2251  }
2252 
2253  pwallet->m_pay_tx_fee = tx_fee_rate;
2254  return true;
2255 }
2256 
2257 static UniValue getwalletinfo(const JSONRPCRequest& request)
2258 {
2259  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
2260  CWallet* const pwallet = wallet.get();
2261 
2262  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
2263  return NullUniValue;
2264  }
2265 
2266  if (request.fHelp || request.params.size() != 0)
2267  throw std::runtime_error(
2268  "getwalletinfo\n"
2269  "Returns an object containing various wallet state info.\n"
2270  "\nResult:\n"
2271  "{\n"
2272  " \"walletname\": xxxxx, (string) the wallet name\n"
2273  " \"walletversion\": xxxxx, (numeric) the wallet version\n"
2274  " \"balance\": xxxxxxx, (numeric) the total confirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
2275  " \"unconfirmed_balance\": xxx, (numeric) the total unconfirmed balance of the wallet in " + CURRENCY_UNIT + "\n"
2276  " \"immature_balance\": xxxxxx, (numeric) the total immature balance of the wallet in " + CURRENCY_UNIT + "\n"
2277  " \"txcount\": xxxxxxx, (numeric) the total number of transactions in the wallet\n"
2278  " \"keypoololdest\": xxxxxx, (numeric) the timestamp (seconds since Unix epoch) of the oldest pre-generated key in the key pool\n"
2279  " \"keypoolsize\": xxxx, (numeric) how many new keys are pre-generated (only counts external keys)\n"
2280  " \"keypoolsize_hd_internal\": xxxx, (numeric) how many new keys are pre-generated for internal use (used for change outputs, only appears if the wallet is using this feature, otherwise external keys are used)\n"
2281  " \"unlocked_until\": ttt, (numeric) the timestamp in seconds since epoch (midnight Jan 1 1970 GMT) that the wallet is unlocked for transfers, or 0 if the wallet is locked\n"
2282  " \"paytxfee\": x.xxxx, (numeric) the transaction fee configuration, set in " + CURRENCY_UNIT + "/kB\n"
2283  " \"hdseedid\": \"<hash360>\" (string, optional) the Hash360 of the HD seed (only present when HD is enabled)\n"
2284  " \"hdmasterkeyid\": \"<hash360>\" (string, optional) alias for hdseedid retained for backwards-compatibility. Will be removed in V0.18.\n"
2285  " \"private_keys_enabled\": true|false (boolean) false if privatekeys are disabled for this wallet (enforced watch-only wallet)\n"
2286  "}\n"
2287  "\nExamples:\n"
2288  + HelpExampleCli("getwalletinfo", "")
2289  + HelpExampleRpc("getwalletinfo", "")
2290  );
2291 
2292  // Make sure the results are valid at least up to the most recent block
2293  // the user could have gotten from another RPC command prior to now
2294  pwallet->BlockUntilSyncedToCurrentChain();
2295 
2296  LOCK2(cs_main, pwallet->cs_wallet);
2297 
2298  UniValue obj(UniValue::VOBJ);
2299 
2300  size_t kpExternalSize = pwallet->KeypoolCountExternalKeys();
2301  obj.pushKV("walletname", pwallet->GetName());
2302  obj.pushKV("walletversion", pwallet->GetVersion());
2303  obj.pushKV("balance", ValueFromAmount(pwallet->GetBalance()));
2304  obj.pushKV("unconfirmed_balance", ValueFromAmount(pwallet->GetUnconfirmedBalance()));
2305  obj.pushKV("immature_balance", ValueFromAmount(pwallet->GetImmatureBalance()));
2306  obj.pushKV("txcount", (int)pwallet->mapWallet.size());
2307  obj.pushKV("keypoololdest", pwallet->GetOldestKeyPoolTime());
2308  obj.pushKV("keypoolsize", (int64_t)kpExternalSize);
2309  CKeyID seed_id = pwallet->GetHDChain().seed_id;
2310  if (!seed_id.IsNull() && pwallet->CanSupportFeature(FEATURE_HD_SPLIT)) {
2311  obj.pushKV("keypoolsize_hd_internal", (int64_t)(pwallet->GetKeyPoolSize() - kpExternalSize));
2312  }
2313  if (pwallet->IsCrypted()) {
2314  obj.pushKV("unlocked_until", pwallet->nRelockTime);
2315  }
2316  obj.pushKV("paytxfee", ValueFromAmount(pwallet->m_pay_tx_fee.GetFeePerK()));
2317  if (!seed_id.IsNull()) {
2318  obj.pushKV("hdseedid", seed_id.GetHex());
2319  obj.pushKV("hdmasterkeyid", seed_id.GetHex());
2320  }
2321  obj.pushKV("private_keys_enabled", !pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS));
2322  return obj;
2323 }
2324 
2325 static UniValue listwalletdir(const JSONRPCRequest& request)
2326 {
2327  if (request.fHelp || request.params.size() != 0) {
2328  throw std::runtime_error(
2329  "listwalletdir\n"
2330  "Returns a list of wallets in the wallet directory.\n"
2331  "{\n"
2332  " \"wallets\" : [ (json array of objects)\n"
2333  " {\n"
2334  " \"name\" : \"name\" (string) The wallet name\n"
2335  " }\n"
2336  " ,...\n"
2337  " ]\n"
2338  "}\n"
2339  "\nExamples:\n"
2340  + HelpExampleCli("listwalletdir", "")
2341  + HelpExampleRpc("listwalletdir", "")
2342  );
2343  }
2344 
2345  UniValue wallets(UniValue::VARR);
2346  for (const auto& path : ListWalletDir()) {
2347  UniValue wallet(UniValue::VOBJ);
2348  wallet.pushKV("name", path.string());
2349  wallets.push_back(wallet);
2350  }
2351 
2352  UniValue result(UniValue::VOBJ);
2353  result.pushKV("wallets", wallets);
2354  return result;
2355 }
2356 
2357 static UniValue listwallets(const JSONRPCRequest& request)
2358 {
2359  if (request.fHelp || request.params.size() != 0)
2360  throw std::runtime_error(
2361  "listwallets\n"
2362  "Returns a list of currently loaded wallets.\n"
2363  "For full information on the wallet, use \"getwalletinfo\"\n"
2364  "\nResult:\n"
2365  "[ (json array of strings)\n"
2366  " \"walletname\" (string) the wallet name\n"
2367  " ...\n"
2368  "]\n"
2369  "\nExamples:\n"
2370  + HelpExampleCli("listwallets", "")
2371  + HelpExampleRpc("listwallets", "")
2372  );
2373 
2374  UniValue obj(UniValue::VARR);
2375 
2376  for (const std::shared_ptr<CWallet>& wallet : GetWallets()) {
2377  if (!EnsureWalletIsAvailable(wallet.get(), request.fHelp)) {
2378  return NullUniValue;
2379  }
2380 
2381  LOCK(wallet->cs_wallet);
2382 
2383  obj.push_back(wallet->GetName());
2384  }
2385 
2386  return obj;
2387 }
2388 
2389 static UniValue loadwallet(const JSONRPCRequest& request)
2390 {
2391  if (request.fHelp || request.params.size() != 1)
2392  throw std::runtime_error(
2393  "loadwallet \"filename\"\n"
2394  "\nLoads a wallet from a wallet file or directory."
2395  "\nNote that all wallet command-line options used when starting bsha3d will be"
2396  "\napplied to the new wallet (eg -zapwallettxes, upgradewallet, rescan, etc).\n"
2397  "\nArguments:\n"
2398  "1. \"filename\" (string, required) The wallet directory or .dat file.\n"
2399  "\nResult:\n"
2400  "{\n"
2401  " \"name\" : <wallet_name>, (string) The wallet name if loaded successfully.\n"
2402  " \"warning\" : <warning>, (string) Warning message if wallet was not loaded cleanly.\n"
2403  "}\n"
2404  "\nExamples:\n"
2405  + HelpExampleCli("loadwallet", "\"test.dat\"")
2406  + HelpExampleRpc("loadwallet", "\"test.dat\"")
2407  );
2408  std::string wallet_file = request.params[0].get_str();
2409  std::string error;
2410 
2411  fs::path wallet_path = fs::absolute(wallet_file, GetWalletDir());
2412  if (fs::symlink_status(wallet_path).type() == fs::file_not_found) {
2413  throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Wallet " + wallet_file + " not found.");
2414  } else if (fs::is_directory(wallet_path)) {
2415  // The given filename is a directory. Check that there's a wallet.dat file.
2416  fs::path wallet_dat_file = wallet_path / "wallet.dat";
2417  if (fs::symlink_status(wallet_dat_file).type() == fs::file_not_found) {
2418  throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Directory " + wallet_file + " does not contain a wallet.dat file.");
2419  }
2420  }
2421 
2422  std::string warning;
2423  if (!CWallet::Verify(wallet_file, false, error, warning)) {
2424  throw JSONRPCError(RPC_WALLET_ERROR, "Wallet file verification failed: " + error);
2425  }
2426 
2427  std::shared_ptr<CWallet> const wallet = CWallet::CreateWalletFromFile(wallet_file, fs::absolute(wallet_file, GetWalletDir()));
2428  if (!wallet) {
2429  throw JSONRPCError(RPC_WALLET_ERROR, "Wallet loading failed.");
2430  }
2431  AddWallet(wallet);
2432 
2433  wallet->postInitProcess();
2434 
2435  UniValue obj(UniValue::VOBJ);
2436  obj.pushKV("name", wallet->GetName());
2437  obj.pushKV("warning", warning);
2438 
2439  return obj;
2440 }
2441 
2442 static UniValue createwallet(const JSONRPCRequest& request)
2443 {
2444  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
2445  throw std::runtime_error(
2446  "createwallet \"wallet_name\" ( disable_private_keys )\n"
2447  "\nCreates and loads a new wallet.\n"
2448  "\nArguments:\n"
2449  "1. \"wallet_name\" (string, required) The name for the new wallet. If this is a path, the wallet will be created at the path location.\n"
2450  "2. disable_private_keys (boolean, optional, default: false) Disable the possibility of private keys (only watchonlys are possible in this mode).\n"
2451  "\nResult:\n"
2452  "{\n"
2453  " \"name\" : <wallet_name>, (string) The wallet name if created successfully. If the wallet was created using a full path, the wallet_name will be the full path.\n"
2454  " \"warning\" : <warning>, (string) Warning message if wallet was not loaded cleanly.\n"
2455  "}\n"
2456  "\nExamples:\n"
2457  + HelpExampleCli("createwallet", "\"testwallet\"")
2458  + HelpExampleRpc("createwallet", "\"testwallet\"")
2459  );
2460  }
2461  std::string wallet_name = request.params[0].get_str();
2462  std::string error;
2463  std::string warning;
2464 
2465  bool disable_privatekeys = false;
2466  if (!request.params[1].isNull()) {
2467  disable_privatekeys = request.params[1].get_bool();
2468  }
2469 
2470  fs::path wallet_path = fs::absolute(wallet_name, GetWalletDir());
2471  if (fs::symlink_status(wallet_path).type() != fs::file_not_found) {
2472  throw JSONRPCError(RPC_WALLET_ERROR, "Wallet " + wallet_name + " already exists.");
2473  }
2474 
2475  // Wallet::Verify will check if we're trying to create a wallet with a duplication name.
2476  if (!CWallet::Verify(wallet_name, false, error, warning)) {
2477  throw JSONRPCError(RPC_WALLET_ERROR, "Wallet file verification failed: " + error);
2478  }
2479 
2480  std::shared_ptr<CWallet> const wallet = CWallet::CreateWalletFromFile(wallet_name, fs::absolute(wallet_name, GetWalletDir()), (disable_privatekeys ? (uint64_t)WALLET_FLAG_DISABLE_PRIVATE_KEYS : 0));
2481  if (!wallet) {
2482  throw JSONRPCError(RPC_WALLET_ERROR, "Wallet creation failed.");
2483  }
2484  AddWallet(wallet);
2485 
2486  wallet->postInitProcess();
2487 
2488  UniValue obj(UniValue::VOBJ);
2489  obj.pushKV("name", wallet->GetName());
2490  obj.pushKV("warning", warning);
2491 
2492  return obj;
2493 }
2494 
2495 static UniValue unloadwallet(const JSONRPCRequest& request)
2496 {
2497  if (request.fHelp || request.params.size() > 1) {
2498  throw std::runtime_error(
2499  "unloadwallet ( \"wallet_name\" )\n"
2500  "Unloads the wallet referenced by the request endpoint otherwise unloads the wallet specified in the argument.\n"
2501  "Specifying the wallet name on a wallet endpoint is invalid."
2502  "\nArguments:\n"
2503  "1. \"wallet_name\" (string, optional) The name of the wallet to unload.\n"
2504  "\nExamples:\n"
2505  + HelpExampleCli("unloadwallet", "wallet_name")
2506  + HelpExampleRpc("unloadwallet", "wallet_name")
2507  );
2508  }
2509 
2510  std::string wallet_name;
2511  if (GetWalletNameFromJSONRPCRequest(request, wallet_name)) {
2512  if (!request.params[0].isNull()) {
2513  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot unload the requested wallet");
2514  }
2515  } else {
2516  wallet_name = request.params[0].get_str();
2517  }
2518 
2519  std::shared_ptr<CWallet> wallet = GetWallet(wallet_name);
2520  if (!wallet) {
2521  throw JSONRPCError(RPC_WALLET_NOT_FOUND, "Requested wallet does not exist or is not loaded");
2522  }
2523 
2524  // Release the "main" shared pointer and prevent further notifications.
2525  // Note that any attempt to load the same wallet would fail until the wallet
2526  // is destroyed (see CheckUniqueFileid).
2527  if (!RemoveWallet(wallet)) {
2528  throw JSONRPCError(RPC_MISC_ERROR, "Requested wallet already unloaded");
2529  }
2530  UnregisterValidationInterface(wallet.get());
2531 
2532  // The wallet can be in use so it's not possible to explicitly unload here.
2533  // Just notify the unload intent so that all shared pointers are released.
2534  // The wallet will be destroyed once the last shared pointer is released.
2535  wallet->NotifyUnload();
2536 
2537  // There's no point in waiting for the wallet to unload.
2538  // At this point this method should never fail. The unloading could only
2539  // fail due to an unexpected error which would cause a process termination.
2540 
2541  return NullUniValue;
2542 }
2543 
2544 static UniValue resendwallettransactions(const JSONRPCRequest& request)
2545 {
2546  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
2547  CWallet* const pwallet = wallet.get();
2548 
2549  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
2550  return NullUniValue;
2551  }
2552 
2553  if (request.fHelp || request.params.size() != 0)
2554  throw std::runtime_error(
2555  "resendwallettransactions\n"
2556  "Immediately re-broadcast unconfirmed wallet transactions to all peers.\n"
2557  "Intended only for testing; the wallet code periodically re-broadcasts\n"
2558  "automatically.\n"
2559  "Returns an RPC error if -walletbroadcast is set to false.\n"
2560  "Returns array of transaction ids that were re-broadcast.\n"
2561  );
2562 
2563  if (!g_connman)
2564  throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled");
2565 
2566  LOCK2(cs_main, pwallet->cs_wallet);
2567 
2568  if (!pwallet->GetBroadcastTransactions()) {
2569  throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet transaction broadcasting is disabled with -walletbroadcast");
2570  }
2571 
2572  std::vector<uint256> txids = pwallet->ResendWalletTransactionsBefore(GetTime(), g_connman.get());
2573  UniValue result(UniValue::VARR);
2574  for (const uint256& txid : txids)
2575  {
2576  result.push_back(txid.ToString());
2577  }
2578  return result;
2579 }
2580 
2581 static UniValue listunspent(const JSONRPCRequest& request)
2582 {
2583  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
2584  CWallet* const pwallet = wallet.get();
2585 
2586  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
2587  return NullUniValue;
2588  }
2589 
2590  if (request.fHelp || request.params.size() > 5)
2591  throw std::runtime_error(
2592  "listunspent ( minconf maxconf [\"addresses\",...] [include_unsafe] [query_options])\n"
2593  "\nReturns array of unspent transaction outputs\n"
2594  "with between minconf and maxconf (inclusive) confirmations.\n"
2595  "Optionally filter to only include txouts paid to specified addresses.\n"
2596  "\nArguments:\n"
2597  "1. minconf (numeric, optional, default=1) The minimum confirmations to filter\n"
2598  "2. maxconf (numeric, optional, default=9999999) The maximum confirmations to filter\n"
2599  "3. \"addresses\" (string) A json array of bitcoin addresses to filter\n"
2600  " [\n"
2601  " \"address\" (string) bitcoin address\n"
2602  " ,...\n"
2603  " ]\n"
2604  "4. include_unsafe (bool, optional, default=true) Include outputs that are not safe to spend\n"
2605  " See description of \"safe\" attribute below.\n"
2606  "5. query_options (json, optional) JSON with query options\n"
2607  " {\n"
2608  " \"minimumAmount\" (numeric or string, default=0) Minimum value of each UTXO in " + CURRENCY_UNIT + "\n"
2609  " \"maximumAmount\" (numeric or string, default=unlimited) Maximum value of each UTXO in " + CURRENCY_UNIT + "\n"
2610  " \"maximumCount\" (numeric or string, default=unlimited) Maximum number of UTXOs\n"
2611  " \"minimumSumAmount\" (numeric or string, default=unlimited) Minimum sum value of all UTXOs in " + CURRENCY_UNIT + "\n"
2612  " }\n"
2613  "\nResult\n"
2614  "[ (array of json object)\n"
2615  " {\n"
2616  " \"txid\" : \"txid\", (string) the transaction id \n"
2617  " \"vout\" : n, (numeric) the vout value\n"
2618  " \"address\" : \"address\", (string) the bitcoin address\n"
2619  " \"label\" : \"label\", (string) The associated label, or \"\" for the default label\n"
2620  " \"scriptPubKey\" : \"key\", (string) the script key\n"
2621  " \"amount\" : x.xxx, (numeric) the transaction output amount in " + CURRENCY_UNIT + "\n"
2622  " \"confirmations\" : n, (numeric) The number of confirmations\n"
2623  " \"redeemScript\" : n (string) The redeemScript if scriptPubKey is P2SH\n"
2624  " \"spendable\" : xxx, (bool) Whether we have the private keys to spend this output\n"
2625  " \"solvable\" : xxx, (bool) Whether we know how to spend this output, ignoring the lack of keys\n"
2626  " \"safe\" : xxx (bool) Whether this output is considered safe to spend. Unconfirmed transactions\n"
2627  " from outside keys and unconfirmed replacement transactions are considered unsafe\n"
2628  " and are not eligible for spending by fundrawtransaction and sendtoaddress.\n"
2629  " }\n"
2630  " ,...\n"
2631  "]\n"
2632 
2633  "\nExamples\n"
2634  + HelpExampleCli("listunspent", "")
2635  + HelpExampleCli("listunspent", "6 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
2636  + HelpExampleRpc("listunspent", "6, 9999999 \"[\\\"1PGFqEzfmQch1gKD3ra4k18PNj3tTUUSqg\\\",\\\"1LtvqCaApEdUGFkpKMM4MstjcaL4dKg8SP\\\"]\"")
2637  + HelpExampleCli("listunspent", "6 9999999 '[]' true '{ \"minimumAmount\": 0.005 }'")
2638  + HelpExampleRpc("listunspent", "6, 9999999, [] , true, { \"minimumAmount\": 0.005 } ")
2639  );
2640 
2641  int nMinDepth = 1;
2642  if (!request.params[0].isNull()) {
2644  nMinDepth = request.params[0].get_int();
2645  }
2646 
2647  int nMaxDepth = 9999999;
2648  if (!request.params[1].isNull()) {
2650  nMaxDepth = request.params[1].get_int();
2651  }
2652 
2653  std::set<CTxDestination> destinations;
2654  if (!request.params[2].isNull()) {
2656  UniValue inputs = request.params[2].get_array();
2657  for (unsigned int idx = 0; idx < inputs.size(); idx++) {
2658  const UniValue& input = inputs[idx];
2659  CTxDestination dest = DecodeDestination(input.get_str());
2660  if (!IsValidDestination(dest)) {
2661  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid BSHA3 address: ") + input.get_str());
2662  }
2663  if (!destinations.insert(dest).second) {
2664  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + input.get_str());
2665  }
2666  }
2667  }
2668 
2669  bool include_unsafe = true;
2670  if (!request.params[3].isNull()) {
2672  include_unsafe = request.params[3].get_bool();
2673  }
2674 
2675  CAmount nMinimumAmount = 0;
2676  CAmount nMaximumAmount = MAX_MONEY;
2677  CAmount nMinimumSumAmount = MAX_MONEY;
2678  uint64_t nMaximumCount = 0;
2679 
2680  if (!request.params[4].isNull()) {
2681  const UniValue& options = request.params[4].get_obj();
2682 
2683  if (options.exists("minimumAmount"))
2684  nMinimumAmount = AmountFromValue(options["minimumAmount"]);
2685 
2686  if (options.exists("maximumAmount"))
2687  nMaximumAmount = AmountFromValue(options["maximumAmount"]);
2688 
2689  if (options.exists("minimumSumAmount"))
2690  nMinimumSumAmount = AmountFromValue(options["minimumSumAmount"]);
2691 
2692  if (options.exists("maximumCount"))
2693  nMaximumCount = options["maximumCount"].get_int64();
2694  }
2695 
2696  // Make sure the results are valid at least up to the most recent block
2697  // the user could have gotten from another RPC command prior to now
2698  pwallet->BlockUntilSyncedToCurrentChain();
2699 
2700  UniValue results(UniValue::VARR);
2701  std::vector<COutput> vecOutputs;
2702  {
2703  LOCK2(cs_main, pwallet->cs_wallet);
2704  pwallet->AvailableCoins(vecOutputs, !include_unsafe, nullptr, nMinimumAmount, nMaximumAmount, nMinimumSumAmount, nMaximumCount, nMinDepth, nMaxDepth);
2705  }
2706 
2707  LOCK(pwallet->cs_wallet);
2708 
2709  for (const COutput& out : vecOutputs) {
2710  CTxDestination address;
2711  const CScript& scriptPubKey = out.tx->tx->vout[out.i].scriptPubKey;
2712  bool fValidAddress = ExtractDestination(scriptPubKey, address);
2713 
2714  if (destinations.size() && (!fValidAddress || !destinations.count(address)))
2715  continue;
2716 
2717  UniValue entry(UniValue::VOBJ);
2718  entry.pushKV("txid", out.tx->GetHash().GetHex());
2719  entry.pushKV("vout", out.i);
2720 
2721  if (fValidAddress) {
2722  entry.pushKV("address", EncodeDestination(address));
2723 
2724  auto i = pwallet->mapAddressBook.find(address);
2725  if (i != pwallet->mapAddressBook.end()) {
2726  entry.pushKV("label", i->second.name);
2727  }
2728 
2729  if (scriptPubKey.IsPayToScriptHash()) {
2730  const CScriptID& hash = boost::get<CScriptID>(address);
2731  CScript redeemScript;
2732  if (pwallet->GetCScript(hash, redeemScript)) {
2733  entry.pushKV("redeemScript", HexStr(redeemScript.begin(), redeemScript.end()));
2734  }
2735  }
2736  }
2737 
2738  entry.pushKV("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
2739  entry.pushKV("amount", ValueFromAmount(out.tx->tx->vout[out.i].nValue));
2740  entry.pushKV("confirmations", out.nDepth);
2741  entry.pushKV("spendable", out.fSpendable);
2742  entry.pushKV("solvable", out.fSolvable);
2743  entry.pushKV("safe", out.fSafe);
2744  results.push_back(entry);
2745  }
2746 
2747  return results;
2748 }
2749 
2750 void FundTransaction(CWallet* const pwallet, CMutableTransaction& tx, CAmount& fee_out, int& change_position, UniValue options)
2751 {
2752  // Make sure the results are valid at least up to the most recent block
2753  // the user could have gotten from another RPC command prior to now
2754  pwallet->BlockUntilSyncedToCurrentChain();
2755 
2756  CCoinControl coinControl;
2757  change_position = -1;
2758  bool lockUnspents = false;
2759  UniValue subtractFeeFromOutputs;
2760  std::set<int> setSubtractFeeFromOutputs;
2761 
2762  if (!options.isNull()) {
2763  if (options.type() == UniValue::VBOOL) {
2764  // backward compatibility bool only fallback
2765  coinControl.fAllowWatchOnly = options.get_bool();
2766  }
2767  else {
2769  RPCTypeCheckObj(options,
2770  {
2771  {"changeAddress", UniValueType(UniValue::VSTR)},
2772  {"changePosition", UniValueType(UniValue::VNUM)},
2773  {"change_type", UniValueType(UniValue::VSTR)},
2774  {"includeWatching", UniValueType(UniValue::VBOOL)},
2775  {"lockUnspents", UniValueType(UniValue::VBOOL)},
2776  {"feeRate", UniValueType()}, // will be checked below
2777  {"subtractFeeFromOutputs", UniValueType(UniValue::VARR)},
2778  {"replaceable", UniValueType(UniValue::VBOOL)},
2779  {"conf_target", UniValueType(UniValue::VNUM)},
2780  {"estimate_mode", UniValueType(UniValue::VSTR)},
2781  },
2782  true, true);
2783 
2784  if (options.exists("changeAddress")) {
2785  CTxDestination dest = DecodeDestination(options["changeAddress"].get_str());
2786 
2787  if (!IsValidDestination(dest)) {
2788  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "changeAddress must be a valid bitcoin address");
2789  }
2790 
2791  coinControl.destChange = dest;
2792  }
2793 
2794  if (options.exists("changePosition"))
2795  change_position = options["changePosition"].get_int();
2796 
2797  if (options.exists("change_type")) {
2798  if (options.exists("changeAddress")) {
2799  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both changeAddress and address_type options");
2800  }
2801  coinControl.m_change_type = pwallet->m_default_change_type;
2802  if (!ParseOutputType(options["change_type"].get_str(), *coinControl.m_change_type)) {
2803  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown change type '%s'", options["change_type"].get_str()));
2804  }
2805  }
2806 
2807  if (options.exists("includeWatching"))
2808  coinControl.fAllowWatchOnly = options["includeWatching"].get_bool();
2809 
2810  if (options.exists("lockUnspents"))
2811  lockUnspents = options["lockUnspents"].get_bool();
2812 
2813  if (options.exists("feeRate"))
2814  {
2815  coinControl.m_feerate = CFeeRate(AmountFromValue(options["feeRate"]));
2816  coinControl.fOverrideFeeRate = true;
2817  }
2818 
2819  if (options.exists("subtractFeeFromOutputs"))
2820  subtractFeeFromOutputs = options["subtractFeeFromOutputs"].get_array();
2821 
2822  if (options.exists("replaceable")) {
2823  coinControl.m_signal_bip125_rbf = options["replaceable"].get_bool();
2824  }
2825  if (options.exists("conf_target")) {
2826  if (options.exists("feeRate")) {
2827  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both conf_target and feeRate");
2828  }
2829  coinControl.m_confirm_target = ParseConfirmTarget(options["conf_target"]);
2830  }
2831  if (options.exists("estimate_mode")) {
2832  if (options.exists("feeRate")) {
2833  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and feeRate");
2834  }
2835  if (!FeeModeFromString(options["estimate_mode"].get_str(), coinControl.m_fee_mode)) {
2836  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
2837  }
2838  }
2839  }
2840  }
2841 
2842  if (tx.vout.size() == 0)
2843  throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
2844 
2845  if (change_position != -1 && (change_position < 0 || (unsigned int)change_position > tx.vout.size()))
2846  throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds");
2847 
2848  for (unsigned int idx = 0; idx < subtractFeeFromOutputs.size(); idx++) {
2849  int pos = subtractFeeFromOutputs[idx].get_int();
2850  if (setSubtractFeeFromOutputs.count(pos))
2851  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated position: %d", pos));
2852  if (pos < 0)
2853  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, negative position: %d", pos));
2854  if (pos >= int(tx.vout.size()))
2855  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, position too large: %d", pos));
2856  setSubtractFeeFromOutputs.insert(pos);
2857  }
2858 
2859  std::string strFailReason;
2860 
2861  if (!pwallet->FundTransaction(tx, fee_out, change_position, strFailReason, lockUnspents, setSubtractFeeFromOutputs, coinControl)) {
2862  throw JSONRPCError(RPC_WALLET_ERROR, strFailReason);
2863  }
2864 }
2865 
2866 static UniValue fundrawtransaction(const JSONRPCRequest& request)
2867 {
2868  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
2869  CWallet* const pwallet = wallet.get();
2870 
2871  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
2872  return NullUniValue;
2873  }
2874 
2875  if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
2876  throw std::runtime_error(
2877  "fundrawtransaction \"hexstring\" ( options iswitness )\n"
2878  "\nAdd inputs to a transaction until it has enough in value to meet its out value.\n"
2879  "This will not modify existing inputs, and will add at most one change output to the outputs.\n"
2880  "No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n"
2881  "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
2882  "The inputs added will not be signed, use signrawtransaction for that.\n"
2883  "Note that all existing inputs must have their previous output transaction be in the wallet.\n"
2884  "Note that all inputs selected must be of standard form and P2SH scripts must be\n"
2885  "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
2886  "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n"
2887  "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n"
2888  "\nArguments:\n"
2889  "1. \"hexstring\" (string, required) The hex string of the raw transaction\n"
2890  "2. options (object, optional)\n"
2891  " {\n"
2892  " \"changeAddress\" (string, optional, default pool address) The bitcoin address to receive the change\n"
2893  " \"changePosition\" (numeric, optional, default random) The index of the change output\n"
2894  " \"change_type\" (string, optional) The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -changetype.\n"
2895  " \"includeWatching\" (boolean, optional, default false) Also select inputs which are watch only\n"
2896  " \"lockUnspents\" (boolean, optional, default false) Lock selected unspent outputs\n"
2897  " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific fee rate in " + CURRENCY_UNIT + "/kB\n"
2898  " \"subtractFeeFromOutputs\" (array, optional) A json array of integers.\n"
2899  " The fee will be equally deducted from the amount of each specified output.\n"
2900  " The outputs are specified by their zero-based index, before any change output is added.\n"
2901  " Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
2902  " If no outputs are specified here, the sender pays the fee.\n"
2903  " [vout_index,...]\n"
2904  " \"replaceable\" (boolean, optional) Marks this transaction as BIP125 replaceable.\n"
2905  " Allows this transaction to be replaced by a transaction with higher fees\n"
2906  " \"conf_target\" (numeric, optional) Confirmation target (in blocks)\n"
2907  " \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
2908  " \"UNSET\"\n"
2909  " \"ECONOMICAL\"\n"
2910  " \"CONSERVATIVE\"\n"
2911  " }\n"
2912  " for backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}\n"
2913  "3. iswitness (boolean, optional) Whether the transaction hex is a serialized witness transaction \n"
2914  " If iswitness is not present, heuristic tests will be used in decoding\n"
2915 
2916  "\nResult:\n"
2917  "{\n"
2918  " \"hex\": \"value\", (string) The resulting raw transaction (hex-encoded string)\n"
2919  " \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n"
2920  " \"changepos\": n (numeric) The position of the added change output, or -1\n"
2921  "}\n"
2922  "\nExamples:\n"
2923  "\nCreate a transaction with no inputs\n"
2924  + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
2925  "\nAdd sufficient unsigned inputs to meet the output value\n"
2926  + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
2927  "\nSign the transaction\n"
2928  + HelpExampleCli("signrawtransaction", "\"fundedtransactionhex\"") +
2929  "\nSend the transaction\n"
2930  + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
2931  );
2932 
2933  RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType(), UniValue::VBOOL});
2934 
2935  // parse hex string from parameter
2937  bool try_witness = request.params[2].isNull() ? true : request.params[2].get_bool();
2938  bool try_no_witness = request.params[2].isNull() ? true : !request.params[2].get_bool();
2939  if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
2940  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
2941  }
2942 
2943  CAmount fee;
2944  int change_position;
2945  FundTransaction(pwallet, tx, fee, change_position, request.params[1]);
2946 
2947  UniValue result(UniValue::VOBJ);
2948  result.pushKV("hex", EncodeHexTx(tx));
2949  result.pushKV("fee", ValueFromAmount(fee));
2950  result.pushKV("changepos", change_position);
2951 
2952  return result;
2953 }
2954 
2956 {
2957  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
2958  CWallet* const pwallet = wallet.get();
2959 
2960  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
2961  return NullUniValue;
2962  }
2963 
2964  if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
2965  throw std::runtime_error(
2966  "signrawtransactionwithwallet \"hexstring\" ( [{\"txid\":\"id\",\"vout\":n,\"scriptPubKey\":\"hex\",\"redeemScript\":\"hex\"},...] sighashtype )\n"
2967  "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
2968  "The second optional argument (may be null) is an array of previous transaction outputs that\n"
2969  "this transaction depends on but may not yet be in the block chain.\n"
2970  + HelpRequiringPassphrase(pwallet) + "\n"
2971 
2972  "\nArguments:\n"
2973  "1. \"hexstring\" (string, required) The transaction hex string\n"
2974  "2. \"prevtxs\" (string, optional) An json array of previous dependent transaction outputs\n"
2975  " [ (json array of json objects, or 'null' if none provided)\n"
2976  " {\n"
2977  " \"txid\":\"id\", (string, required) The transaction id\n"
2978  " \"vout\":n, (numeric, required) The output number\n"
2979  " \"scriptPubKey\": \"hex\", (string, required) script key\n"
2980  " \"redeemScript\": \"hex\", (string, required for P2SH or P2WSH) redeem script\n"
2981  " \"amount\": value (numeric, required) The amount spent\n"
2982  " }\n"
2983  " ,...\n"
2984  " ]\n"
2985  "3. \"sighashtype\" (string, optional, default=ALL) The signature hash type. Must be one of\n"
2986  " \"ALL\"\n"
2987  " \"NONE\"\n"
2988  " \"SINGLE\"\n"
2989  " \"ALL|ANYONECANPAY\"\n"
2990  " \"NONE|ANYONECANPAY\"\n"
2991  " \"SINGLE|ANYONECANPAY\"\n"
2992 
2993  "\nResult:\n"
2994  "{\n"
2995  " \"hex\" : \"value\", (string) The hex-encoded raw transaction with signature(s)\n"
2996  " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
2997  " \"errors\" : [ (json array of objects) Script verification errors (if there are any)\n"
2998  " {\n"
2999  " \"txid\" : \"hash\", (string) The hash of the referenced, previous transaction\n"
3000  " \"vout\" : n, (numeric) The index of the output to spent and used as input\n"
3001  " \"scriptSig\" : \"hex\", (string) The hex-encoded signature script\n"
3002  " \"sequence\" : n, (numeric) Script sequence number\n"
3003  " \"error\" : \"text\" (string) Verification or signing error related to the input\n"
3004  " }\n"
3005  " ,...\n"
3006  " ]\n"
3007  "}\n"
3008 
3009  "\nExamples:\n"
3010  + HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"")
3011  + HelpExampleRpc("signrawtransactionwithwallet", "\"myhex\"")
3012  );
3013 
3014  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VSTR}, true);
3015 
3016  CMutableTransaction mtx;
3017  if (!DecodeHexTx(mtx, request.params[0].get_str(), true)) {
3018  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
3019  }
3020 
3021  // Sign the transaction
3022  LOCK2(cs_main, pwallet->cs_wallet);
3023  EnsureWalletIsUnlocked(pwallet);
3024 
3025  return SignTransaction(mtx, request.params[1], pwallet, false, request.params[2]);
3026 }
3027 
3028 static UniValue bumpfee(const JSONRPCRequest& request)
3029 {
3030  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3031  CWallet* const pwallet = wallet.get();
3032 
3033 
3034  if (!EnsureWalletIsAvailable(pwallet, request.fHelp))
3035  return NullUniValue;
3036 
3037  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
3038  throw std::runtime_error(
3039  "bumpfee \"txid\" ( options ) \n"
3040  "\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n"
3041  "An opt-in RBF transaction with the given txid must be in the wallet.\n"
3042  "The command will pay the additional fee by decreasing (or perhaps removing) its change output.\n"
3043  "If the change output is not big enough to cover the increased fee, the command will currently fail\n"
3044  "instead of adding new inputs to compensate. (A future implementation could improve this.)\n"
3045  "The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n"
3046  "By default, the new fee will be calculated automatically using estimatesmartfee.\n"
3047  "The user can specify a confirmation target for estimatesmartfee.\n"
3048  "Alternatively, the user can specify totalFee, or use RPC settxfee to set a higher fee rate.\n"
3049  "At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n"
3050  "returned by getnetworkinfo) to enter the node's mempool.\n"
3051  "\nArguments:\n"
3052  "1. txid (string, required) The txid to be bumped\n"
3053  "2. options (object, optional)\n"
3054  " {\n"
3055  " \"confTarget\" (numeric, optional) Confirmation target (in blocks)\n"
3056  " \"totalFee\" (numeric, optional) Total fee (NOT feerate) to pay, in satoshis.\n"
3057  " In rare cases, the actual fee paid might be slightly higher than the specified\n"
3058  " totalFee if the tx change output has to be removed because it is too close to\n"
3059  " the dust threshold.\n"
3060  " \"replaceable\" (boolean, optional, default true) Whether the new transaction should still be\n"
3061  " marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n"
3062  " be left unchanged from the original. If false, any input sequence numbers in the\n"
3063  " original transaction that were less than 0xfffffffe will be increased to 0xfffffffe\n"
3064  " so the new transaction will not be explicitly bip-125 replaceable (though it may\n"
3065  " still be replaceable in practice, for example if it has unconfirmed ancestors which\n"
3066  " are replaceable).\n"
3067  " \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
3068  " \"UNSET\"\n"
3069  " \"ECONOMICAL\"\n"
3070  " \"CONSERVATIVE\"\n"
3071  " }\n"
3072  "\nResult:\n"
3073  "{\n"
3074  " \"txid\": \"value\", (string) The id of the new transaction\n"
3075  " \"origfee\": n, (numeric) Fee of the replaced transaction\n"
3076  " \"fee\": n, (numeric) Fee of the new transaction\n"
3077  " \"errors\": [ str... ] (json array of strings) Errors encountered during processing (may be empty)\n"
3078  "}\n"
3079  "\nExamples:\n"
3080  "\nBump the fee, get the new transaction\'s txid\n" +
3081  HelpExampleCli("bumpfee", "<txid>"));
3082  }
3083 
3084  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VOBJ});
3085  uint256 hash(ParseHashV(request.params[0], "txid"));
3086 
3087  // optional parameters
3088  CAmount totalFee = 0;
3089  CCoinControl coin_control;
3090  coin_control.m_signal_bip125_rbf = true;
3091  if (!request.params[1].isNull()) {
3092  UniValue options = request.params[1];
3093  RPCTypeCheckObj(options,
3094  {
3095  {"confTarget", UniValueType(UniValue::VNUM)},
3096  {"totalFee", UniValueType(UniValue::VNUM)},
3097  {"replaceable", UniValueType(UniValue::VBOOL)},
3098  {"estimate_mode", UniValueType(UniValue::VSTR)},
3099  },
3100  true, true);
3101 
3102  if (options.exists("confTarget") && options.exists("totalFee")) {
3103  throw JSONRPCError(RPC_INVALID_PARAMETER, "confTarget and totalFee options should not both be set. Please provide either a confirmation target for fee estimation or an explicit total fee for the transaction.");
3104  } else if (options.exists("confTarget")) { // TODO: alias this to conf_target
3105  coin_control.m_confirm_target = ParseConfirmTarget(options["confTarget"]);
3106  } else if (options.exists("totalFee")) {
3107  totalFee = options["totalFee"].get_int64();
3108  if (totalFee <= 0) {
3109  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid totalFee %s (must be greater than 0)", FormatMoney(totalFee)));
3110  }
3111  }
3112 
3113  if (options.exists("replaceable")) {
3114  coin_control.m_signal_bip125_rbf = options["replaceable"].get_bool();
3115  }
3116  if (options.exists("estimate_mode")) {
3117  if (!FeeModeFromString(options["estimate_mode"].get_str(), coin_control.m_fee_mode)) {
3118  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid estimate_mode parameter");
3119  }
3120  }
3121  }
3122 
3123  // Make sure the results are valid at least up to the most recent block
3124  // the user could have gotten from another RPC command prior to now
3125  pwallet->BlockUntilSyncedToCurrentChain();
3126 
3127  LOCK2(cs_main, pwallet->cs_wallet);
3128  EnsureWalletIsUnlocked(pwallet);
3129 
3130 
3131  std::vector<std::string> errors;
3132  CAmount old_fee;
3133  CAmount new_fee;
3134  CMutableTransaction mtx;
3135  feebumper::Result res = feebumper::CreateTransaction(pwallet, hash, coin_control, totalFee, errors, old_fee, new_fee, mtx);
3136  if (res != feebumper::Result::OK) {
3137  switch(res) {
3139  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errors[0]);
3140  break;
3142  throw JSONRPCError(RPC_INVALID_REQUEST, errors[0]);
3143  break;
3145  throw JSONRPCError(RPC_INVALID_PARAMETER, errors[0]);
3146  break;
3148  throw JSONRPCError(RPC_WALLET_ERROR, errors[0]);
3149  break;
3150  default:
3151  throw JSONRPCError(RPC_MISC_ERROR, errors[0]);
3152  break;
3153  }
3154  }
3155 
3156  // sign bumped transaction
3157  if (!feebumper::SignTransaction(pwallet, mtx)) {
3158  throw JSONRPCError(RPC_WALLET_ERROR, "Can't sign transaction.");
3159  }
3160  // commit the bumped transaction
3161  uint256 txid;
3162  if (feebumper::CommitTransaction(pwallet, hash, std::move(mtx), errors, txid) != feebumper::Result::OK) {
3163  throw JSONRPCError(RPC_WALLET_ERROR, errors[0]);
3164  }
3165  UniValue result(UniValue::VOBJ);
3166  result.pushKV("txid", txid.GetHex());
3167  result.pushKV("origfee", ValueFromAmount(old_fee));
3168  result.pushKV("fee", ValueFromAmount(new_fee));
3169  UniValue result_errors(UniValue::VARR);
3170  for (const std::string& error : errors) {
3171  result_errors.push_back(error);
3172  }
3173  result.pushKV("errors", result_errors);
3174 
3175  return result;
3176 }
3177 
3179 {
3180  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3181  CWallet* const pwallet = wallet.get();
3182 
3183 
3184  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3185  return NullUniValue;
3186  }
3187 
3188  if (request.fHelp || request.params.size() < 1 || request.params.size() > 2) {
3189  throw std::runtime_error(
3190  "generate nblocks ( maxtries )\n"
3191  "\nMine up to nblocks blocks immediately (before the RPC call returns) to an address in the wallet.\n"
3192  "\nArguments:\n"
3193  "1. nblocks (numeric, required) How many blocks are generated immediately.\n"
3194  "2. maxtries (numeric, optional) How many iterations to try (default = 1000000).\n"
3195  "\nResult:\n"
3196  "[ blockhashes ] (array) hashes of blocks generated\n"
3197  "\nExamples:\n"
3198  "\nGenerate 11 blocks\n"
3199  + HelpExampleCli("generate", "11")
3200  );
3201  }
3202 
3203  if (!IsDeprecatedRPCEnabled("generate")) {
3204  throw JSONRPCError(RPC_METHOD_DEPRECATED, "The wallet generate rpc method is deprecated and will be fully removed in v0.19. "
3205  "To use generate in v0.18, restart bsha3d with -deprecatedrpc=generate.\n"
3206  "Clients should transition to using the node rpc method generatetoaddress\n");
3207  }
3208 
3209  int num_generate = request.params[0].get_int();
3210  uint64_t max_tries = 1000000;
3211  if (!request.params[1].isNull()) {
3212  max_tries = request.params[1].get_int();
3213  }
3214 
3215  std::shared_ptr<CReserveScript> coinbase_script;
3216  pwallet->GetScriptForMining(coinbase_script);
3217 
3218  // If the keypool is exhausted, no script is returned at all. Catch this.
3219  if (!coinbase_script) {
3220  throw JSONRPCError(RPC_WALLET_KEYPOOL_RAN_OUT, "Error: Keypool ran out, please call keypoolrefill first");
3221  }
3222 
3223  //throw an error if no script was provided
3224  if (coinbase_script->reserveScript.empty()) {
3225  throw JSONRPCError(RPC_INTERNAL_ERROR, "No coinbase script available");
3226  }
3227 
3228  return generateBlocks(coinbase_script, num_generate, max_tries, true);
3229 }
3230 
3232 {
3233  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3234  CWallet* const pwallet = wallet.get();
3235 
3236  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3237  return NullUniValue;
3238  }
3239 
3240  if (request.fHelp || request.params.size() > 2) {
3241  throw std::runtime_error(
3242  "rescanblockchain (\"start_height\") (\"stop_height\")\n"
3243  "\nRescan the local blockchain for wallet related transactions.\n"
3244  "\nArguments:\n"
3245  "1. \"start_height\" (numeric, optional) block height where the rescan should start\n"
3246  "2. \"stop_height\" (numeric, optional) the last block height that should be scanned\n"
3247  "\nResult:\n"
3248  "{\n"
3249  " \"start_height\" (numeric) The block height where the rescan has started. If omitted, rescan started from the genesis block.\n"
3250  " \"stop_height\" (numeric) The height of the last rescanned block. If omitted, rescan stopped at the chain tip.\n"
3251  "}\n"
3252  "\nExamples:\n"
3253  + HelpExampleCli("rescanblockchain", "100000 120000")
3254  + HelpExampleRpc("rescanblockchain", "100000, 120000")
3255  );
3256  }
3257 
3258  WalletRescanReserver reserver(pwallet);
3259  if (!reserver.reserve()) {
3260  throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
3261  }
3262 
3263  CBlockIndex *pindexStart = nullptr;
3264  CBlockIndex *pindexStop = nullptr;
3265  CBlockIndex *pChainTip = nullptr;
3266  {
3267  LOCK(cs_main);
3268  pindexStart = chainActive.Genesis();
3269  pChainTip = chainActive.Tip();
3270 
3271  if (!request.params[0].isNull()) {
3272  pindexStart = chainActive[request.params[0].get_int()];
3273  if (!pindexStart) {
3274  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid start_height");
3275  }
3276  }
3277 
3278  if (!request.params[1].isNull()) {
3279  pindexStop = chainActive[request.params[1].get_int()];
3280  if (!pindexStop) {
3281  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid stop_height");
3282  }
3283  else if (pindexStop->nHeight < pindexStart->nHeight) {
3284  throw JSONRPCError(RPC_INVALID_PARAMETER, "stop_height must be greater than start_height");
3285  }
3286  }
3287  }
3288 
3289  // We can't rescan beyond non-pruned blocks, stop and throw an error
3290  if (fPruneMode) {
3291  LOCK(cs_main);
3292  CBlockIndex *block = pindexStop ? pindexStop : pChainTip;
3293  while (block && block->nHeight >= pindexStart->nHeight) {
3294  if (!(block->nStatus & BLOCK_HAVE_DATA)) {
3295  throw JSONRPCError(RPC_MISC_ERROR, "Can't rescan beyond pruned data. Use RPC call getblockchaininfo to determine your pruned height.");
3296  }
3297  block = block->pprev;
3298  }
3299  }
3300 
3301  CBlockIndex *stopBlock = pwallet->ScanForWalletTransactions(pindexStart, pindexStop, reserver, true);
3302  if (!stopBlock) {
3303  if (pwallet->IsAbortingRescan()) {
3304  throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted.");
3305  }
3306  // if we got a nullptr returned, ScanForWalletTransactions did rescan up to the requested stopindex
3307  stopBlock = pindexStop ? pindexStop : pChainTip;
3308  }
3309  else {
3310  throw JSONRPCError(RPC_MISC_ERROR, "Rescan failed. Potentially corrupted data files.");
3311  }
3312  UniValue response(UniValue::VOBJ);
3313  response.pushKV("start_height", pindexStart->nHeight);
3314  response.pushKV("stop_height", stopBlock->nHeight);
3315  return response;
3316 }
3317 
3318 class DescribeWalletAddressVisitor : public boost::static_visitor<UniValue>
3319 {
3320 public:
3321  CWallet * const pwallet;
3322 
3323  void ProcessSubScript(const CScript& subscript, UniValue& obj, bool include_addresses = false) const
3324  {
3325  // Always present: script type and redeemscript
3326  std::vector<std::vector<unsigned char>> solutions_data;
3327  txnouttype which_type = Solver(subscript, solutions_data);
3328  obj.pushKV("script", GetTxnOutputType(which_type));
3329  obj.pushKV("hex", HexStr(subscript.begin(), subscript.end()));
3330 
3331  CTxDestination embedded;
3333  if (ExtractDestination(subscript, embedded)) {
3334  // Only when the script corresponds to an address.
3335  UniValue subobj(UniValue::VOBJ);
3336  UniValue detail = DescribeAddress(embedded);
3337  subobj.pushKVs(detail);
3338  UniValue wallet_detail = boost::apply_visitor(*this, embedded);
3339  subobj.pushKVs(wallet_detail);
3340  subobj.pushKV("address", EncodeDestination(embedded));
3341  subobj.pushKV("scriptPubKey", HexStr(subscript.begin(), subscript.end()));
3342  // Always report the pubkey at the top level, so that `getnewaddress()['pubkey']` always works.
3343  if (subobj.exists("pubkey")) obj.pushKV("pubkey", subobj["pubkey"]);
3344  obj.pushKV("embedded", std::move(subobj));
3345  if (include_addresses) a.push_back(EncodeDestination(embedded));
3346  } else if (which_type == TX_MULTISIG) {
3347  // Also report some information on multisig scripts (which do not have a corresponding address).
3348  // TODO: abstract out the common functionality between this logic and ExtractDestinations.
3349  obj.pushKV("sigsrequired", solutions_data[0][0]);
3350  UniValue pubkeys(UniValue::VARR);
3351  for (size_t i = 1; i < solutions_data.size() - 1; ++i) {
3352  CPubKey key(solutions_data[i].begin(), solutions_data[i].end());
3353  if (include_addresses) a.push_back(EncodeDestination(key.GetID()));
3354  pubkeys.push_back(HexStr(key.begin(), key.end()));
3355  }
3356  obj.pushKV("pubkeys", std::move(pubkeys));
3357  }
3358 
3359  // The "addresses" field is confusing because it refers to public keys using their P2PKH address.
3360  // For that reason, only add the 'addresses' field when needed for backward compatibility. New applications
3361  // can use the 'embedded'->'address' field for P2SH or P2WSH wrapped addresses, and 'pubkeys' for
3362  // inspecting multisig participants.
3363  if (include_addresses) obj.pushKV("addresses", std::move(a));
3364  }
3365 
3366  explicit DescribeWalletAddressVisitor(CWallet* _pwallet) : pwallet(_pwallet) {}
3367 
3369 
3370  UniValue operator()(const CKeyID& keyID) const
3371  {
3372  UniValue obj(UniValue::VOBJ);
3373  CPubKey vchPubKey;
3374  if (pwallet && pwallet->GetPubKey(keyID, vchPubKey)) {
3375  obj.pushKV("pubkey", HexStr(vchPubKey));
3376  obj.pushKV("iscompressed", vchPubKey.IsCompressed());
3377  }
3378  return obj;
3379  }
3380 
3381  UniValue operator()(const CScriptID& scriptID) const
3382  {
3383  UniValue obj(UniValue::VOBJ);
3384  CScript subscript;
3385  if (pwallet && pwallet->GetCScript(scriptID, subscript)) {
3386  ProcessSubScript(subscript, obj, IsDeprecatedRPCEnabled("validateaddress"));
3387  }
3388  return obj;
3389  }
3390 
3392  {
3393  UniValue obj(UniValue::VOBJ);
3394  CPubKey pubkey;
3395  if (pwallet && pwallet->GetPubKey(CKeyID(id), pubkey)) {
3396  obj.pushKV("pubkey", HexStr(pubkey));
3397  }
3398  return obj;
3399  }
3400 
3402  {
3403  UniValue obj(UniValue::VOBJ);
3404  CScript subscript;
3405  CRIPEMD160 hasher;
3406  uint160 hash;
3407  hasher.Write(id.begin(), 32).Finalize(hash.begin());
3408  if (pwallet && pwallet->GetCScript(CScriptID(hash), subscript)) {
3409  ProcessSubScript(subscript, obj);
3410  }
3411  return obj;
3412  }
3413 
3415 };
3416 
3417 static UniValue DescribeWalletAddress(CWallet* pwallet, const CTxDestination& dest)
3418 {
3420  UniValue detail = DescribeAddress(dest);
3421  ret.pushKVs(detail);
3422  ret.pushKVs(boost::apply_visitor(DescribeWalletAddressVisitor(pwallet), dest));
3423  return ret;
3424 }
3425 
3427 static UniValue AddressBookDataToJSON(const CAddressBookData& data, const bool verbose)
3428 {
3430  if (verbose) {
3431  ret.pushKV("name", data.name);
3432  }
3433  ret.pushKV("purpose", data.purpose);
3434  return ret;
3435 }
3436 
3438 {
3439  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3440  CWallet* const pwallet = wallet.get();
3441 
3442  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3443  return NullUniValue;
3444  }
3445 
3446  if (request.fHelp || request.params.size() != 1) {
3447  throw std::runtime_error(
3448  "getaddressinfo \"address\"\n"
3449  "\nReturn information about the given bitcoin address. Some information requires the address\n"
3450  "to be in the wallet.\n"
3451  "\nArguments:\n"
3452  "1. \"address\" (string, required) The bitcoin address to get the information of.\n"
3453  "\nResult:\n"
3454  "{\n"
3455  " \"address\" : \"address\", (string) The bitcoin address validated\n"
3456  " \"scriptPubKey\" : \"hex\", (string) The hex-encoded scriptPubKey generated by the address\n"
3457  " \"ismine\" : true|false, (boolean) If the address is yours or not\n"
3458  " \"solvable\" : true|false, (boolean) If the address is solvable by the wallet\n"
3459  " \"iswatchonly\" : true|false, (boolean) If the address is watchonly\n"
3460  " \"isscript\" : true|false, (boolean) If the key is a script\n"
3461  " \"iswitness\" : true|false, (boolean) If the address is a witness address\n"
3462  " \"witness_version\" : version (numeric, optional) The version number of the witness program\n"
3463  " \"witness_program\" : \"hex\" (string, optional) The hex value of the witness program\n"
3464  " \"script\" : \"type\" (string, optional) The output script type. Only if \"isscript\" is true and the redeemscript is known. Possible types: nonstandard, pubkey, pubkeyhash, scripthash, multisig, nulldata, witness_v0_keyhash, witness_v0_scripthash, witness_unknown\n"
3465  " \"hex\" : \"hex\", (string, optional) The redeemscript for the p2sh address\n"
3466  " \"pubkeys\" (string, optional) Array of pubkeys associated with the known redeemscript (only if \"script\" is \"multisig\")\n"
3467  " [\n"
3468  " \"pubkey\"\n"
3469  " ,...\n"
3470  " ]\n"
3471  " \"sigsrequired\" : xxxxx (numeric, optional) Number of signatures required to spend multisig output (only if \"script\" is \"multisig\")\n"
3472  " \"pubkey\" : \"publickeyhex\", (string, optional) The hex value of the raw public key, for single-key addresses (possibly embedded in P2SH or P2WSH)\n"
3473  " \"embedded\" : {...}, (object, optional) Information about the address embedded in P2SH or P2WSH, if relevant and known. It includes all getaddressinfo output fields for the embedded address, excluding metadata (\"timestamp\", \"hdkeypath\", \"hdseedid\") and relation to the wallet (\"ismine\", \"iswatchonly\").\n"
3474  " \"iscompressed\" : true|false, (boolean) If the address is compressed\n"
3475  " \"label\" : \"label\" (string) The label associated with the address, \"\" is the default label\n"
3476  " \"timestamp\" : timestamp, (number, optional) The creation time of the key if available in seconds since epoch (Jan 1 1970 GMT)\n"
3477  " \"hdkeypath\" : \"keypath\" (string, optional) The HD keypath if the key is HD and available\n"
3478  " \"hdseedid\" : \"<hash360>\" (string, optional) The Hash360 of the HD seed\n"
3479  " \"hdmasterkeyid\" : \"<hash360>\" (string, optional) alias for hdseedid maintained for backwards compatibility. Will be removed in V0.18.\n"
3480  " \"labels\" (object) Array of labels associated with the address.\n"
3481  " [\n"
3482  " { (json object of label data)\n"
3483  " \"name\": \"labelname\" (string) The label\n"
3484  " \"purpose\": \"string\" (string) Purpose of address (\"send\" for sending address, \"receive\" for receiving address)\n"
3485  " },...\n"
3486  " ]\n"
3487  "}\n"
3488  "\nExamples:\n"
3489  + HelpExampleCli("getaddressinfo", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
3490  + HelpExampleRpc("getaddressinfo", "\"1PSSGeFHDnKNxiEyFrD1wcEaHr9hrQDDWc\"")
3491  );
3492  }
3493 
3494  LOCK(pwallet->cs_wallet);
3495 
3497  CTxDestination dest = DecodeDestination(request.params[0].get_str());
3498 
3499  // Make sure the destination is valid
3500  if (!IsValidDestination(dest)) {
3501  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
3502  }
3503 
3504  std::string currentAddress = EncodeDestination(dest);
3505  ret.pushKV("address", currentAddress);
3506 
3507  CScript scriptPubKey = GetScriptForDestination(dest);
3508  ret.pushKV("scriptPubKey", HexStr(scriptPubKey.begin(), scriptPubKey.end()));
3509 
3510  isminetype mine = IsMine(*pwallet, dest);
3511  ret.pushKV("ismine", bool(mine & ISMINE_SPENDABLE));
3512  ret.pushKV("iswatchonly", bool(mine & ISMINE_WATCH_ONLY));
3513  ret.pushKV("solvable", IsSolvable(*pwallet, scriptPubKey));
3514  UniValue detail = DescribeWalletAddress(pwallet, dest);
3515  ret.pushKVs(detail);
3516  if (pwallet->mapAddressBook.count(dest)) {
3517  ret.pushKV("label", pwallet->mapAddressBook[dest].name);
3518  }
3519  const CKeyMetadata* meta = nullptr;
3520  CKeyID key_id = GetKeyForDestination(*pwallet, dest);
3521  if (!key_id.IsNull()) {
3522  auto it = pwallet->mapKeyMetadata.find(key_id);
3523  if (it != pwallet->mapKeyMetadata.end()) {
3524  meta = &it->second;
3525  }
3526  }
3527  if (!meta) {
3528  auto it = pwallet->m_script_metadata.find(CScriptID(scriptPubKey));
3529  if (it != pwallet->m_script_metadata.end()) {
3530  meta = &it->second;
3531  }
3532  }
3533  if (meta) {
3534  ret.pushKV("timestamp", meta->nCreateTime);
3535  if (!meta->hdKeypath.empty()) {
3536  ret.pushKV("hdkeypath", meta->hdKeypath);
3537  ret.pushKV("hdseedid", meta->hd_seed_id.GetHex());
3538  ret.pushKV("hdmasterkeyid", meta->hd_seed_id.GetHex());
3539  }
3540  }
3541 
3542  // Currently only one label can be associated with an address, return an array
3543  // so the API remains stable if we allow multiple labels to be associated with
3544  // an address.
3545  UniValue labels(UniValue::VARR);
3546  std::map<CTxDestination, CAddressBookData>::iterator mi = pwallet->mapAddressBook.find(dest);
3547  if (mi != pwallet->mapAddressBook.end()) {
3548  labels.push_back(AddressBookDataToJSON(mi->second, true));
3549  }
3550  ret.pushKV("labels", std::move(labels));
3551 
3552  return ret;
3553 }
3554 
3555 static UniValue getaddressesbylabel(const JSONRPCRequest& request)
3556 {
3557  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3558  CWallet* const pwallet = wallet.get();
3559 
3560  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3561  return NullUniValue;
3562  }
3563 
3564  if (request.fHelp || request.params.size() != 1)
3565  throw std::runtime_error(
3566  "getaddressesbylabel \"label\"\n"
3567  "\nReturns the list of addresses assigned the specified label.\n"
3568  "\nArguments:\n"
3569  "1. \"label\" (string, required) The label.\n"
3570  "\nResult:\n"
3571  "{ (json object with addresses as keys)\n"
3572  " \"address\": { (json object with information about address)\n"
3573  " \"purpose\": \"string\" (string) Purpose of address (\"send\" for sending address, \"receive\" for receiving address)\n"
3574  " },...\n"
3575  "}\n"
3576  "\nExamples:\n"
3577  + HelpExampleCli("getaddressesbylabel", "\"tabby\"")
3578  + HelpExampleRpc("getaddressesbylabel", "\"tabby\"")
3579  );
3580 
3581  LOCK(pwallet->cs_wallet);
3582 
3583  std::string label = LabelFromValue(request.params[0]);
3584 
3585  // Find all addresses that have the given label
3587  for (const std::pair<const CTxDestination, CAddressBookData>& item : pwallet->mapAddressBook) {
3588  if (item.second.name == label) {
3589  ret.pushKV(EncodeDestination(item.first), AddressBookDataToJSON(item.second, false));
3590  }
3591  }
3592 
3593  if (ret.empty()) {
3594  throw JSONRPCError(RPC_WALLET_INVALID_LABEL_NAME, std::string("No addresses with label " + label));
3595  }
3596 
3597  return ret;
3598 }
3599 
3600 static UniValue listlabels(const JSONRPCRequest& request)
3601 {
3602  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3603  CWallet* const pwallet = wallet.get();
3604 
3605  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3606  return NullUniValue;
3607  }
3608 
3609  if (request.fHelp || request.params.size() > 1)
3610  throw std::runtime_error(
3611  "listlabels ( \"purpose\" )\n"
3612  "\nReturns the list of all labels, or labels that are assigned to addresses with a specific purpose.\n"
3613  "\nArguments:\n"
3614  "1. \"purpose\" (string, optional) Address purpose to list labels for ('send','receive'). An empty string is the same as not providing this argument.\n"
3615  "\nResult:\n"
3616  "[ (json array of string)\n"
3617  " \"label\", (string) Label name\n"
3618  " ...\n"
3619  "]\n"
3620  "\nExamples:\n"
3621  "\nList all labels\n"
3622  + HelpExampleCli("listlabels", "") +
3623  "\nList labels that have receiving addresses\n"
3624  + HelpExampleCli("listlabels", "receive") +
3625  "\nList labels that have sending addresses\n"
3626  + HelpExampleCli("listlabels", "send") +
3627  "\nAs a JSON-RPC call\n"
3628  + HelpExampleRpc("listlabels", "receive")
3629  );
3630 
3631  LOCK(pwallet->cs_wallet);
3632 
3633  std::string purpose;
3634  if (!request.params[0].isNull()) {
3635  purpose = request.params[0].get_str();
3636  }
3637 
3638  // Add to a set to sort by label name, then insert into Univalue array
3639  std::set<std::string> label_set;
3640  for (const std::pair<const CTxDestination, CAddressBookData>& entry : pwallet->mapAddressBook) {
3641  if (purpose.empty() || entry.second.purpose == purpose) {
3642  label_set.insert(entry.second.name);
3643  }
3644  }
3645 
3647  for (const std::string& name : label_set) {
3648  ret.push_back(name);
3649  }
3650 
3651  return ret;
3652 }
3653 
3655 {
3656  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3657  CWallet* const pwallet = wallet.get();
3658 
3659  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3660  return NullUniValue;
3661  }
3662 
3663  if (request.fHelp || request.params.size() > 2) {
3664  throw std::runtime_error(
3665  "sethdseed ( \"newkeypool\" \"seed\" )\n"
3666  "\nSet or generate a new HD wallet seed. Non-HD wallets will not be upgraded to being a HD wallet. Wallets that are already\n"
3667  "HD will have a new HD seed set so that new keys added to the keypool will be derived from this new seed.\n"
3668  "\nNote that you will need to MAKE A NEW BACKUP of your wallet after setting the HD wallet seed.\n"
3669  + HelpRequiringPassphrase(pwallet) +
3670  "\nArguments:\n"
3671  "1. \"newkeypool\" (boolean, optional, default=true) Whether to flush old unused addresses, including change addresses, from the keypool and regenerate it.\n"
3672  " If true, the next address from getnewaddress and change address from getrawchangeaddress will be from this new seed.\n"
3673  " If false, addresses (including change addresses if the wallet already had HD Chain Split enabled) from the existing\n"
3674  " keypool will be used until it has been depleted.\n"
3675  "2. \"seed\" (string, optional) The WIF private key to use as the new HD seed; if not provided a random seed will be used.\n"
3676  " The seed value can be retrieved using the dumpwallet command. It is the private key marked hdseed=1\n"
3677  "\nExamples:\n"
3678  + HelpExampleCli("sethdseed", "")
3679  + HelpExampleCli("sethdseed", "false")
3680  + HelpExampleCli("sethdseed", "true \"wifkey\"")
3681  + HelpExampleRpc("sethdseed", "true, \"wifkey\"")
3682  );
3683  }
3684 
3685  if (IsInitialBlockDownload()) {
3686  throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Cannot set a new HD seed while still in Initial Block Download");
3687  }
3688 
3689  LOCK2(cs_main, pwallet->cs_wallet);
3690 
3691  // Do not do anything to non-HD wallets
3692  if (!pwallet->IsHDEnabled()) {
3693  throw JSONRPCError(RPC_WALLET_ERROR, "Cannot set a HD seed on a non-HD wallet. Start with -upgradewallet in order to upgrade a non-HD wallet to HD");
3694  }
3695 
3696  EnsureWalletIsUnlocked(pwallet);
3697 
3698  bool flush_key_pool = true;
3699  if (!request.params[0].isNull()) {
3700  flush_key_pool = request.params[0].get_bool();
3701  }
3702 
3703  CPubKey master_pub_key;
3704  if (request.params[1].isNull()) {
3705  master_pub_key = pwallet->GenerateNewSeed();
3706  } else {
3707  CKey key = DecodeSecret(request.params[1].get_str());
3708  if (!key.IsValid()) {
3709  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
3710  }
3711 
3712  if (HaveKey(*pwallet, key)) {
3713  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key (either as an HD seed or as a loose private key)");
3714  }
3715 
3716  master_pub_key = pwallet->DeriveNewSeed(key);
3717  }
3718 
3719  pwallet->SetHDSeed(master_pub_key);
3720  if (flush_key_pool) pwallet->NewKeyPool();
3721 
3722  return NullUniValue;
3723 }
3724 
3725 void AddKeypathToMap(const CWallet* pwallet, const CKeyID& keyID, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
3726 {
3727  CPubKey vchPubKey;
3728  if (!pwallet->GetPubKey(keyID, vchPubKey)) {
3729  return;
3730  }
3731  KeyOriginInfo info;
3732  if (!pwallet->GetKeyOrigin(keyID, info)) {
3733  throw JSONRPCError(RPC_INTERNAL_ERROR, "Internal keypath is broken");
3734  }
3735  hd_keypaths.emplace(vchPubKey, std::move(info));
3736 }
3737 
3738 bool FillPSBT(const CWallet* pwallet, PartiallySignedTransaction& psbtx, const CTransaction* txConst, int sighash_type, bool sign, bool bip32derivs)
3739 {
3740  LOCK(pwallet->cs_wallet);
3741  // Get all of the previous transactions
3742  bool complete = true;
3743  for (unsigned int i = 0; i < txConst->vin.size(); ++i) {
3744  const CTxIn& txin = txConst->vin[i];
3745  PSBTInput& input = psbtx.inputs.at(i);
3746 
3747  // If we don't know about this input, skip it and let someone else deal with it
3748  const uint256& txhash = txin.prevout.hash;
3749  const auto it = pwallet->mapWallet.find(txhash);
3750  if (it != pwallet->mapWallet.end()) {
3751  const CWalletTx& wtx = it->second;
3752  CTxOut utxo = wtx.tx->vout[txin.prevout.n];
3753  // Update both UTXOs from the wallet.
3754  input.non_witness_utxo = wtx.tx;
3755  input.witness_utxo = utxo;
3756  }
3757 
3758  // Get the Sighash type
3759  if (sign && input.sighash_type > 0 && input.sighash_type != sighash_type) {
3760  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Specified Sighash and sighash in PSBT do not match.");
3761  }
3762 
3763  complete &= SignPSBTInput(HidingSigningProvider(pwallet, !sign, !bip32derivs), *psbtx.tx, input, i, sighash_type);
3764  }
3765 
3766  // Fill in the bip32 keypaths and redeemscripts for the outputs so that hardware wallets can identify change
3767  for (unsigned int i = 0; i < txConst->vout.size(); ++i) {
3768  const CTxOut& out = txConst->vout.at(i);
3769  PSBTOutput& psbt_out = psbtx.outputs.at(i);
3770 
3771  // Fill a SignatureData with output info
3772  SignatureData sigdata;
3773  psbt_out.FillSignatureData(sigdata);
3774 
3775  MutableTransactionSignatureCreator creator(psbtx.tx.get_ptr(), 0, out.nValue, 1);
3776  ProduceSignature(HidingSigningProvider(pwallet, true, !bip32derivs), creator, out.scriptPubKey, sigdata);
3777  psbt_out.FromSignatureData(sigdata);
3778  }
3779  return complete;
3780 }
3781 
3783 {
3784  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3785  CWallet* const pwallet = wallet.get();
3786 
3787  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3788  return NullUniValue;
3789  }
3790 
3791  if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
3792  throw std::runtime_error(
3793  "walletprocesspsbt \"psbt\" ( sign \"sighashtype\" bip32derivs )\n"
3794  "\nUpdate a PSBT with input information from our wallet and then sign inputs\n"
3795  "that we can sign for.\n"
3796  + HelpRequiringPassphrase(pwallet) + "\n"
3797 
3798  "\nArguments:\n"
3799  "1. \"psbt\" (string, required) The transaction base64 string\n"
3800  "2. sign (boolean, optional, default=true) Also sign the transaction when updating\n"
3801  "3. \"sighashtype\" (string, optional, default=ALL) The signature hash type to sign with if not specified by the PSBT. Must be one of\n"
3802  " \"ALL\"\n"
3803  " \"NONE\"\n"
3804  " \"SINGLE\"\n"
3805  " \"ALL|ANYONECANPAY\"\n"
3806  " \"NONE|ANYONECANPAY\"\n"
3807  " \"SINGLE|ANYONECANPAY\"\n"
3808  "4. bip32derivs (boolean, optional, default=false) If true, includes the BIP 32 derivation paths for public keys if we know them\n"
3809 
3810  "\nResult:\n"
3811  "{\n"
3812  " \"psbt\" : \"value\", (string) The base64-encoded partially signed transaction\n"
3813  " \"complete\" : true|false, (boolean) If the transaction has a complete set of signatures\n"
3814  " ]\n"
3815  "}\n"
3816 
3817  "\nExamples:\n"
3818  + HelpExampleCli("walletprocesspsbt", "\"psbt\"")
3819  );
3820 
3821  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VBOOL, UniValue::VSTR});
3822 
3823  // Unserialize the transaction
3825  std::string error;
3826  if (!DecodePSBT(psbtx, request.params[0].get_str(), error)) {
3827  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
3828  }
3829 
3830  // Get the sighash type
3831  int nHashType = ParseSighashString(request.params[2]);
3832 
3833  // Use CTransaction for the constant parts of the
3834  // transaction to avoid rehashing.
3835  const CTransaction txConst(*psbtx.tx);
3836 
3837  // Fill transaction with our data and also sign
3838  bool sign = request.params[1].isNull() ? true : request.params[1].get_bool();
3839  bool bip32derivs = request.params[3].isNull() ? false : request.params[3].get_bool();
3840  bool complete = FillPSBT(pwallet, psbtx, &txConst, nHashType, sign, bip32derivs);
3841 
3842  UniValue result(UniValue::VOBJ);
3843  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
3844  ssTx << psbtx;
3845  result.pushKV("psbt", EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()));
3846  result.pushKV("complete", complete);
3847 
3848  return result;
3849 }
3850 
3852 {
3853  std::shared_ptr<CWallet> const wallet = GetWalletForJSONRPCRequest(request);
3854  CWallet* const pwallet = wallet.get();
3855 
3856  if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
3857  return NullUniValue;
3858  }
3859 
3860  if (request.fHelp || request.params.size() < 2 || request.params.size() > 5)
3861  throw std::runtime_error(
3862  "walletcreatefundedpsbt [{\"txid\":\"id\",\"vout\":n},...] [{\"address\":amount},{\"data\":\"hex\"},...] ( locktime ) ( replaceable ) ( options bip32derivs )\n"
3863  "\nCreates and funds a transaction in the Partially Signed Transaction format. Inputs will be added if supplied inputs are not enough\n"
3864  "Implements the Creator and Updater roles.\n"
3865  "\nArguments:\n"
3866  "1. \"inputs\" (array, required) A json array of json objects\n"
3867  " [\n"
3868  " {\n"
3869  " \"txid\":\"id\", (string, required) The transaction id\n"
3870  " \"vout\":n, (numeric, required) The output number\n"
3871  " \"sequence\":n (numeric, optional) The sequence number\n"
3872  " } \n"
3873  " ,...\n"
3874  " ]\n"
3875  "2. \"outputs\" (array, required) a json array with outputs (key-value pairs)\n"
3876  " [\n"
3877  " {\n"
3878  " \"address\": x.xxx, (obj, optional) A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + "\n"
3879  " },\n"
3880  " {\n"
3881  " \"data\": \"hex\" (obj, optional) A key-value pair. The key must be \"data\", the value is hex-encoded data\n"
3882  " }\n"
3883  " ,... More key-value pairs of the above form. For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
3884  " accepted as second parameter.\n"
3885  " ]\n"
3886  "3. locktime (numeric, optional, default=0) Raw locktime. Non-0 value also locktime-activates inputs\n"
3887  " Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible.\n"
3888  "4. options (object, optional)\n"
3889  " {\n"
3890  " \"changeAddress\" (string, optional, default pool address) The bitcoin address to receive the change\n"
3891  " \"changePosition\" (numeric, optional, default random) The index of the change output\n"
3892  " \"change_type\" (string, optional) The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", and \"bech32\". Default is set by -changetype.\n"
3893  " \"includeWatching\" (boolean, optional, default false) Also select inputs which are watch only\n"
3894  " \"lockUnspents\" (boolean, optional, default false) Lock selected unspent outputs\n"
3895  " \"feeRate\" (numeric, optional, default not set: makes wallet determine the fee) Set a specific fee rate in " + CURRENCY_UNIT + "/kB\n"
3896  " \"subtractFeeFromOutputs\" (array, optional) A json array of integers.\n"
3897  " The fee will be equally deducted from the amount of each specified output.\n"
3898  " The outputs are specified by their zero-based index, before any change output is added.\n"
3899  " Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
3900  " If no outputs are specified here, the sender pays the fee.\n"
3901  " [vout_index,...]\n"
3902  " \"replaceable\" (boolean, optional) Marks this transaction as BIP125 replaceable.\n"
3903  " Allows this transaction to be replaced by a transaction with higher fees\n"
3904  " \"conf_target\" (numeric, optional) Confirmation target (in blocks)\n"
3905  " \"estimate_mode\" (string, optional, default=UNSET) The fee estimate mode, must be one of:\n"
3906  " \"UNSET\"\n"
3907  " \"ECONOMICAL\"\n"
3908  " \"CONSERVATIVE\"\n"
3909  " }\n"
3910  "5. bip32derivs (boolean, optional, default=false) If true, includes the BIP 32 derivation paths for public keys if we know them\n"
3911  "\nResult:\n"
3912  "{\n"
3913  " \"psbt\": \"value\", (string) The resulting raw transaction (base64-encoded string)\n"
3914  " \"fee\": n, (numeric) Fee in " + CURRENCY_UNIT + " the resulting transaction pays\n"
3915  " \"changepos\": n (numeric) The position of the added change output, or -1\n"
3916  "}\n"
3917  "\nExamples:\n"
3918  "\nCreate a transaction with no inputs\n"
3919  + HelpExampleCli("walletcreatefundedpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
3920  );
3921 
3922  RPCTypeCheck(request.params, {
3923  UniValue::VARR,
3924  UniValueType(), // ARR or OBJ, checked later
3925  UniValue::VNUM,
3926  UniValue::VOBJ,
3927  UniValue::VBOOL
3928  }, true
3929  );
3930 
3931  CAmount fee;
3932  int change_position;
3933  CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], request.params[3]["replaceable"]);
3934  FundTransaction(pwallet, rawTx, fee, change_position, request.params[3]);
3935 
3936  // Make a blank psbt
3938  psbtx.tx = rawTx;
3939  for (unsigned int i = 0; i < rawTx.vin.size(); ++i) {
3940  psbtx.inputs.push_back(PSBTInput());
3941  }
3942  for (unsigned int i = 0; i < rawTx.vout.size(); ++i) {
3943  psbtx.outputs.push_back(PSBTOutput());
3944  }
3945 
3946  // Use CTransaction for the constant parts of the
3947  // transaction to avoid rehashing.
3948  const CTransaction txConst(*psbtx.tx);
3949 
3950  // Fill transaction with out data but don't sign
3951  bool bip32derivs = request.params[4].isNull() ? false : request.params[4].get_bool();
3952  FillPSBT(pwallet, psbtx, &txConst, 1, false, bip32derivs);
3953 
3954  // Serialize the PSBT
3955  CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
3956  ssTx << psbtx;
3957 
3958  UniValue result(UniValue::VOBJ);
3959  result.pushKV("psbt", EncodeBase64((unsigned char*)ssTx.data(), ssTx.size()));
3960  result.pushKV("fee", ValueFromAmount(fee));
3961  result.pushKV("changepos", change_position);
3962  return result;
3963 }
3964 
3965 UniValue abortrescan(const JSONRPCRequest& request); // in rpcdump.cpp
3966 UniValue dumpprivkey(const JSONRPCRequest& request); // in rpcdump.cpp
3967 UniValue importprivkey(const JSONRPCRequest& request);
3968 UniValue importaddress(const JSONRPCRequest& request);
3969 UniValue importpubkey(const JSONRPCRequest& request);
3970 UniValue dumpwallet(const JSONRPCRequest& request);
3971 UniValue importwallet(const JSONRPCRequest& request);
3972 UniValue importprunedfunds(const JSONRPCRequest& request);
3973 UniValue removeprunedfunds(const JSONRPCRequest& request);
3974 UniValue importmulti(const JSONRPCRequest& request);
3975 
3976 // clang-format off
3977 static const CRPCCommand commands[] =
3978 { // category name actor (function) argNames
3979  // --------------------- ------------------------ ----------------------- ----------
3980  { "generating", "generate", &generate, {"nblocks","maxtries"} },
3981  { "hidden", "resendwallettransactions", &resendwallettransactions, {} },
3982  { "rawtransactions", "fundrawtransaction", &fundrawtransaction, {"hexstring","options","iswitness"} },
3983  { "wallet", "abandontransaction", &abandontransaction, {"txid"} },
3984  { "wallet", "abortrescan", &abortrescan, {} },
3985  { "wallet", "addmultisigaddress", &addmultisigaddress, {"nrequired","keys","label","address_type"} },
3986  { "wallet", "backupwallet", &backupwallet, {"destination"} },
3987  { "wallet", "bumpfee", &bumpfee, {"txid", "options"} },
3988  { "wallet", "createwallet", &createwallet, {"wallet_name", "disable_private_keys"} },
3989  { "wallet", "dumpprivkey", &dumpprivkey, {"address"} },
3990  { "wallet", "dumpwallet", &dumpwallet, {"filename"} },
3991  { "wallet", "encryptwallet", &encryptwallet, {"passphrase"} },
3992  { "wallet", "getaddressesbylabel", &getaddressesbylabel, {"label"} },
3993  { "wallet", "getaddressinfo", &getaddressinfo, {"address"} },
3994  { "wallet", "getbalance", &getbalance, {"dummy","minconf","include_watchonly"} },
3995  { "wallet", "getnewaddress", &getnewaddress, {"label","address_type"} },
3996  { "wallet", "getrawchangeaddress", &getrawchangeaddress, {"address_type"} },
3997  { "wallet", "getreceivedbyaddress", &getreceivedbyaddress, {"address","minconf"} },
3998  { "wallet", "getreceivedbylabel", &getreceivedbylabel, {"label","minconf"} },
3999  { "wallet", "gettransaction", &gettransaction, {"txid","include_watchonly"} },
4000  { "wallet", "getunconfirmedbalance", &getunconfirmedbalance, {} },
4001  { "wallet", "getwalletinfo", &getwalletinfo, {} },
4002  { "wallet", "importaddress", &importaddress, {"address","label","rescan","p2sh"} },
4003  { "wallet", "importmulti", &importmulti, {"requests","options"} },
4004  { "wallet", "importprivkey", &importprivkey, {"privkey","label","rescan"} },
4005  { "wallet", "importprunedfunds", &importprunedfunds, {"rawtransaction","txoutproof"} },
4006  { "wallet", "importpubkey", &importpubkey, {"pubkey","label","rescan"} },
4007  { "wallet", "importwallet", &importwallet, {"filename"} },
4008  { "wallet", "keypoolrefill", &keypoolrefill, {"newsize"} },
4009  { "wallet", "listaddressgroupings", &listaddressgroupings, {} },
4010  { "wallet", "listlabels", &listlabels, {"purpose"} },
4011  { "wallet", "listlockunspent", &listlockunspent, {} },
4012  { "wallet", "listreceivedbyaddress", &listreceivedbyaddress, {"minconf","include_empty","include_watchonly","address_filter"} },
4013  { "wallet", "listreceivedbylabel", &listreceivedbylabel, {"minconf","include_empty","include_watchonly"} },
4014  { "wallet", "listsinceblock", &listsinceblock, {"blockhash","target_confirmations","include_watchonly","include_removed"} },
4015  { "wallet", "listtransactions", &listtransactions, {"dummy","count","skip","include_watchonly"} },
4016  { "wallet", "listunspent", &listunspent, {"minconf","maxconf","addresses","include_unsafe","query_options"} },
4017  { "wallet", "listwalletdir", &listwalletdir, {} },
4018  { "wallet", "listwallets", &listwallets, {} },
4019  { "wallet", "loadwallet", &loadwallet, {"filename"} },
4020  { "wallet", "lockunspent", &lockunspent, {"unlock","transactions"} },
4021  { "wallet", "removeprunedfunds", &removeprunedfunds, {"txid"} },
4022  { "wallet", "rescanblockchain", &rescanblockchain, {"start_height", "stop_height"} },
4023  { "wallet", "sendmany", &sendmany, {"dummy","amounts","minconf","comment","subtractfeefrom","replaceable","conf_target","estimate_mode"} },
4024  { "wallet", "sendtoaddress", &sendtoaddress, {"address","amount","comment","comment_to","subtractfeefromamount","replaceable","conf_target","estimate_mode"} },
4025  { "wallet", "sethdseed", &sethdseed, {"newkeypool","seed"} },
4026  { "wallet", "setlabel", &setlabel, {"address","label"} },
4027  { "wallet", "settxfee", &settxfee, {"amount"} },
4028  { "wallet", "signmessage", &signmessage, {"address","message"} },
4029  { "wallet", "signrawtransactionwithwallet", &signrawtransactionwithwallet, {"hexstring","prevtxs","sighashtype"} },
4030  { "wallet", "unloadwallet", &unloadwallet, {"wallet_name"} },
4031  { "wallet", "walletcreatefundedpsbt", &walletcreatefundedpsbt, {"inputs","outputs","locktime","options","bip32derivs"} },
4032  { "wallet", "walletlock", &walletlock, {} },
4033  { "wallet", "walletpassphrase", &walletpassphrase, {"passphrase","timeout"} },
4034  { "wallet", "walletpassphrasechange", &walletpassphrasechange, {"oldpassphrase","newpassphrase"} },
4035  { "wallet", "walletprocesspsbt", &walletprocesspsbt, {"psbt","sign","sighashtype","bip32derivs"} },
4036 };
4037 // clang-format on
4038 
4040 {
4041  for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
4042  t.appendCommand(commands[vcidx].name, &commands[vcidx]);
4043 }
No wallet specified (error when there are multiple wallets loaded)
Definition: protocol.h:86
CAmount nValue
Definition: transaction.h:134
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: server.cpp:75
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: server.cpp:126
CTxMemPool mempool
CScript CreateMultisigRedeemscript(const int required, const std::vector< CPubKey > &pubkeys)
Definition: util.cpp:47
CPubKey AddrToPubKey(CKeyStore *const keystore, const std::string &addr_in)
Definition: util.cpp:26
Result CreateTransaction(const CWallet *wallet, const uint256 &txid, const CCoinControl &coin_control, CAmount total_fee, std::vector< std::string > &errors, CAmount &old_fee, CAmount &new_fee, CMutableTransaction &mtx)
Create bumpfee transaction.
Definition: feebumper.cpp:76
std::map< CTxDestination, tallyitem > mapTally
Definition: rpcwallet.cpp:1027
OutputType m_default_change_type
Definition: wallet.h:932
std::string hdKeypath
Definition: walletdb.h:99
std::set< std::set< CTxDestination > > GetAddressGroupings() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3431
bool fPruneMode
True if we&#39;re running in -prune mode.
Definition: validation.cpp:228
UniValue operator()(const CNoDestination &dest) const
Definition: rpcwallet.cpp:3368
CAmount GetImmatureBalance() const
Definition: wallet.cpp:2054
const std::vector< UniValue > & getValues() const
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:155
bool GetWalletNameFromJSONRPCRequest(const JSONRPCRequest &request, std::string &wallet_name)
Definition: rpcwallet.cpp:43
Keypool ran out, call keypoolrefill first.
Definition: protocol.h:79
int64_t GetOldestKeyPoolTime()
Definition: wallet.cpp:3373
UniValue importwallet(const JSONRPCRequest &request)
Definition: rpcdump.cpp:504
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:26
static bool Verify(std::string wallet_file, bool salvage_wallet, std::string &error_string, std::string &warning_string)
Verify wallet naming and perform salvage on the wallet if required.
Definition: wallet.cpp:3824
std::map< std::string, std::string > mapValue_t
Definition: wallet.h:182
bool CanSupportFeature(enum WalletFeature wf) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
check whether we are allowed to upgrade (or already support) to the named feature ...
Definition: wallet.h:770
Enter the wallet passphrase with walletpassphrase first.
Definition: protocol.h:80
Bitcoin RPC command dispatcher.
Definition: server.h:143
void AvailableCoins(std::vector< COutput > &vCoins, bool fOnlySafe=true, const CCoinControl *coinControl=nullptr, const CAmount &nMinimumAmount=1, const CAmount &nMaximumAmount=MAX_MONEY, const CAmount &nMinimumSumAmount=MAX_MONEY, const uint64_t nMaximumCount=0, const int nMinDepth=0, const int nMaxDepth=9999999) const EXCLUSIVE_LOCKS_REQUIRED(cs_main
populate vCoins with vector of available COutputs.
Definition: wallet.cpp:2151
int64_t GetBlockTime() const
Definition: chain.h:297
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:50
std::vector< std::shared_ptr< CWallet > > GetWallets()
Definition: dummywallet.cpp:47
CScript scriptPubKey
Definition: transaction.h:135
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:177
void UnlockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3612
uint32_t nStatus
Verification status of this block. See enum BlockStatus.
Definition: chain.h:207
std::shared_ptr< CWallet > GetWallet(const std::string &name)
Definition: wallet.cpp:75
bool get_bool() const
UniValue operator()(const WitnessV0ScriptHash &id) const
Definition: rpcwallet.cpp:3401
boost::optional< CMutableTransaction > tx
Definition: sign.h:559
bool HaveKey(const CKeyStore &store, const CKey &key)
Checks if a CKey is in the given CKeyStore compressed or otherwise.
Definition: keystore.cpp:199
Definition: block.h:74
boost::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
Definition: coincontrol.h:32
std::map< CTxDestination, CAddressBookData > mapAddressBook
Definition: wallet.h:763
bool IsValidDestinationString(const std::string &str, const CChainParams &params)
Definition: key_io.cpp:219
std::map< std::string, tallyitem > label_tally
Definition: rpcwallet.cpp:1063
#define strprintf
Definition: tinyformat.h:1066
bool IsPayToScriptHash() const
Definition: script.cpp:197
bool AddWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:43
const uint256 & GetHash() const
Definition: wallet.h:283
bool IsFromMe(const isminefilter &filter) const
Definition: wallet.h:483
auto start
Definition: rpcwallet.cpp:1067
std::vector< uint256 > txids
Definition: rpcwallet.cpp:989
bool IsCrypted() const
Definition: crypter.h:144
bool EnsureWalletIsAvailable(CWallet *const pwallet, bool avoidException)
Definition: rpcwallet.cpp:73
std::vector< CTxIn > vin
Definition: transaction.h:362
RBFTransactionState
Definition: rbf.h:12
UniValue ret(UniValue::VARR)
Definition: rpcwallet.cpp:1140
TxItems wtxOrdered
Definition: wallet.h:758
UniValue getaddressinfo(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:3437
CAmount GetDebit(const isminefilter &filter) const
filter decides which addresses will count towards the debit
Definition: wallet.cpp:1774
std::string urlDecode(const std::string &urlEncoded)
Definition: httpserver.cpp:662
CFeeRate m_pay_tx_fee
Definition: wallet.h:918
bool GetCScript(const CScriptID &hash, CScript &redeemScriptOut) const override
Definition: keystore.cpp:112
bool FundTransaction(CMutableTransaction &tx, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, bool lockUnspents, const std::set< int > &setSubtractFeeFromOutputs, CCoinControl)
Insert additional inputs into the transaction by calling CreateTransaction();.
Definition: wallet.cpp:2479
int Height() const
Return the maximal height in the chain.
Definition: chain.h:476
bool CommitTransaction(CTransactionRef tx, mapValue_t mapValue, std::vector< std::pair< std::string, std::string >> orderForm, CReserveKey &reservekey, CConnman *connman, CValidationState &state)
Call after CreateTransaction unless you want to abort.
Definition: wallet.cpp:2958
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:324
UniValue ValueFromAmount(const CAmount &amount)
Definition: core_write.cpp:19
size_t KeypoolCountExternalKeys() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3183
std::string HexStr(const T itbegin, const T itend, bool fSpaces=false)
std::basic_string< char, std::char_traits< char >, secure_allocator< char > > SecureString
Definition: secure.h:56
bool fIsWatchonly
Definition: rpcwallet.cpp:990
value_type * data()
Definition: streams.h:321
CPubKey HexToPubKey(const std::string &hex_in)
Definition: util.cpp:13
UniValue DescribeAddress(const CTxDestination &dest)
Definition: util.cpp:125
CKeyID GetKeyForDestination(const CKeyStore &store, const CTxDestination &dest)
Return the CKeyID of the key involved in a script (if there is a unique one).
Definition: keystore.cpp:177
boost::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
Definition: coincontrol.h:22
const std::string & get_str() const
uint8_t isminefilter
used for bitflags of isminetype
Definition: ismine.h:25
CBlockIndex * Genesis() const
Returns the index entry for the genesis block of this chain, or nullptr if none.
Definition: chain.h:440
bool IsWalletFlagSet(uint64_t flag)
check if a certain wallet flag is set
Definition: wallet.cpp:1431
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: server.cpp:516
const UniValue & get_array() const
CAmount GetLegacyBalance(const isminefilter &filter, int minDepth) const
Definition: wallet.cpp:2103
const std::string CURRENCY_UNIT
Definition: feerate.cpp:10
txnouttype Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char >> &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
Definition: standard.cpp:90
A version of CTransaction with the PSBT format.
Definition: sign.h:557
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:221
std::string name
Definition: wallet.h:166
int64_t get_int64() const
bool GetKeyOrigin(const CKeyID &keyid, KeyOriginInfo &info) const override
Implement lookup of key origin information through wallet key metadata.
Definition: wallet.cpp:4321
CTxOut witness_utxo
Definition: sign.h:222
void UnregisterValidationInterface(CValidationInterface *pwalletIn)
Unregister a wallet from core.
A signature creator for transactions.
Definition: sign.h:83
bool pushKVs(const UniValue &obj)
Definition: univalue.cpp:146
const std::vector< std::string > & getKeys() const
void RPCRunLater(const std::string &name, std::function< void()> func, int64_t nSeconds)
Run func nSeconds from now.
Definition: server.cpp:539
bool EncryptWallet(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:640
unsigned char * begin()
Definition: uint256.h:56
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:402
bool appendCommand(const std::string &name, const CRPCCommand *pcmd)
Appends a CRPCCommand to the dispatch table.
Definition: server.cpp:285
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:155
bool IsNull() const
Definition: uint256.h:32
std::string purpose
Definition: wallet.h:167
const std::string strMessageMagic
Definition: validation.cpp:251
bool fOverrideFeeRate
Override automatic min/max checks on fee, m_feerate must be set if true.
Definition: coincontrol.h:28
const unsigned char * begin() const
Definition: pubkey.h:111
OutputType
Definition: outputtype.h:15
std::string HelpRequiringPassphrase(CWallet *const pwallet)
Definition: rpcwallet.cpp:66
Coin Control Features.
Definition: coincontrol.h:16
std::vector< fs::path > ListWalletDir()
Get wallets in wallet directory.
Definition: dummywallet.cpp:42
CFeeRate m_min_fee
Override with -mintxfee.
Definition: wallet.h:923
const std::vector< CTxIn > vin
Definition: transaction.h:281
Invalid, missing or duplicate parameter.
Definition: protocol.h:52
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: server.cpp:117
boost::optional< CFeeRate > m_feerate
Override the wallet&#39;s m_pay_tx_fee if set.
Definition: coincontrol.h:30
static std::shared_ptr< CWallet > CreateWalletFromFile(const std::string &name, const fs::path &path, uint64_t wallet_creation_flags=0)
Definition: wallet.cpp:3875
bool GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const override
Definition: crypter.cpp:278
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:234
bool DecodePSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Definition: core_read.cpp:179
void FromSignatureData(const SignatureData &sigdata)
Definition: sign.cpp:643
UniValue generateBlocks(std::shared_ptr< CReserveScript > coinbaseScript, int nGenerate, uint64_t nMaxTries, bool keepScript)
Generate blocks (mine)
Definition: mining.cpp:124
bool SignCompact(const uint256 &hash, std::vector< unsigned char > &vchSig) const
Create a compact signature (65 bytes), which allows reconstructing the used public key...
Definition: key.cpp:241
bool fIncludeEmpty
Definition: rpcwallet.cpp:1007
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
uint256 GetBlockHash() const
Definition: chain.h:292
A structure for PSBTs which contains per output information.
Definition: sign.h:444
bool SetAddressBook(const CTxDestination &address, const std::string &strName, const std::string &purpose)
Definition: wallet.cpp:3092
The wallet passphrase entered was incorrect.
Definition: protocol.h:81
std::vector< PSBTOutput > outputs
Definition: sign.h:561
iterator end()
Definition: prevector.h:303
#define LOCK2(cs1, cs2)
Definition: sync.h:182
std::string name
Definition: server.h:135
bool IsLockedCoin(uint256 hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3624
isminefilter filter
Definition: rpcwallet.cpp:1011
UniValue walletprocesspsbt(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:3782
void push_back(const T &value)
Definition: prevector.h:423
UniValue signrawtransactionwithwallet(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:2955
bool push_back(const UniValue &val)
Definition: univalue.cpp:108
bool SignTransaction(CWallet *wallet, CMutableTransaction &mtx)
Sign the new transaction,.
Definition: feebumper.cpp:214
UniValue importaddress(const JSONRPCRequest &request)
Definition: rpcdump.cpp:253
bool CheckFinalTx(const CTransaction &tx, int flags)
Transaction validation functions.
Definition: validation.cpp:315
CAmount GetBalance(const isminefilter &filter=ISMINE_SPENDABLE, const int min_depth=0) const
Definition: wallet.cpp:2022
void GetAmounts(std::list< COutputEntry > &listReceived, std::list< COutputEntry > &listSent, CAmount &nFee, const isminefilter &filter) const
Definition: wallet.cpp:1529
CCriticalSection cs_main
Definition: validation.cpp:216
int GetDepthInMainChain() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Return depth of transaction in blockchain: <0 : conflicts with a transaction this deep in the blockch...
Definition: wallet.cpp:4231
bool AbandonTransaction(const uint256 &hashTx)
Definition: wallet.cpp:1024
size_type size() const
Definition: streams.h:312
const unsigned char * end() const
Definition: pubkey.h:112
CAmount GetCredit(const isminefilter &filter) const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: wallet.cpp:1805
CTransactionRef tx
Definition: wallet.h:218
CFeeRate minRelayTxFee
A fee rate smaller than this is considered zero fee (for relaying, mining and transaction creation) ...
Definition: validation.cpp:241
UniValue operator()(const CScriptID &scriptID) const
Definition: rpcwallet.cpp:3381
UniValue params
Definition: server.h:44
bool NewKeyPool()
Mark old keypool keys as used, and generate all new keys.
Definition: wallet.cpp:3149
int ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:215
isminetype
IsMine() return codes.
Definition: ismine.h:17
An input of a transaction.
Definition: transaction.h:61
boost::variant< CNoDestination, CKeyID, CScriptID, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:123
OutputType m_default_address_type
Definition: wallet.h:931
CTxDestination subtype to encode any future Witness version.
Definition: standard.h:92
bool IsHDEnabled() const
Definition: wallet.cpp:1418
unsigned int GetKeyPoolSize() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.h:1000
#define LOCK(cs)
Definition: sync.h:181
const char * name
Definition: rest.cpp:37
CTxDestination AddAndGetDestinationForScript(CKeyStore &keystore, const CScript &script, OutputType type)
Get a destination of the requested type (if possible) to the specified script.
Definition: outputtype.cpp:76
bool exists(const std::string &key) const
Definition: univalue.h:76
bool IsLocked() const
Definition: crypter.cpp:155
int GetVersion()
get the current wallet format (the oldest client version guaranteed to understand this wallet) ...
Definition: wallet.h:1013
UniValue generate(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:3178
CTxDestination destChange
Custom change destination, if not set an address is generated.
Definition: coincontrol.h:20
Fast randomness source.
Definition: random.h:45
An encapsulated public key.
Definition: pubkey.h:30
uint32_t n
Definition: transaction.h:22
void UnlockAllCoins() EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3618
bool IsHex(const std::string &str)
const std::vector< CTxOut > vout
Definition: transaction.h:282
Unexpected type was passed as parameter.
Definition: protocol.h:49
bool IsCoinBase() const
Definition: wallet.h:284
CAmount GetUnconfirmedBalance() const
Definition: wallet.cpp:2039
Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
Definition: protocol.h:82
bool has_filtered_address
Definition: rpcwallet.cpp:1016
bool empty() const
Definition: univalue.h:67
UniValue importprunedfunds(const JSONRPCRequest &request)
Definition: rpcdump.cpp:332
bool IsInitialBlockDownload()
Check whether we are doing an initial block download (synchronizing from disk or network) ...
UniValue dumpwallet(const JSONRPCRequest &request)
Definition: rpcdump.cpp:677
void ProcessSubScript(const CScript &subscript, UniValue &obj, bool include_addresses=false) const
Definition: rpcwallet.cpp:3323
const char * GetTxnOutputType(txnouttype t)
Get the name of a txnouttype as a C string, or nullptr if unknown.
Definition: standard.cpp:27
auto end
Definition: rpcwallet.cpp:1068
General application defined errors.
Definition: protocol.h:48
A structure for PSBTs which contain per-input information.
Definition: sign.h:219
bool pushKV(const std::string &key, const UniValue &val)
Definition: univalue.cpp:133
bool GetKey(const CKeyID &address, CKey &keyOut) const override
Definition: crypter.cpp:261
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: server.cpp:51
An output of a transaction.
Definition: transaction.h:131
bool IsSpent(const uint256 &hash, unsigned int n) const EXCLUSIVE_LOCKS_REQUIRED(cs_main
Outpoint is spent if any non-conflicted transaction spends it:
Definition: wallet.cpp:597
int get_int() const
Invalid address or key.
Definition: protocol.h:50
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:288
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: server.cpp:511
CAmount AmountFromValue(const UniValue &value)
Definition: server.cpp:105
Invalid wallet specified.
Definition: protocol.h:85
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:18
int64_t nCreateTime
Definition: walletdb.h:98
CCriticalSection cs_wallet
Definition: wallet.h:709
std::vector< CTxOut > vout
Definition: transaction.h:363
std::string FormatMoney(const CAmount &n)
Money parsing/formatting utilities.
std::shared_ptr< CWallet > GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: rpcwallet.cpp:53
bool IsDeprecatedRPCEnabled(const std::string &method)
Definition: server.cpp:380
Special output type for change outputs only.
bool isNull() const
Definition: univalue.h:78
std::vector< PSBTInput > inputs
Definition: sign.h:560
boost::optional< bool > m_signal_bip125_rbf
Override the wallet&#39;s m_signal_rbf if set.
Definition: coincontrol.h:34
CCriticalSection cs
Definition: txmempool.h:487
UniValue rescanblockchain(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:3231
RAII object to check and reserve a wallet rescan.
Definition: wallet.h:1176
A transaction with a bunch of additional info that only the owner cares about.
Definition: wallet.h:295
RPC method is deprecated.
Definition: protocol.h:59
void RegisterWalletRPCCommands(CRPCTable &t)
Definition: rpcwallet.cpp:4039
bool IsSolvable(const SigningProvider &provider, const CScript &script)
Definition: sign.cpp:497
CRIPEMD160 & Write(const unsigned char *data, size_t len)
Definition: ripemd160.cpp:247
void ListLockedCoins(std::vector< COutPoint > &vOutpts) const EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3632
bool FillPSBT(const CWallet *pwallet, PartiallySignedTransaction &psbtx, const CTransaction *txConst, int sighash_type, bool sign, bool bip32derivs)
Definition: rpcwallet.cpp:3738
std::map< CTxDestination, CAmount > GetAddressBalances() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: wallet.cpp:3391
bool GetBroadcastTransactions() const
Inquire whether this wallet broadcasts transactions.
Definition: wallet.h:1050
int sighash_type
Definition: sign.h:230
void BlockUntilSyncedToCurrentChain() LOCKS_EXCLUDED(cs_main
Blocks until the wallet state is up-to-date to /at least/ the current chain at the time this function...
Definition: wallet.cpp:1193
CBlockIndex * ScanForWalletTransactions(CBlockIndex *pindexStart, CBlockIndex *pindexStop, const WalletRescanReserver &reserver, bool fUpdate=false)
Scan the block chain (starting in pindexStart) for transactions from or to us.
Definition: wallet.cpp:1629
void LockCoin(const COutPoint &output) EXCLUSIVE_LOCKS_REQUIRED(cs_wallet)
Definition: wallet.cpp:3606
CPubKey DeriveNewSeed(const CKey &key)
Definition: wallet.cpp:1370
Failed to encrypt the wallet.
Definition: protocol.h:83
bool CreateTransaction(const std::vector< CRecipient > &vecSend, CTransactionRef &tx, CReserveKey &reservekey, CAmount &nFeeRet, int &nChangePosInOut, std::string &strFailReason, const CCoinControl &coin_control, bool sign=true)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: wallet.cpp:2561
bool fHelp
Definition: server.h:45
txnouttype
Definition: standard.h:56
Capture information about block/transaction validation.
Definition: validation.h:26
256-bit opaque blob.
Definition: uint256.h:122
CTxDestination DecodeDestination(const std::string &str)
Definition: key_io.cpp:214
void GetScriptForMining(std::shared_ptr< CReserveScript > &script)
Definition: wallet.cpp:3595
enum VType type() const
Definition: univalue.h:178
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:51
std::vector< CTransactionRef > vtx
Definition: block.h:78
std::string FormatStateMessage(const CValidationState &state)
Convert CValidationState to a human-readable message for logging.
Definition: validation.cpp:453
void FillSignatureData(SignatureData &sigdata) const
Definition: sign.cpp:630
RBFTransactionState IsRBFOptIn(const CTransaction &tx, CTxMemPool &pool)
Definition: rbf.cpp:17
#define ARRAYLEN(array)
bool setArray()
Definition: univalue.cpp:94
UniValue walletcreatefundedpsbt(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:3851
bool HasWallets()
Definition: wallet.cpp:63
bool ChangeWalletPassphrase(const SecureString &strOldWalletPassphrase, const SecureString &strNewWalletPassphrase)
Definition: wallet.cpp:431
const std::string & GetName() const
Get a name for this wallet for logging/debugging purposes.
Definition: wallet.h:729
A key allocated from the key pool.
Definition: wallet.h:1145
Result CommitTransaction(CWallet *wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< std::string > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:219
Address book data.
Definition: wallet.h:163
CAmount nAmount
Definition: rpcwallet.cpp:987
The block chain is a tree shaped structure starting with the genesis block at the root...
Definition: chain.h:170
const CChainParams & Params()
Return the currently selected parameters.
std::set< CTxDestination > GetLabelAddresses(const std::string &label) const
Definition: wallet.cpp:3524
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:384
int RPCSerializationFlags()
Definition: server.cpp:548
UniValue operator()(const WitnessUnknown &id) const
Definition: rpcwallet.cpp:3414
bool TopUpKeyPool(unsigned int kpSize=0)
Definition: wallet.cpp:3210
Not enough funds in wallet or account.
Definition: protocol.h:77
const UniValue & get_obj() const
bool push_backV(const std::vector< UniValue > &vec)
Definition: univalue.cpp:117
void SetHDSeed(const CPubKey &key)
Definition: wallet.cpp:1397
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: server.cpp:68
std::string URI
Definition: server.h:46
CTransactionRef non_witness_utxo
Definition: sign.h:221
isminetype IsMine(const CKeyStore &keystore, const CScript &scriptPubKey)
Definition: ismine.cpp:175
A reference to a CKey: the Hash360 of its serialized public key.
Definition: pubkey.h:20
CBlockIndex * Tip() const
Returns the index entry for the tip of this chain, or nullptr if none.
Definition: chain.h:445
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:113
void LearnRelatedScripts(const CPubKey &key, OutputType)
Explicitly make the wallet learn the related scripts for outputs to the given key.
Definition: wallet.cpp:4274
std::string GetHex() const
Definition: uint256.cpp:21
bool RemoveWallet(const std::shared_ptr< CWallet > &wallet)
Definition: wallet.cpp:53
A CWallet is an extension of a keystore, which also maintains a set of transactions and balances...
Definition: wallet.h:599
unsigned int ParseConfirmTarget(const UniValue &value)
Check bounds on a command line confirm target.
Definition: mining.cpp:33
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:131
UniValue SignTransaction(CMutableTransaction &mtx, const UniValue &prevTxsUnival, CBasicKeyStore *keystore, bool is_temp_keystore, const UniValue &hashType)
Sign a transaction with the given keystore and previous transactions.
Fee rate in satoshis per kilobyte: CAmount / kB.
Definition: feerate.h:19
std::unique_ptr< CConnman > g_connman
Definition: init.cpp:74
160-bit opaque blob.
Definition: uint256.h:111
const UniValue NullUniValue
Definition: univalue.cpp:13
UniValue removeprunedfunds(const JSONRPCRequest &request)
Definition: rpcdump.cpp:395
fs::path GetWalletDir()
Get the path of the wallet directory.
Definition: dummywallet.cpp:37
bool ProduceSignature(const SigningProvider &provider, const BaseSignatureCreator &creator, const CScript &fromPubKey, SignatureData &sigdata)
Produce a script signature using a generic signature creator.
Definition: sign.cpp:186
bool error(const char *fmt, const Args &... args)
Definition: util.h:59
CTxDestination GetDestinationForKey(const CPubKey &key, OutputType type)
Get a destination of the requested type (if possible) to the specified key.
Definition: outputtype.cpp:45
Definition: wallet.h:203
iterator begin()
Definition: prevector.h:301
void FundTransaction(CWallet *const pwallet, CMutableTransaction &tx, CAmount &fee_out, int &change_position, UniValue options)
Definition: rpcwallet.cpp:2750
DescribeWalletAddressVisitor(CWallet *_pwallet)
Definition: rpcwallet.cpp:3366
UniValue operator()(const WitnessV0KeyHash &id) const
Definition: rpcwallet.cpp:3391
UniValue sethdseed(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:3654
std::vector< uint256 > ResendWalletTransactionsBefore(int64_t nTime, CConnman *connman) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: wallet.cpp:1963
A reference to a CScript: the Hash360 of its serialization (see script.h)
Definition: standard.h:22
bool GetKeyFromPool(CPubKey &key, bool internal=false)
Definition: wallet.cpp:3337
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:209
CMutableTransaction ConstructTransaction(const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime, const UniValue &rbf)
Create a transaction from univalue parameters.
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:37
A mutable version of CTransaction.
Definition: transaction.h:360
A writer stream (for serialization) that computes a 256-bit SHA-3-256 hash.
Definition: hash.h:165
Wallet errors.
Definition: protocol.h:76
bool IsAbortingRescan()
Definition: wallet.h:809
UniValue dumpprivkey(const JSONRPCRequest &request)
Definition: rpcdump.cpp:633
FeeEstimateMode m_fee_mode
Fee estimation mode to control arguments to estimateSmartFee.
Definition: coincontrol.h:38
void AddKeypathToMap(const CWallet *pwallet, const CKeyID &keyID, std::map< CPubKey, KeyOriginInfo > &hd_keypaths)
Definition: rpcwallet.cpp:3725
UniValue JSONRPCError(int code, const std::string &message)
Definition: protocol.cpp:51
void clear()
Definition: univalue.cpp:15
No valid connection manager instance found.
Definition: protocol.h:73
size_t size() const
Definition: univalue.h:69
int64_t GetTime()
GetTimeMicros() and GetTimeMillis() both return the system time, but in different units...
Definition: utiltime.cpp:20
std::string ToString() const
Definition: feerate.cpp:40
An encapsulated private key.
Definition: key.h:27
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:264
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: chain.h:183
CTxDestination filtered_address
Definition: rpcwallet.cpp:1017
CKeyID hd_seed_id
Definition: walletdb.h:100
bool ReadBlockFromDisk(CBlock &block, const CDiskBlockPos &pos, const Consensus::Params &consensusParams)
Functions for disk access for blocks.
UniValue abortrescan(const JSONRPCRequest &request)
Definition: rpcdump.cpp:191
CKey DecodeSecret(const std::string &str)
Definition: key_io.cpp:133
Still downloading initial blocks.
Definition: protocol.h:68
full block available in blk*.dat
Definition: chain.h:154
bool SignPSBTInput(const SigningProvider &provider, const CMutableTransaction &tx, PSBTInput &input, int index, int sighash)
Signs a PSBTInput, verifying that all provided data matches what is being signed. ...
Definition: sign.cpp:242
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: ripemd160.cpp:273
CChain & chainActive
The currently-connected chain of blocks (protected by cs_main).
Definition: validation.cpp:219
const CHDChain & GetHDChain() const
Definition: wallet.h:1079
CKeyID seed_id
seed hash360
Definition: walletdb.h:63
bool BackupWallet(const std::string &strDest)
Definition: wallet.cpp:4196
UniValue importmulti(const JSONRPCRequest &request)
Definition: rpcdump.cpp:1062
COutPoint prevout
Definition: transaction.h:64
UniValue importprivkey(const JSONRPCRequest &request)
Definition: rpcdump.cpp:100
UniValue importpubkey(const JSONRPCRequest &request)
Definition: rpcdump.cpp:433
std::multimap< int64_t, CWalletTx * > TxItems
Definition: wallet.h:757
UniValue listtransactions(const JSONRPCRequest &request)
Definition: rpcwallet.cpp:1327
const CBlockIndex * FindFork(const CBlockIndex *pindex) const
Find the last common block between this chain and a block index entry.
Definition: chain.cpp:51
UniValue operator()(const CKeyID &keyID) const
Definition: rpcwallet.cpp:3370
bool ParseOutputType(const std::string &type, OutputType &output_type)
Definition: outputtype.cpp:20
bool IsImmatureCoinBase() const EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Definition: wallet.cpp:4255
Invalid label name.
Definition: protocol.h:78
CAmount GetFeePerK() const
Return the fee in satoshis for a size of 1000 bytes.
Definition: feerate.h:41
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: server.h:32
int64_t nRelockTime
Holds a timestamp at which point the wallet is scheduled (externally) to be relocked. Caller must arrange for actual relocking to occur via Lock().
Definition: wallet.h:854
Error parsing or validating structure in raw format.
Definition: protocol.h:54
CPubKey GenerateNewSeed()
Definition: wallet.cpp:1362
std::string EncodeBase64(const unsigned char *pch, size_t len)
A hasher class for RIPEMD-160.
Definition: ripemd160.h:12
bool IsValid() const
Check whether this private key is valid.
Definition: key.h:93
bool Unlock(const SecureString &strWalletPassphrase)
Definition: wallet.cpp:411
void EnsureWalletIsUnlocked(CWallet *const pwallet)
Definition: rpcwallet.cpp:85
bool isAbandoned() const
Definition: wallet.h:280
uint256 hash
Definition: transaction.h:21
bool IsCompressed() const
Check whether this is a compressed public key.
Definition: pubkey.h:180
CBlockIndex * LookupBlockIndex(const uint256 &hash)
Definition: validation.h:431