Bitcoin Core  24.1.0
P2P Digital Currency
spend.cpp
Go to the documentation of this file.
1 // Copyright (c) 2011-2021 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <consensus/validation.h>
6 #include <core_io.h>
7 #include <key_io.h>
8 #include <policy/policy.h>
10 #include <rpc/util.h>
11 #include <util/fees.h>
12 #include <util/rbf.h>
13 #include <util/translation.h>
14 #include <util/vector.h>
15 #include <wallet/coincontrol.h>
16 #include <wallet/feebumper.h>
17 #include <wallet/fees.h>
18 #include <wallet/rpc/util.h>
19 #include <wallet/spend.h>
20 #include <wallet/wallet.h>
21 
22 #include <univalue.h>
23 
24 
25 namespace wallet {
26 static void ParseRecipients(const UniValue& address_amounts, const UniValue& subtract_fee_outputs, std::vector<CRecipient>& recipients)
27 {
28  std::set<CTxDestination> destinations;
29  int i = 0;
30  for (const std::string& address: address_amounts.getKeys()) {
31  CTxDestination dest = DecodeDestination(address);
32  if (!IsValidDestination(dest)) {
33  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + address);
34  }
35 
36  if (destinations.count(dest)) {
37  throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + address);
38  }
39  destinations.insert(dest);
40 
41  CScript script_pub_key = GetScriptForDestination(dest);
42  CAmount amount = AmountFromValue(address_amounts[i++]);
43 
44  bool subtract_fee = false;
45  for (unsigned int idx = 0; idx < subtract_fee_outputs.size(); idx++) {
46  const UniValue& addr = subtract_fee_outputs[idx];
47  if (addr.get_str() == address) {
48  subtract_fee = true;
49  }
50  }
51 
52  CRecipient recipient = {script_pub_key, amount, subtract_fee};
53  recipients.push_back(recipient);
54  }
55 }
56 
57 static void InterpretFeeEstimationInstructions(const UniValue& conf_target, const UniValue& estimate_mode, const UniValue& fee_rate, UniValue& options)
58 {
59  if (options.exists("conf_target") || options.exists("estimate_mode")) {
60  if (!conf_target.isNull() || !estimate_mode.isNull()) {
61  throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass conf_target and estimate_mode either as arguments or in the options object, but not both");
62  }
63  } else {
64  options.pushKV("conf_target", conf_target);
65  options.pushKV("estimate_mode", estimate_mode);
66  }
67  if (options.exists("fee_rate")) {
68  if (!fee_rate.isNull()) {
69  throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass the fee_rate either as an argument, or in the options object, but not both");
70  }
71  } else {
72  options.pushKV("fee_rate", fee_rate);
73  }
74  if (!options["conf_target"].isNull() && (options["estimate_mode"].isNull() || (options["estimate_mode"].get_str() == "unset"))) {
75  throw JSONRPCError(RPC_INVALID_PARAMETER, "Specify estimate_mode");
76  }
77 }
78 
79 static UniValue FinishTransaction(const std::shared_ptr<CWallet> pwallet, const UniValue& options, const CMutableTransaction& rawTx)
80 {
81  // Make a blank psbt
82  PartiallySignedTransaction psbtx(rawTx);
83 
84  // First fill transaction with our data without signing,
85  // so external signers are not asked sign more than once.
86  bool complete;
87  pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, false, true);
88  const TransactionError err{pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, true, false)};
89  if (err != TransactionError::OK) {
90  throw JSONRPCTransactionError(err);
91  }
92 
94  complete = FinalizeAndExtractPSBT(psbtx, mtx);
95 
96  UniValue result(UniValue::VOBJ);
97 
98  const bool psbt_opt_in{options.exists("psbt") && options["psbt"].get_bool()};
99  bool add_to_wallet{options.exists("add_to_wallet") ? options["add_to_wallet"].get_bool() : true};
100  if (psbt_opt_in || !complete || !add_to_wallet) {
101  // Serialize the PSBT
103  ssTx << psbtx;
104  result.pushKV("psbt", EncodeBase64(ssTx.str()));
105  }
106 
107  if (complete) {
108  std::string hex{EncodeHexTx(CTransaction(mtx))};
109  CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
110  result.pushKV("txid", tx->GetHash().GetHex());
111  if (add_to_wallet && !psbt_opt_in) {
112  pwallet->CommitTransaction(tx, {}, /*orderForm=*/{});
113  } else {
114  result.pushKV("hex", hex);
115  }
116  }
117  result.pushKV("complete", complete);
118 
119  return result;
120 }
121 
122 static void PreventOutdatedOptions(const UniValue& options)
123 {
124  if (options.exists("feeRate")) {
125  throw JSONRPCError(RPC_INVALID_PARAMETER, "Use fee_rate (" + CURRENCY_ATOM + "/vB) instead of feeRate");
126  }
127  if (options.exists("changeAddress")) {
128  throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_address instead of changeAddress");
129  }
130  if (options.exists("changePosition")) {
131  throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_position instead of changePosition");
132  }
133  if (options.exists("includeWatching")) {
134  throw JSONRPCError(RPC_INVALID_PARAMETER, "Use include_watching instead of includeWatching");
135  }
136  if (options.exists("lockUnspents")) {
137  throw JSONRPCError(RPC_INVALID_PARAMETER, "Use lock_unspents instead of lockUnspents");
138  }
139  if (options.exists("subtractFeeFromOutputs")) {
140  throw JSONRPCError(RPC_INVALID_PARAMETER, "Use subtract_fee_from_outputs instead of subtractFeeFromOutputs");
141  }
142 }
143 
144 UniValue SendMoney(CWallet& wallet, const CCoinControl &coin_control, std::vector<CRecipient> &recipients, mapValue_t map_value, bool verbose)
145 {
147 
148  // This function is only used by sendtoaddress and sendmany.
149  // This should always try to sign, if we don't have private keys, don't try to do anything here.
150  if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
151  throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
152  }
153 
154  // Shuffle recipient list
155  std::shuffle(recipients.begin(), recipients.end(), FastRandomContext());
156 
157  // Send
158  constexpr int RANDOM_CHANGE_POSITION = -1;
159  auto res = CreateTransaction(wallet, recipients, RANDOM_CHANGE_POSITION, coin_control, true);
160  if (!res) {
162  }
163  const CTransactionRef& tx = res->tx;
164  wallet.CommitTransaction(tx, std::move(map_value), {} /* orderForm */);
165  if (verbose) {
166  UniValue entry(UniValue::VOBJ);
167  entry.pushKV("txid", tx->GetHash().GetHex());
168  entry.pushKV("fee_reason", StringForFeeReason(res->fee_calc.reason));
169  return entry;
170  }
171  return tx->GetHash().GetHex();
172 }
173 
174 
188 static void SetFeeEstimateMode(const CWallet& wallet, CCoinControl& cc, const UniValue& conf_target, const UniValue& estimate_mode, const UniValue& fee_rate, bool override_min_fee)
189 {
190  if (!fee_rate.isNull()) {
191  if (!conf_target.isNull()) {
192  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both conf_target and fee_rate. Please provide either a confirmation target in blocks for automatic fee estimation, or an explicit fee rate.");
193  }
194  if (!estimate_mode.isNull() && estimate_mode.get_str() != "unset") {
195  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and fee_rate");
196  }
197  // Fee rates in sat/vB cannot represent more than 3 significant digits.
198  cc.m_feerate = CFeeRate{AmountFromValue(fee_rate, /*decimals=*/3)};
199  if (override_min_fee) cc.fOverrideFeeRate = true;
200  // Default RBF to true for explicit fee_rate, if unset.
201  if (!cc.m_signal_bip125_rbf) cc.m_signal_bip125_rbf = true;
202  return;
203  }
204  if (!estimate_mode.isNull() && !FeeModeFromString(estimate_mode.get_str(), cc.m_fee_mode)) {
206  }
207  if (!conf_target.isNull()) {
208  cc.m_confirm_target = ParseConfirmTarget(conf_target, wallet.chain().estimateMaxBlocks());
209  }
210 }
211 
213 {
214  return RPCHelpMan{"sendtoaddress",
215  "\nSend an amount to a given address." +
217  {
218  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to send to."},
219  {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1"},
220  {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment used to store what the transaction is for.\n"
221  "This is not part of the transaction, just kept in your wallet."},
222  {"comment_to", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment to store the name of the person or organization\n"
223  "to which you're sending the transaction. This is not part of the \n"
224  "transaction, just kept in your wallet."},
225  {"subtractfeefromamount", RPCArg::Type::BOOL, RPCArg::Default{false}, "The fee will be deducted from the amount being sent.\n"
226  "The recipient will receive less bitcoins than you enter in the amount field."},
227  {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Signal that this transaction can be replaced by a transaction (BIP 125)"},
228  {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
229  {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
230  "\"" + FeeModes("\"\n\"") + "\""},
231  {"avoid_reuse", RPCArg::Type::BOOL, RPCArg::Default{true}, "(only available if avoid_reuse wallet flag is set) Avoid spending from dirty addresses; addresses are considered\n"
232  "dirty if they have previously been used in a transaction. If true, this also activates avoidpartialspends, grouping outputs by their addresses."},
233  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
234  {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, return extra information about the transaction."},
235  },
236  {
237  RPCResult{"if verbose is not set or set to false",
238  RPCResult::Type::STR_HEX, "txid", "The transaction id."
239  },
240  RPCResult{"if verbose is set to true",
241  RPCResult::Type::OBJ, "", "",
242  {
243  {RPCResult::Type::STR_HEX, "txid", "The transaction id."},
244  {RPCResult::Type::STR, "fee_reason", "The transaction fee reason."}
245  },
246  },
247  },
248  RPCExamples{
249  "\nSend 0.1 BTC\n"
250  + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1") +
251  "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode using positional arguments\n"
252  + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1 \"donation\" \"sean's outpost\" false true 6 economical") +
253  "\nSend 0.1 BTC with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB, subtract fee from amount, BIP125-replaceable, using positional arguments\n"
254  + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1 \"drinks\" \"room77\" true true null \"unset\" null 1.1") +
255  "\nSend 0.2 BTC with a confirmation target of 6 blocks in economical fee estimate mode using named arguments\n"
256  + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.2 conf_target=6 estimate_mode=\"economical\"") +
257  "\nSend 0.5 BTC with a fee rate of 25 " + CURRENCY_ATOM + "/vB using named arguments\n"
258  + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.5 fee_rate=25")
259  + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.5 fee_rate=25 subtractfeefromamount=false replaceable=true avoid_reuse=true comment=\"2 pizzas\" comment_to=\"jeremy\" verbose=true")
260  },
261  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
262 {
263  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
264  if (!pwallet) return UniValue::VNULL;
265 
266  // Make sure the results are valid at least up to the most recent block
267  // the user could have gotten from another RPC command prior to now
268  pwallet->BlockUntilSyncedToCurrentChain();
269 
270  LOCK(pwallet->cs_wallet);
271 
272  // Wallet comments
273  mapValue_t mapValue;
274  if (!request.params[2].isNull() && !request.params[2].get_str().empty())
275  mapValue["comment"] = request.params[2].get_str();
276  if (!request.params[3].isNull() && !request.params[3].get_str().empty())
277  mapValue["to"] = request.params[3].get_str();
278 
279  bool fSubtractFeeFromAmount = false;
280  if (!request.params[4].isNull()) {
281  fSubtractFeeFromAmount = request.params[4].get_bool();
282  }
283 
284  CCoinControl coin_control;
285  if (!request.params[5].isNull()) {
286  coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
287  }
288 
289  coin_control.m_avoid_address_reuse = GetAvoidReuseFlag(*pwallet, request.params[8]);
290  // We also enable partial spend avoidance if reuse avoidance is set.
291  coin_control.m_avoid_partial_spends |= coin_control.m_avoid_address_reuse;
292 
293  SetFeeEstimateMode(*pwallet, coin_control, /*conf_target=*/request.params[6], /*estimate_mode=*/request.params[7], /*fee_rate=*/request.params[9], /*override_min_fee=*/false);
294 
295  EnsureWalletIsUnlocked(*pwallet);
296 
297  UniValue address_amounts(UniValue::VOBJ);
298  const std::string address = request.params[0].get_str();
299  address_amounts.pushKV(address, request.params[1]);
300  UniValue subtractFeeFromAmount(UniValue::VARR);
301  if (fSubtractFeeFromAmount) {
302  subtractFeeFromAmount.push_back(address);
303  }
304 
305  std::vector<CRecipient> recipients;
306  ParseRecipients(address_amounts, subtractFeeFromAmount, recipients);
307  const bool verbose{request.params[10].isNull() ? false : request.params[10].get_bool()};
308 
309  return SendMoney(*pwallet, coin_control, recipients, mapValue, verbose);
310 },
311  };
312 }
313 
315 {
316  return RPCHelpMan{"sendmany",
317  "\nSend multiple times. Amounts are double-precision floating point numbers." +
319  {
320  {"dummy", RPCArg::Type::STR, RPCArg::Optional::NO, "Must be set to \"\" for backwards compatibility.", "\"\""},
321  {"amounts", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::NO, "The addresses and amounts",
322  {
323  {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The bitcoin address is the key, the numeric amount (can be string) in " + CURRENCY_UNIT + " is the value"},
324  },
325  },
326  {"minconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED_NAMED_ARG, "Ignored dummy value"},
327  {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED_NAMED_ARG, "A comment"},
328  {"subtractfeefrom", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The addresses.\n"
329  "The fee will be equally deducted from the amount of each selected address.\n"
330  "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
331  "If no addresses are specified here, the sender pays the fee.",
332  {
333  {"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Subtract fee from this address"},
334  },
335  },
336  {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Signal that this transaction can be replaced by a transaction (BIP 125)"},
337  {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
338  {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
339  "\"" + FeeModes("\"\n\"") + "\""},
340  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
341  {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, return extra infomration about the transaction."},
342  },
343  {
344  RPCResult{"if verbose is not set or set to false",
345  RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n"
346  "the number of addresses."
347  },
348  RPCResult{"if verbose is set to true",
349  RPCResult::Type::OBJ, "", "",
350  {
351  {RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n"
352  "the number of addresses."},
353  {RPCResult::Type::STR, "fee_reason", "The transaction fee reason."}
354  },
355  },
356  },
357  RPCExamples{
358  "\nSend two amounts to two different addresses:\n"
359  + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\"") +
360  "\nSend two amounts to two different addresses setting the confirmation and comment:\n"
361  + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\" 6 \"testing\"") +
362  "\nSend two amounts to two different addresses, subtract fee from amount:\n"
363  + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\" 1 \"\" \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") +
364  "\nAs a JSON-RPC call\n"
365  + HelpExampleRpc("sendmany", "\"\", {\"" + EXAMPLE_ADDRESS[0] + "\":0.01,\"" + EXAMPLE_ADDRESS[1] + "\":0.02}, 6, \"testing\"")
366  },
367  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
368 {
369  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
370  if (!pwallet) return UniValue::VNULL;
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
374  pwallet->BlockUntilSyncedToCurrentChain();
375 
376  LOCK(pwallet->cs_wallet);
377 
378  if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
379  throw JSONRPCError(RPC_INVALID_PARAMETER, "Dummy value must be set to \"\"");
380  }
381  UniValue sendTo = request.params[1].get_obj();
382 
383  mapValue_t mapValue;
384  if (!request.params[3].isNull() && !request.params[3].get_str().empty())
385  mapValue["comment"] = request.params[3].get_str();
386 
387  UniValue subtractFeeFromAmount(UniValue::VARR);
388  if (!request.params[4].isNull())
389  subtractFeeFromAmount = request.params[4].get_array();
390 
391  CCoinControl coin_control;
392  if (!request.params[5].isNull()) {
393  coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
394  }
395 
396  SetFeeEstimateMode(*pwallet, coin_control, /*conf_target=*/request.params[6], /*estimate_mode=*/request.params[7], /*fee_rate=*/request.params[8], /*override_min_fee=*/false);
397 
398  std::vector<CRecipient> recipients;
399  ParseRecipients(sendTo, subtractFeeFromAmount, recipients);
400  const bool verbose{request.params[9].isNull() ? false : request.params[9].get_bool()};
401 
402  return SendMoney(*pwallet, coin_control, recipients, std::move(mapValue), verbose);
403 },
404  };
405 }
406 
408 {
409  return RPCHelpMan{"settxfee",
410  "\nSet the transaction fee rate in " + CURRENCY_UNIT + "/kvB for this wallet. Overrides the global -paytxfee command line parameter.\n"
411  "Can be deactivated by passing 0 as the fee. In that case automatic fee selection will be used by default.\n",
412  {
413  {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The transaction fee rate in " + CURRENCY_UNIT + "/kvB"},
414  },
415  RPCResult{
416  RPCResult::Type::BOOL, "", "Returns true if successful"
417  },
418  RPCExamples{
419  HelpExampleCli("settxfee", "0.00001")
420  + HelpExampleRpc("settxfee", "0.00001")
421  },
422  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
423 {
424  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
425  if (!pwallet) return UniValue::VNULL;
426 
427  LOCK(pwallet->cs_wallet);
428 
429  CAmount nAmount = AmountFromValue(request.params[0]);
430  CFeeRate tx_fee_rate(nAmount, 1000);
431  CFeeRate max_tx_fee_rate(pwallet->m_default_max_tx_fee, 1000);
432  if (tx_fee_rate == CFeeRate(0)) {
433  // automatic selection
434  } else if (tx_fee_rate < pwallet->chain().relayMinFee()) {
435  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be less than min relay tx fee (%s)", pwallet->chain().relayMinFee().ToString()));
436  } else if (tx_fee_rate < pwallet->m_min_fee) {
437  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be less than wallet min fee (%s)", pwallet->m_min_fee.ToString()));
438  } else if (tx_fee_rate > max_tx_fee_rate) {
439  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("txfee cannot be more than wallet max tx fee (%s)", max_tx_fee_rate.ToString()));
440  }
441 
442  pwallet->m_pay_tx_fee = tx_fee_rate;
443  return true;
444 },
445  };
446 }
447 
448 
449 // Only includes key documentation where the key is snake_case in all RPC methods. MixedCase keys can be added later.
450 static std::vector<RPCArg> FundTxDoc(bool solving_data = true)
451 {
452  std::vector<RPCArg> args = {
453  {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
454  {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
455  "\"" + FeeModes("\"\n\"") + "\""},
456  {
457  "replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Marks this transaction as BIP125-replaceable.\n"
458  "Allows this transaction to be replaced by a transaction with higher fees"
459  },
460  };
461  if (solving_data) {
462  args.push_back({"solving_data", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "Keys and scripts needed for producing a final transaction with a dummy signature.\n"
463  "Used for fee estimation during coin selection.",
464  {
465  {
466  "pubkeys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Public keys involved in this transaction.",
467  {
468  {"pubkey", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A public key"},
469  }
470  },
471  {
472  "scripts", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Scripts involved in this transaction.",
473  {
474  {"script", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A script"},
475  }
476  },
477  {
478  "descriptors", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Descriptors that provide solving data for this transaction.",
479  {
480  {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A descriptor"},
481  }
482  },
483  }
484  });
485  }
486  return args;
487 }
488 
489 void FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& fee_out, int& change_position, const UniValue& options, CCoinControl& coinControl, bool override_min_fee)
490 {
491  // Make sure the results are valid at least up to the most recent block
492  // the user could have gotten from another RPC command prior to now
493  wallet.BlockUntilSyncedToCurrentChain();
494 
495  change_position = -1;
496  bool lockUnspents = false;
497  UniValue subtractFeeFromOutputs;
498  std::set<int> setSubtractFeeFromOutputs;
499 
500  if (!options.isNull()) {
501  if (options.type() == UniValue::VBOOL) {
502  // backward compatibility bool only fallback
503  coinControl.fAllowWatchOnly = options.get_bool();
504  }
505  else {
507  RPCTypeCheckObj(options,
508  {
509  {"add_inputs", UniValueType(UniValue::VBOOL)},
510  {"include_unsafe", UniValueType(UniValue::VBOOL)},
511  {"add_to_wallet", UniValueType(UniValue::VBOOL)},
512  {"changeAddress", UniValueType(UniValue::VSTR)},
513  {"change_address", UniValueType(UniValue::VSTR)},
514  {"changePosition", UniValueType(UniValue::VNUM)},
515  {"change_position", UniValueType(UniValue::VNUM)},
516  {"change_type", UniValueType(UniValue::VSTR)},
517  {"includeWatching", UniValueType(UniValue::VBOOL)},
518  {"include_watching", UniValueType(UniValue::VBOOL)},
519  {"inputs", UniValueType(UniValue::VARR)},
520  {"lockUnspents", UniValueType(UniValue::VBOOL)},
521  {"lock_unspents", UniValueType(UniValue::VBOOL)},
522  {"locktime", UniValueType(UniValue::VNUM)},
523  {"fee_rate", UniValueType()}, // will be checked by AmountFromValue() in SetFeeEstimateMode()
524  {"feeRate", UniValueType()}, // will be checked by AmountFromValue() below
525  {"psbt", UniValueType(UniValue::VBOOL)},
526  {"solving_data", UniValueType(UniValue::VOBJ)},
527  {"subtractFeeFromOutputs", UniValueType(UniValue::VARR)},
528  {"subtract_fee_from_outputs", UniValueType(UniValue::VARR)},
529  {"replaceable", UniValueType(UniValue::VBOOL)},
530  {"conf_target", UniValueType(UniValue::VNUM)},
531  {"estimate_mode", UniValueType(UniValue::VSTR)},
532  {"input_weights", UniValueType(UniValue::VARR)},
533  },
534  true, true);
535 
536  if (options.exists("add_inputs")) {
537  coinControl.m_allow_other_inputs = options["add_inputs"].get_bool();
538  }
539 
540  if (options.exists("changeAddress") || options.exists("change_address")) {
541  const std::string change_address_str = (options.exists("change_address") ? options["change_address"] : options["changeAddress"]).get_str();
542  CTxDestination dest = DecodeDestination(change_address_str);
543 
544  if (!IsValidDestination(dest)) {
545  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Change address must be a valid bitcoin address");
546  }
547 
548  coinControl.destChange = dest;
549  }
550 
551  if (options.exists("changePosition") || options.exists("change_position")) {
552  change_position = (options.exists("change_position") ? options["change_position"] : options["changePosition"]).getInt<int>();
553  }
554 
555  if (options.exists("change_type")) {
556  if (options.exists("changeAddress") || options.exists("change_address")) {
557  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both change address and address type options");
558  }
559  if (std::optional<OutputType> parsed = ParseOutputType(options["change_type"].get_str())) {
560  coinControl.m_change_type.emplace(parsed.value());
561  } else {
562  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown change type '%s'", options["change_type"].get_str()));
563  }
564  }
565 
566  const UniValue include_watching_option = options.exists("include_watching") ? options["include_watching"] : options["includeWatching"];
567  coinControl.fAllowWatchOnly = ParseIncludeWatchonly(include_watching_option, wallet);
568 
569  if (options.exists("lockUnspents") || options.exists("lock_unspents")) {
570  lockUnspents = (options.exists("lock_unspents") ? options["lock_unspents"] : options["lockUnspents"]).get_bool();
571  }
572 
573  if (options.exists("include_unsafe")) {
574  coinControl.m_include_unsafe_inputs = options["include_unsafe"].get_bool();
575  }
576 
577  if (options.exists("feeRate")) {
578  if (options.exists("fee_rate")) {
579  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both fee_rate (" + CURRENCY_ATOM + "/vB) and feeRate (" + CURRENCY_UNIT + "/kvB)");
580  }
581  if (options.exists("conf_target")) {
582  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both conf_target and feeRate. Please provide either a confirmation target in blocks for automatic fee estimation, or an explicit fee rate.");
583  }
584  if (options.exists("estimate_mode")) {
585  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and feeRate");
586  }
587  coinControl.m_feerate = CFeeRate(AmountFromValue(options["feeRate"]));
588  coinControl.fOverrideFeeRate = true;
589  }
590 
591  if (options.exists("subtractFeeFromOutputs") || options.exists("subtract_fee_from_outputs") )
592  subtractFeeFromOutputs = (options.exists("subtract_fee_from_outputs") ? options["subtract_fee_from_outputs"] : options["subtractFeeFromOutputs"]).get_array();
593 
594  if (options.exists("replaceable")) {
595  coinControl.m_signal_bip125_rbf = options["replaceable"].get_bool();
596  }
597  SetFeeEstimateMode(wallet, coinControl, options["conf_target"], options["estimate_mode"], options["fee_rate"], override_min_fee);
598  }
599  } else {
600  // if options is null and not a bool
602  }
603 
604  if (options.exists("solving_data")) {
605  const UniValue solving_data = options["solving_data"].get_obj();
606  if (solving_data.exists("pubkeys")) {
607  for (const UniValue& pk_univ : solving_data["pubkeys"].get_array().getValues()) {
608  const std::string& pk_str = pk_univ.get_str();
609  if (!IsHex(pk_str)) {
610  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not hex", pk_str));
611  }
612  const std::vector<unsigned char> data(ParseHex(pk_str));
613  const CPubKey pubkey(data.begin(), data.end());
614  if (!pubkey.IsFullyValid()) {
615  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not a valid public key", pk_str));
616  }
617  coinControl.m_external_provider.pubkeys.emplace(pubkey.GetID(), pubkey);
618  // Add witness script for pubkeys
619  const CScript wit_script = GetScriptForDestination(WitnessV0KeyHash(pubkey));
620  coinControl.m_external_provider.scripts.emplace(CScriptID(wit_script), wit_script);
621  }
622  }
623 
624  if (solving_data.exists("scripts")) {
625  for (const UniValue& script_univ : solving_data["scripts"].get_array().getValues()) {
626  const std::string& script_str = script_univ.get_str();
627  if (!IsHex(script_str)) {
628  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not hex", script_str));
629  }
630  std::vector<unsigned char> script_data(ParseHex(script_str));
631  const CScript script(script_data.begin(), script_data.end());
632  coinControl.m_external_provider.scripts.emplace(CScriptID(script), script);
633  }
634  }
635 
636  if (solving_data.exists("descriptors")) {
637  for (const UniValue& desc_univ : solving_data["descriptors"].get_array().getValues()) {
638  const std::string& desc_str = desc_univ.get_str();
639  FlatSigningProvider desc_out;
640  std::string error;
641  std::vector<CScript> scripts_temp;
642  std::unique_ptr<Descriptor> desc = Parse(desc_str, desc_out, error, true);
643  if (!desc) {
644  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor '%s': %s", desc_str, error));
645  }
646  desc->Expand(0, desc_out, scripts_temp, desc_out);
647  coinControl.m_external_provider.Merge(std::move(desc_out));
648  }
649  }
650  }
651 
652  if (options.exists("input_weights")) {
653  for (const UniValue& input : options["input_weights"].get_array().getValues()) {
654  uint256 txid = ParseHashO(input, "txid");
655 
656  const UniValue& vout_v = find_value(input, "vout");
657  if (!vout_v.isNum()) {
658  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
659  }
660  int vout = vout_v.getInt<int>();
661  if (vout < 0) {
662  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
663  }
664 
665  const UniValue& weight_v = find_value(input, "weight");
666  if (!weight_v.isNum()) {
667  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing weight key");
668  }
669  int64_t weight = weight_v.getInt<int64_t>();
670  const int64_t min_input_weight = GetTransactionInputWeight(CTxIn());
671  CHECK_NONFATAL(min_input_weight == 165);
672  if (weight < min_input_weight) {
673  throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, weight cannot be less than 165 (41 bytes (size of outpoint + sequence + empty scriptSig) * 4 (witness scaling factor)) + 1 (empty witness)");
674  }
675  if (weight > MAX_STANDARD_TX_WEIGHT) {
676  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, weight cannot be greater than the maximum standard tx weight of %d", MAX_STANDARD_TX_WEIGHT));
677  }
678 
679  coinControl.SetInputWeight(COutPoint(txid, vout), weight);
680  }
681  }
682 
683  if (tx.vout.size() == 0)
684  throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
685 
686  if (change_position != -1 && (change_position < 0 || (unsigned int)change_position > tx.vout.size()))
687  throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds");
688 
689  for (unsigned int idx = 0; idx < subtractFeeFromOutputs.size(); idx++) {
690  int pos = subtractFeeFromOutputs[idx].getInt<int>();
691  if (setSubtractFeeFromOutputs.count(pos))
692  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated position: %d", pos));
693  if (pos < 0)
694  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, negative position: %d", pos));
695  if (pos >= int(tx.vout.size()))
696  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, position too large: %d", pos));
697  setSubtractFeeFromOutputs.insert(pos);
698  }
699 
701 
702  if (!FundTransaction(wallet, tx, fee_out, change_position, error, lockUnspents, setSubtractFeeFromOutputs, coinControl)) {
703  throw JSONRPCError(RPC_WALLET_ERROR, error.original);
704  }
705 }
706 
707 static void SetOptionsInputWeights(const UniValue& inputs, UniValue& options)
708 {
709  if (options.exists("input_weights")) {
710  throw JSONRPCError(RPC_INVALID_PARAMETER, "Input weights should be specified in inputs rather than in options.");
711  }
712  if (inputs.size() == 0) {
713  return;
714  }
715  UniValue weights(UniValue::VARR);
716  for (const UniValue& input : inputs.getValues()) {
717  if (input.exists("weight")) {
718  weights.push_back(input);
719  }
720  }
721  options.pushKV("input_weights", weights);
722 }
723 
725 {
726  return RPCHelpMan{"fundrawtransaction",
727  "\nIf the transaction has no inputs, they will be automatically selected to meet its out value.\n"
728  "It will add at most one change output to the outputs.\n"
729  "No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n"
730  "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
731  "The inputs added will not be signed, use signrawtransactionwithkey\n"
732  "or signrawtransactionwithwallet for that.\n"
733  "All existing inputs must either have their previous output transaction be in the wallet\n"
734  "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n"
735  "Note that all inputs selected must be of standard form and P2SH scripts must be\n"
736  "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n"
737  "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n"
738  "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n",
739  {
740  {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"},
741  {"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "for backward compatibility: passing in a true instead of an object will result in {\"includeWatching\":true}",
742  Cat<std::vector<RPCArg>>(
743  {
744  {"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{true}, "For a transaction with existing inputs, automatically include more if they are not enough."},
745  {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n"
746  "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
747  "If that happens, you will need to fund the transaction with different inputs and republish it."},
748  {"changeAddress", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
749  {"changePosition", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
750  {"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."},
751  {"includeWatching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch only.\n"
752  "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n"
753  "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."},
754  {"lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
755  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
756  {"feeRate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_UNIT + "/kvB."},
757  {"subtractFeeFromOutputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The integers.\n"
758  "The fee will be equally deducted from the amount of each specified output.\n"
759  "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
760  "If no outputs are specified here, the sender pays the fee.",
761  {
762  {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
763  },
764  },
765  {"input_weights", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "Inputs and their corresponding weights",
766  {
767  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
768  {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output index"},
769  {"weight", RPCArg::Type::NUM, RPCArg::Optional::NO, "The maximum weight for this input, "
770  "including the weight of the outpoint and sequence number. "
771  "Note that serialized signature sizes are not guaranteed to be consistent, "
772  "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
773  "Remember to convert serialized sizes to weight units when necessary."},
774  },
775  },
776  },
777  FundTxDoc()),
778  "options"},
779  {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
780  "If iswitness is not present, heuristic tests will be used in decoding.\n"
781  "If true, only witness deserialization will be tried.\n"
782  "If false, only non-witness deserialization will be tried.\n"
783  "This boolean should reflect whether the transaction has inputs\n"
784  "(e.g. fully valid, or on-chain transactions), if known by the caller."
785  },
786  },
787  RPCResult{
788  RPCResult::Type::OBJ, "", "",
789  {
790  {RPCResult::Type::STR_HEX, "hex", "The resulting raw transaction (hex-encoded string)"},
791  {RPCResult::Type::STR_AMOUNT, "fee", "Fee in " + CURRENCY_UNIT + " the resulting transaction pays"},
792  {RPCResult::Type::NUM, "changepos", "The position of the added change output, or -1"},
793  }
794  },
795  RPCExamples{
796  "\nCreate a transaction with no inputs\n"
797  + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
798  "\nAdd sufficient unsigned inputs to meet the output value\n"
799  + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
800  "\nSign the transaction\n"
801  + HelpExampleCli("signrawtransactionwithwallet", "\"fundedtransactionhex\"") +
802  "\nSend the transaction\n"
803  + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
804  },
805  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
806 {
807  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
808  if (!pwallet) return UniValue::VNULL;
809 
810  RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType(), UniValue::VBOOL});
811 
812  // parse hex string from parameter
814  bool try_witness = request.params[2].isNull() ? true : request.params[2].get_bool();
815  bool try_no_witness = request.params[2].isNull() ? true : !request.params[2].get_bool();
816  if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
817  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
818  }
819 
820  CAmount fee;
821  int change_position;
822  CCoinControl coin_control;
823  // Automatically select (additional) coins. Can be overridden by options.add_inputs.
824  coin_control.m_allow_other_inputs = true;
825  FundTransaction(*pwallet, tx, fee, change_position, request.params[1], coin_control, /*override_min_fee=*/true);
826 
827  UniValue result(UniValue::VOBJ);
828  result.pushKV("hex", EncodeHexTx(CTransaction(tx)));
829  result.pushKV("fee", ValueFromAmount(fee));
830  result.pushKV("changepos", change_position);
831 
832  return result;
833 },
834  };
835 }
836 
838 {
839  return RPCHelpMan{"signrawtransactionwithwallet",
840  "\nSign inputs for raw transaction (serialized, hex-encoded).\n"
841  "The second optional argument (may be null) is an array of previous transaction outputs that\n"
842  "this transaction depends on but may not yet be in the block chain." +
844  {
845  {"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"},
846  {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "The previous dependent transaction outputs",
847  {
849  {
850  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
851  {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
852  {"scriptPubKey", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "script key"},
853  {"redeemScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2SH) redeem script"},
854  {"witnessScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2WSH or P2SH-P2WSH) witness script"},
855  {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "(required for Segwit inputs) the amount spent"},
856  },
857  },
858  },
859  },
860  {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type. Must be one of\n"
861  " \"DEFAULT\"\n"
862  " \"ALL\"\n"
863  " \"NONE\"\n"
864  " \"SINGLE\"\n"
865  " \"ALL|ANYONECANPAY\"\n"
866  " \"NONE|ANYONECANPAY\"\n"
867  " \"SINGLE|ANYONECANPAY\""},
868  },
869  RPCResult{
870  RPCResult::Type::OBJ, "", "",
871  {
872  {RPCResult::Type::STR_HEX, "hex", "The hex-encoded raw transaction with signature(s)"},
873  {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
874  {RPCResult::Type::ARR, "errors", /*optional=*/true, "Script verification errors (if there are any)",
875  {
876  {RPCResult::Type::OBJ, "", "",
877  {
878  {RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"},
879  {RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"},
880  {RPCResult::Type::ARR, "witness", "",
881  {
882  {RPCResult::Type::STR_HEX, "witness", ""},
883  }},
884  {RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"},
885  {RPCResult::Type::NUM, "sequence", "Script sequence number"},
886  {RPCResult::Type::STR, "error", "Verification or signing error related to the input"},
887  }},
888  }},
889  }
890  },
891  RPCExamples{
892  HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"")
893  + HelpExampleRpc("signrawtransactionwithwallet", "\"myhex\"")
894  },
895  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
896 {
897  const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
898  if (!pwallet) return UniValue::VNULL;
899 
900  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VSTR}, true);
901 
903  if (!DecodeHexTx(mtx, request.params[0].get_str())) {
904  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
905  }
906 
907  // Sign the transaction
908  LOCK(pwallet->cs_wallet);
909  EnsureWalletIsUnlocked(*pwallet);
910 
911  // Fetch previous transactions (inputs):
912  std::map<COutPoint, Coin> coins;
913  for (const CTxIn& txin : mtx.vin) {
914  coins[txin.prevout]; // Create empty map entry keyed by prevout.
915  }
916  pwallet->chain().findCoins(coins);
917 
918  // Parse the prevtxs array
919  ParsePrevouts(request.params[1], nullptr, coins);
920 
921  int nHashType = ParseSighashString(request.params[2]);
922 
923  // Script verification errors
924  std::map<int, bilingual_str> input_errors;
925 
926  bool complete = pwallet->SignTransaction(mtx, coins, nHashType, input_errors);
927  UniValue result(UniValue::VOBJ);
928  SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
929  return result;
930 },
931  };
932 }
933 
934 static RPCHelpMan bumpfee_helper(std::string method_name)
935 {
936  const bool want_psbt = method_name == "psbtbumpfee";
937  const std::string incremental_fee{CFeeRate(DEFAULT_INCREMENTAL_RELAY_FEE).ToString(FeeEstimateMode::SAT_VB)};
938 
939  return RPCHelpMan{method_name,
940  "\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n"
941  + std::string(want_psbt ? "Returns a PSBT instead of creating and signing a new transaction.\n" : "") +
942  "An opt-in RBF transaction with the given txid must be in the wallet.\n"
943  "The command will pay the additional fee by reducing change outputs or adding inputs when necessary.\n"
944  "It may add a new change output if one does not already exist.\n"
945  "All inputs in the original transaction will be included in the replacement transaction.\n"
946  "The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n"
947  "By default, the new fee will be calculated automatically using the estimatesmartfee RPC.\n"
948  "The user can specify a confirmation target for estimatesmartfee.\n"
949  "Alternatively, the user can specify a fee rate in " + CURRENCY_ATOM + "/vB for the new transaction.\n"
950  "At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n"
951  "returned by getnetworkinfo) to enter the node's mempool.\n"
952  "* WARNING: before version 0.21, fee_rate was in " + CURRENCY_UNIT + "/kvB. As of 0.21, fee_rate is in " + CURRENCY_ATOM + "/vB. *\n",
953  {
954  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The txid to be bumped"},
956  {
957  {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks\n"},
958  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"},
959  "\nSpecify a fee rate in " + CURRENCY_ATOM + "/vB instead of relying on the built-in fee estimator.\n"
960  "Must be at least " + incremental_fee + " higher than the current transaction fee rate.\n"
961  "WARNING: before version 0.21, fee_rate was in " + CURRENCY_UNIT + "/kvB. As of 0.21, fee_rate is in " + CURRENCY_ATOM + "/vB.\n"},
962  {"replaceable", RPCArg::Type::BOOL, RPCArg::Default{true}, "Whether the new transaction should still be\n"
963  "marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n"
964  "be left unchanged from the original. If false, any input sequence numbers in the\n"
965  "original transaction that were less than 0xfffffffe will be increased to 0xfffffffe\n"
966  "so the new transaction will not be explicitly bip-125 replaceable (though it may\n"
967  "still be replaceable in practice, for example if it has unconfirmed ancestors which\n"
968  "are replaceable).\n"},
969  {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
970  "\"" + FeeModes("\"\n\"") + "\""},
971  },
972  "options"},
973  },
974  RPCResult{
975  RPCResult::Type::OBJ, "", "", Cat(
976  want_psbt ?
977  std::vector<RPCResult>{{RPCResult::Type::STR, "psbt", "The base64-encoded unsigned PSBT of the new transaction."}} :
978  std::vector<RPCResult>{{RPCResult::Type::STR_HEX, "txid", "The id of the new transaction."}},
979  {
980  {RPCResult::Type::STR_AMOUNT, "origfee", "The fee of the replaced transaction."},
981  {RPCResult::Type::STR_AMOUNT, "fee", "The fee of the new transaction."},
982  {RPCResult::Type::ARR, "errors", "Errors encountered during processing (may be empty).",
983  {
984  {RPCResult::Type::STR, "", ""},
985  }},
986  })
987  },
988  RPCExamples{
989  "\nBump the fee, get the new transaction\'s " + std::string(want_psbt ? "psbt" : "txid") + "\n" +
990  HelpExampleCli(method_name, "<txid>")
991  },
992  [want_psbt](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
993 {
994  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
995  if (!pwallet) return UniValue::VNULL;
996 
997  if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !want_psbt) {
998  throw JSONRPCError(RPC_WALLET_ERROR, "bumpfee is not available with wallets that have private keys disabled. Use psbtbumpfee instead.");
999  }
1000 
1001  RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VOBJ});
1002  uint256 hash(ParseHashV(request.params[0], "txid"));
1003 
1004  CCoinControl coin_control;
1005  coin_control.fAllowWatchOnly = pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS);
1006  // optional parameters
1007  coin_control.m_signal_bip125_rbf = true;
1008 
1009  if (!request.params[1].isNull()) {
1010  UniValue options = request.params[1];
1011  RPCTypeCheckObj(options,
1012  {
1013  {"confTarget", UniValueType(UniValue::VNUM)},
1014  {"conf_target", UniValueType(UniValue::VNUM)},
1015  {"fee_rate", UniValueType()}, // will be checked by AmountFromValue() in SetFeeEstimateMode()
1016  {"replaceable", UniValueType(UniValue::VBOOL)},
1017  {"estimate_mode", UniValueType(UniValue::VSTR)},
1018  },
1019  true, true);
1020 
1021  if (options.exists("confTarget") && options.exists("conf_target")) {
1022  throw JSONRPCError(RPC_INVALID_PARAMETER, "confTarget and conf_target options should not both be set. Use conf_target (confTarget is deprecated).");
1023  }
1024 
1025  auto conf_target = options.exists("confTarget") ? options["confTarget"] : options["conf_target"];
1026 
1027  if (options.exists("replaceable")) {
1028  coin_control.m_signal_bip125_rbf = options["replaceable"].get_bool();
1029  }
1030  SetFeeEstimateMode(*pwallet, coin_control, conf_target, options["estimate_mode"], options["fee_rate"], /*override_min_fee=*/false);
1031  }
1032 
1033  // Make sure the results are valid at least up to the most recent block
1034  // the user could have gotten from another RPC command prior to now
1035  pwallet->BlockUntilSyncedToCurrentChain();
1036 
1037  LOCK(pwallet->cs_wallet);
1038 
1039  EnsureWalletIsUnlocked(*pwallet);
1040 
1041 
1042  std::vector<bilingual_str> errors;
1043  CAmount old_fee;
1044  CAmount new_fee;
1045  CMutableTransaction mtx;
1046  feebumper::Result res;
1047  // Targeting feerate bump.
1048  res = feebumper::CreateRateBumpTransaction(*pwallet, hash, coin_control, errors, old_fee, new_fee, mtx, /*require_mine=*/ !want_psbt);
1049  if (res != feebumper::Result::OK) {
1050  switch(res) {
1052  throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errors[0].original);
1053  break;
1055  throw JSONRPCError(RPC_INVALID_REQUEST, errors[0].original);
1056  break;
1058  throw JSONRPCError(RPC_INVALID_PARAMETER, errors[0].original);
1059  break;
1061  throw JSONRPCError(RPC_WALLET_ERROR, errors[0].original);
1062  break;
1063  default:
1064  throw JSONRPCError(RPC_MISC_ERROR, errors[0].original);
1065  break;
1066  }
1067  }
1068 
1069  UniValue result(UniValue::VOBJ);
1070 
1071  // For bumpfee, return the new transaction id.
1072  // For psbtbumpfee, return the base64-encoded unsigned PSBT of the new transaction.
1073  if (!want_psbt) {
1074  if (!feebumper::SignTransaction(*pwallet, mtx)) {
1075  throw JSONRPCError(RPC_WALLET_ERROR, "Can't sign transaction.");
1076  }
1077 
1078  uint256 txid;
1079  if (feebumper::CommitTransaction(*pwallet, hash, std::move(mtx), errors, txid) != feebumper::Result::OK) {
1080  throw JSONRPCError(RPC_WALLET_ERROR, errors[0].original);
1081  }
1082 
1083  result.pushKV("txid", txid.GetHex());
1084  } else {
1085  PartiallySignedTransaction psbtx(mtx);
1086  bool complete = false;
1087  const TransactionError err = pwallet->FillPSBT(psbtx, complete, SIGHASH_DEFAULT, false /* sign */, true /* bip32derivs */);
1089  CHECK_NONFATAL(!complete);
1091  ssTx << psbtx;
1092  result.pushKV("psbt", EncodeBase64(ssTx.str()));
1093  }
1094 
1095  result.pushKV("origfee", ValueFromAmount(old_fee));
1096  result.pushKV("fee", ValueFromAmount(new_fee));
1097  UniValue result_errors(UniValue::VARR);
1098  for (const bilingual_str& error : errors) {
1099  result_errors.push_back(error.original);
1100  }
1101  result.pushKV("errors", result_errors);
1102 
1103  return result;
1104 },
1105  };
1106 }
1107 
1108 RPCHelpMan bumpfee() { return bumpfee_helper("bumpfee"); }
1109 RPCHelpMan psbtbumpfee() { return bumpfee_helper("psbtbumpfee"); }
1110 
1112 {
1113  return RPCHelpMan{"send",
1114  "\nEXPERIMENTAL warning: this call may be changed in future releases.\n"
1115  "\nSend a transaction.\n",
1116  {
1117  {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs (key-value pairs), where none of the keys are duplicated.\n"
1118  "That is, each address can only appear once and there can only be one 'data' object.\n"
1119  "For convenience, a dictionary, which holds the key-value pairs directly, is also accepted.",
1120  {
1122  {
1123  {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + ""},
1124  },
1125  },
1127  {
1128  {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data"},
1129  },
1130  },
1131  },
1132  },
1133  {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
1134  {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
1135  "\"" + FeeModes("\"\n\"") + "\""},
1136  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
1138  Cat<std::vector<RPCArg>>(
1139  {
1140  {"add_inputs", RPCArg::Type::BOOL, RPCArg::DefaultHint{"false when \"inputs\" are specified, true otherwise"},"Automatically include coins from the wallet to cover the target amount.\n"},
1141  {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n"
1142  "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
1143  "If that happens, you will need to fund the transaction with different inputs and republish it."},
1144  {"add_to_wallet", RPCArg::Type::BOOL, RPCArg::Default{true}, "When false, returns a serialized transaction which will not be added to the wallet or broadcast"},
1145  {"change_address", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
1146  {"change_position", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
1147  {"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if change_address is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\" and \"bech32m\"."},
1148  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
1149  {"include_watching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch only.\n"
1150  "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n"
1151  "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."},
1152  {"inputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Specify inputs instead of adding them automatically. A JSON array of JSON objects",
1153  {
1154  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1155  {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1156  {"sequence", RPCArg::Type::NUM, RPCArg::Optional::NO, "The sequence number"},
1157  {"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, "
1158  "including the weight of the outpoint and sequence number. "
1159  "Note that signature sizes are not guaranteed to be consistent, "
1160  "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
1161  "Remember to convert serialized sizes to weight units when necessary."},
1162  },
1163  },
1164  {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
1165  {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
1166  {"psbt", RPCArg::Type::BOOL, RPCArg::DefaultHint{"automatic"}, "Always return a PSBT, implies add_to_wallet=false."},
1167  {"subtract_fee_from_outputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Outputs to subtract the fee from, specified as integer indices.\n"
1168  "The fee will be equally deducted from the amount of each specified output.\n"
1169  "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
1170  "If no outputs are specified here, the sender pays the fee.",
1171  {
1172  {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
1173  },
1174  },
1175  },
1176  FundTxDoc()),
1177  "options"},
1178  },
1179  RPCResult{
1180  RPCResult::Type::OBJ, "", "",
1181  {
1182  {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1183  {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."},
1184  {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
1185  {RPCResult::Type::STR, "psbt", /*optional=*/true, "If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"}
1186  }
1187  },
1188  RPCExamples{""
1189  "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode\n"
1190  + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.1}' 6 economical\n") +
1191  "Send 0.2 BTC with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB using positional arguments\n"
1192  + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.2}' null \"unset\" 1.1\n") +
1193  "Send 0.2 BTC with a fee rate of 1 " + CURRENCY_ATOM + "/vB using the options argument\n"
1194  + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.2}' null \"unset\" null '{\"fee_rate\": 1}'\n") +
1195  "Send 0.3 BTC with a fee rate of 25 " + CURRENCY_ATOM + "/vB using named arguments\n"
1196  + HelpExampleCli("-named send", "outputs='{\"" + EXAMPLE_ADDRESS[0] + "\": 0.3}' fee_rate=25\n") +
1197  "Create a transaction that should confirm the next block, with a specific input, and return result without adding to wallet or broadcasting to the network\n"
1198  + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.1}' 1 economical '{\"add_to_wallet\": false, \"inputs\": [{\"txid\":\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\", \"vout\":1}]}'")
1199  },
1200  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1201  {
1202  RPCTypeCheck(request.params, {
1203  UniValueType(), // outputs (ARR or OBJ, checked later)
1204  UniValue::VNUM, // conf_target
1205  UniValue::VSTR, // estimate_mode
1206  UniValueType(), // fee_rate, will be checked by AmountFromValue() in SetFeeEstimateMode()
1207  UniValue::VOBJ, // options
1208  }, true
1209  );
1210 
1211  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
1212  if (!pwallet) return UniValue::VNULL;
1213 
1214  UniValue options{request.params[4].isNull() ? UniValue::VOBJ : request.params[4]};
1215  InterpretFeeEstimationInstructions(/*conf_target=*/request.params[1], /*estimate_mode=*/request.params[2], /*fee_rate=*/request.params[3], options);
1216  PreventOutdatedOptions(options);
1217 
1218 
1219  CAmount fee;
1220  int change_position;
1221  bool rbf{options.exists("replaceable") ? options["replaceable"].get_bool() : pwallet->m_signal_rbf};
1222  CMutableTransaction rawTx = ConstructTransaction(options["inputs"], request.params[0], options["locktime"], rbf);
1223  CCoinControl coin_control;
1224  // Automatically select coins, unless at least one is manually selected. Can
1225  // be overridden by options.add_inputs.
1226  coin_control.m_allow_other_inputs = rawTx.vin.size() == 0;
1227  SetOptionsInputWeights(options["inputs"], options);
1228  FundTransaction(*pwallet, rawTx, fee, change_position, options, coin_control, /*override_min_fee=*/false);
1229 
1230  return FinishTransaction(pwallet, options, rawTx);
1231  }
1232  };
1233 }
1234 
1236 {
1237  return RPCHelpMan{"sendall",
1238  "EXPERIMENTAL warning: this call may be changed in future releases.\n"
1239  "\nSpend the value of all (or specific) confirmed UTXOs in the wallet to one or more recipients.\n"
1240  "Unconfirmed inbound UTXOs and locked UTXOs will not be spent. Sendall will respect the avoid_reuse wallet flag.\n"
1241  "If your wallet contains many small inputs, either because it received tiny payments or as a result of accumulating change, consider using `send_max` to exclude inputs that are worth less than the fees needed to spend them.\n",
1242  {
1243  {"recipients", RPCArg::Type::ARR, RPCArg::Optional::NO, "The sendall destinations. Each address may only appear once.\n"
1244  "Optionally some recipients can be specified with an amount to perform payments, but at least one address must appear without a specified amount.\n",
1245  {
1246  {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "A bitcoin address which receives an equal share of the unspecified amount."},
1248  {
1249  {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + ""},
1250  },
1251  },
1252  },
1253  },
1254  {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
1255  {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
1256  "\"" + FeeModes("\"\n\"") + "\""},
1257  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
1258  {
1260  Cat<std::vector<RPCArg>>(
1261  {
1262  {"add_to_wallet", RPCArg::Type::BOOL, RPCArg::Default{true}, "When false, returns the serialized transaction without broadcasting or adding it to the wallet"},
1263  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
1264  {"include_watching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch-only.\n"
1265  "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n"
1266  "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."},
1267  {"inputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Use exactly the specified inputs to build the transaction. Specifying inputs is incompatible with send_max.",
1268  {
1270  {
1271  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1272  {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1273  {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
1274  },
1275  },
1276  },
1277  },
1278  {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
1279  {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
1280  {"psbt", RPCArg::Type::BOOL, RPCArg::DefaultHint{"automatic"}, "Always return a PSBT, implies add_to_wallet=false."},
1281  {"send_max", RPCArg::Type::BOOL, RPCArg::Default{false}, "When true, only use UTXOs that can pay for their own fees to maximize the output amount. When 'false' (default), no UTXO is left behind. send_max is incompatible with providing specific inputs."},
1282  },
1283  FundTxDoc()
1284  ),
1285  "options"
1286  },
1287  },
1288  RPCResult{
1289  RPCResult::Type::OBJ, "", "",
1290  {
1291  {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1292  {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."},
1293  {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
1294  {RPCResult::Type::STR, "psbt", /*optional=*/true, "If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"}
1295  }
1296  },
1297  RPCExamples{""
1298  "\nSpend all UTXOs from the wallet with a fee rate of 1 " + CURRENCY_ATOM + "/vB using named arguments\n"
1299  + HelpExampleCli("-named sendall", "recipients='[\"" + EXAMPLE_ADDRESS[0] + "\"]' fee_rate=1\n") +
1300  "Spend all UTXOs with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB using positional arguments\n"
1301  + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\"]' null \"unset\" 1.1\n") +
1302  "Spend all UTXOs split into equal amounts to two addresses with a fee rate of 1.5 " + CURRENCY_ATOM + "/vB using the options argument\n"
1303  + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\", \"" + EXAMPLE_ADDRESS[1] + "\"]' null \"unset\" null '{\"fee_rate\": 1.5}'\n") +
1304  "Leave dust UTXOs in wallet, spend only UTXOs with positive effective value with a fee rate of 10 " + CURRENCY_ATOM + "/vB using the options argument\n"
1305  + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\"]' null \"unset\" null '{\"fee_rate\": 10, \"send_max\": true}'\n") +
1306  "Spend all UTXOs with a fee rate of 1.3 " + CURRENCY_ATOM + "/vB using named arguments and sending a 0.25 " + CURRENCY_UNIT + " to another recipient\n"
1307  + HelpExampleCli("-named sendall", "recipients='[{\"" + EXAMPLE_ADDRESS[1] + "\": 0.25}, \""+ EXAMPLE_ADDRESS[0] + "\"]' fee_rate=1.3\n")
1308  },
1309  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1310  {
1311  RPCTypeCheck(request.params, {
1312  UniValue::VARR, // recipients
1313  UniValue::VNUM, // conf_target
1314  UniValue::VSTR, // estimate_mode
1315  UniValueType(), // fee_rate, will be checked by AmountFromValue() in SetFeeEstimateMode()
1316  UniValue::VOBJ, // options
1317  }, true
1318  );
1319 
1320  std::shared_ptr<CWallet> const pwallet{GetWalletForJSONRPCRequest(request)};
1321  if (!pwallet) return UniValue::VNULL;
1322  // Make sure the results are valid at least up to the most recent block
1323  // the user could have gotten from another RPC command prior to now
1324  pwallet->BlockUntilSyncedToCurrentChain();
1325 
1326  UniValue options{request.params[4].isNull() ? UniValue::VOBJ : request.params[4]};
1327  InterpretFeeEstimationInstructions(/*conf_target=*/request.params[1], /*estimate_mode=*/request.params[2], /*fee_rate=*/request.params[3], options);
1328  PreventOutdatedOptions(options);
1329 
1330 
1331  std::set<std::string> addresses_without_amount;
1332  UniValue recipient_key_value_pairs(UniValue::VARR);
1333  const UniValue& recipients{request.params[0]};
1334  for (unsigned int i = 0; i < recipients.size(); ++i) {
1335  const UniValue& recipient{recipients[i]};
1336  if (recipient.isStr()) {
1337  UniValue rkvp(UniValue::VOBJ);
1338  rkvp.pushKV(recipient.get_str(), 0);
1339  recipient_key_value_pairs.push_back(rkvp);
1340  addresses_without_amount.insert(recipient.get_str());
1341  } else {
1342  recipient_key_value_pairs.push_back(recipient);
1343  }
1344  }
1345 
1346  if (addresses_without_amount.size() == 0) {
1347  throw JSONRPCError(RPC_INVALID_PARAMETER, "Must provide at least one address without a specified amount");
1348  }
1349 
1350  CCoinControl coin_control;
1351 
1352  SetFeeEstimateMode(*pwallet, coin_control, options["conf_target"], options["estimate_mode"], options["fee_rate"], /*override_min_fee=*/false);
1353 
1354  coin_control.fAllowWatchOnly = ParseIncludeWatchonly(options["include_watching"], *pwallet);
1355 
1356  const bool rbf{options.exists("replaceable") ? options["replaceable"].get_bool() : pwallet->m_signal_rbf};
1357 
1358  FeeCalculation fee_calc_out;
1359  CFeeRate fee_rate{GetMinimumFeeRate(*pwallet, coin_control, &fee_calc_out)};
1360  // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
1361  // provided one
1362  if (coin_control.m_feerate && fee_rate > *coin_control.m_feerate) {
1363  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Fee rate (%s) is lower than the minimum fee rate setting (%s)", coin_control.m_feerate->ToString(FeeEstimateMode::SAT_VB), fee_rate.ToString(FeeEstimateMode::SAT_VB)));
1364  }
1365  if (fee_calc_out.reason == FeeReason::FALLBACK && !pwallet->m_allow_fallback_fee) {
1366  // eventually allow a fallback fee
1367  throw JSONRPCError(RPC_WALLET_ERROR, "Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.");
1368  }
1369 
1370  CMutableTransaction rawTx{ConstructTransaction(options["inputs"], recipient_key_value_pairs, options["locktime"], rbf)};
1371  LOCK(pwallet->cs_wallet);
1372 
1373  CAmount total_input_value(0);
1374  bool send_max{options.exists("send_max") ? options["send_max"].get_bool() : false};
1375  if (options.exists("inputs") && options.exists("send_max")) {
1376  throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot combine send_max with specific inputs.");
1377  } else if (options.exists("inputs")) {
1378  for (const CTxIn& input : rawTx.vin) {
1379  if (pwallet->IsSpent(input.prevout)) {
1380  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input not available. UTXO (%s:%d) was already spent.", input.prevout.hash.ToString(), input.prevout.n));
1381  }
1382  const CWalletTx* tx{pwallet->GetWalletTx(input.prevout.hash)};
1383  if (!tx || input.prevout.n >= tx->tx->vout.size() || !(pwallet->IsMine(tx->tx->vout[input.prevout.n]) & (coin_control.fAllowWatchOnly ? ISMINE_ALL : ISMINE_SPENDABLE))) {
1384  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input not found. UTXO (%s:%d) is not part of wallet.", input.prevout.hash.ToString(), input.prevout.n));
1385  }
1386  total_input_value += tx->tx->vout[input.prevout.n].nValue;
1387  }
1388  } else {
1389  for (const COutput& output : AvailableCoins(*pwallet, &coin_control, fee_rate, /*nMinimumAmount=*/0).All()) {
1390  CHECK_NONFATAL(output.input_bytes > 0);
1391  if (send_max && fee_rate.GetFee(output.input_bytes) > output.txout.nValue) {
1392  continue;
1393  }
1394  CTxIn input(output.outpoint.hash, output.outpoint.n, CScript(), rbf ? MAX_BIP125_RBF_SEQUENCE : CTxIn::SEQUENCE_FINAL);
1395  rawTx.vin.push_back(input);
1396  total_input_value += output.txout.nValue;
1397  }
1398  }
1399 
1400  // estimate final size of tx
1401  const TxSize tx_size{CalculateMaximumSignedTxSize(CTransaction(rawTx), pwallet.get())};
1402  const CAmount fee_from_size{fee_rate.GetFee(tx_size.vsize)};
1403  const CAmount effective_value{total_input_value - fee_from_size};
1404 
1405  if (fee_from_size > pwallet->m_default_max_tx_fee) {
1407  }
1408 
1409  if (effective_value <= 0) {
1410  if (send_max) {
1411  throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Total value of UTXO pool too low to pay for transaction, try using lower feerate.");
1412  } else {
1413  throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Total value of UTXO pool too low to pay for transaction. Try using lower feerate or excluding uneconomic UTXOs with 'send_max' option.");
1414  }
1415  }
1416 
1417  // If this transaction is too large, e.g. because the wallet has many UTXOs, it will be rejected by the node's mempool.
1418  if (tx_size.weight > MAX_STANDARD_TX_WEIGHT) {
1419  throw JSONRPCError(RPC_WALLET_ERROR, "Transaction too large.");
1420  }
1421 
1422  CAmount output_amounts_claimed{0};
1423  for (const CTxOut& out : rawTx.vout) {
1424  output_amounts_claimed += out.nValue;
1425  }
1426 
1427  if (output_amounts_claimed > total_input_value) {
1428  throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Assigned more value to outputs than available funds.");
1429  }
1430 
1431  const CAmount remainder{effective_value - output_amounts_claimed};
1432  if (remainder < 0) {
1433  throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds for fees after creating specified outputs.");
1434  }
1435 
1436  const CAmount per_output_without_amount{remainder / (long)addresses_without_amount.size()};
1437 
1438  bool gave_remaining_to_first{false};
1439  for (CTxOut& out : rawTx.vout) {
1440  CTxDestination dest;
1441  ExtractDestination(out.scriptPubKey, dest);
1442  std::string addr{EncodeDestination(dest)};
1443  if (addresses_without_amount.count(addr) > 0) {
1444  out.nValue = per_output_without_amount;
1445  if (!gave_remaining_to_first) {
1446  out.nValue += remainder % addresses_without_amount.size();
1447  gave_remaining_to_first = true;
1448  }
1449  if (IsDust(out, pwallet->chain().relayDustFee())) {
1450  // Dynamically generated output amount is dust
1451  throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Dynamically assigned remainder results in dust output.");
1452  }
1453  } else {
1454  if (IsDust(out, pwallet->chain().relayDustFee())) {
1455  // Specified output amount is dust
1456  throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Specified output amount to %s is below dust threshold.", addr));
1457  }
1458  }
1459  }
1460 
1461  const bool lock_unspents{options.exists("lock_unspents") ? options["lock_unspents"].get_bool() : false};
1462  if (lock_unspents) {
1463  for (const CTxIn& txin : rawTx.vin) {
1464  pwallet->LockCoin(txin.prevout);
1465  }
1466  }
1467 
1468  return FinishTransaction(pwallet, options, rawTx);
1469  }
1470  };
1471 }
1472 
1474 {
1475  return RPCHelpMan{"walletprocesspsbt",
1476  "\nUpdate a PSBT with input information from our wallet and then sign inputs\n"
1477  "that we can sign for." +
1479  {
1480  {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction base64 string"},
1481  {"sign", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also sign the transaction when updating (requires wallet to be unlocked)"},
1482  {"sighashtype", RPCArg::Type::STR, RPCArg::Default{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type to sign with if not specified by the PSBT. Must be one of\n"
1483  " \"DEFAULT\"\n"
1484  " \"ALL\"\n"
1485  " \"NONE\"\n"
1486  " \"SINGLE\"\n"
1487  " \"ALL|ANYONECANPAY\"\n"
1488  " \"NONE|ANYONECANPAY\"\n"
1489  " \"SINGLE|ANYONECANPAY\""},
1490  {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"},
1491  {"finalize", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also finalize inputs if possible"},
1492  },
1493  RPCResult{
1494  RPCResult::Type::OBJ, "", "",
1495  {
1496  {RPCResult::Type::STR, "psbt", "The base64-encoded partially signed transaction"},
1497  {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1498  }
1499  },
1500  RPCExamples{
1501  HelpExampleCli("walletprocesspsbt", "\"psbt\"")
1502  },
1503  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1504 {
1505  const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
1506  if (!pwallet) return UniValue::VNULL;
1507 
1508  const CWallet& wallet{*pwallet};
1509  // Make sure the results are valid at least up to the most recent block
1510  // the user could have gotten from another RPC command prior to now
1511  wallet.BlockUntilSyncedToCurrentChain();
1512 
1513  RPCTypeCheck(request.params, {UniValue::VSTR});
1514 
1515  // Unserialize the transaction
1517  std::string error;
1518  if (!DecodeBase64PSBT(psbtx, request.params[0].get_str(), error)) {
1519  throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", error));
1520  }
1521 
1522  // Get the sighash type
1523  int nHashType = ParseSighashString(request.params[2]);
1524 
1525  // Fill transaction with our data and also sign
1526  bool sign = request.params[1].isNull() ? true : request.params[1].get_bool();
1527  bool bip32derivs = request.params[3].isNull() ? true : request.params[3].get_bool();
1528  bool finalize = request.params[4].isNull() ? true : request.params[4].get_bool();
1529  bool complete = true;
1530 
1531  if (sign) EnsureWalletIsUnlocked(*pwallet);
1532 
1533  const TransactionError err{wallet.FillPSBT(psbtx, complete, nHashType, sign, bip32derivs, nullptr, finalize)};
1534  if (err != TransactionError::OK) {
1535  throw JSONRPCTransactionError(err);
1536  }
1537 
1538  UniValue result(UniValue::VOBJ);
1540  ssTx << psbtx;
1541  result.pushKV("psbt", EncodeBase64(ssTx.str()));
1542  result.pushKV("complete", complete);
1543 
1544  return result;
1545 },
1546  };
1547 }
1548 
1550 {
1551  return RPCHelpMan{"walletcreatefundedpsbt",
1552  "\nCreates and funds a transaction in the Partially Signed Transaction format.\n"
1553  "Implements the Creator and Updater roles.\n"
1554  "All existing inputs must either have their previous output transaction be in the wallet\n"
1555  "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n",
1556  {
1557  {"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "Leave empty to add inputs automatically. See add_inputs option.",
1558  {
1560  {
1561  {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1562  {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1563  {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'locktime' and 'options.replaceable' arguments"}, "The sequence number"},
1564  {"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, "
1565  "including the weight of the outpoint and sequence number. "
1566  "Note that signature sizes are not guaranteed to be consistent, "
1567  "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
1568  "Remember to convert serialized sizes to weight units when necessary."},
1569  },
1570  },
1571  },
1572  },
1573  {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs (key-value pairs), where none of the keys are duplicated.\n"
1574  "That is, each address can only appear once and there can only be one 'data' object.\n"
1575  "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
1576  "accepted as second parameter.",
1577  {
1579  {
1580  {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address, the value (float or string) is the amount in " + CURRENCY_UNIT + ""},
1581  },
1582  },
1584  {
1585  {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data"},
1586  },
1587  },
1588  },
1589  },
1590  {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
1592  Cat<std::vector<RPCArg>>(
1593  {
1594  {"add_inputs", RPCArg::Type::BOOL, RPCArg::DefaultHint{"false when \"inputs\" are specified, true otherwise"}, "Automatically include coins from the wallet to cover the target amount.\n"},
1595  {"include_unsafe", RPCArg::Type::BOOL, RPCArg::Default{false}, "Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n"
1596  "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
1597  "If that happens, you will need to fund the transaction with different inputs and republish it."},
1598  {"changeAddress", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
1599  {"changePosition", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
1600  {"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."},
1601  {"includeWatching", RPCArg::Type::BOOL, RPCArg::DefaultHint{"true for watch-only wallets, otherwise false"}, "Also select inputs which are watch only"},
1602  {"lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
1603  {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
1604  {"feeRate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_UNIT + "/kvB."},
1605  {"subtractFeeFromOutputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The outputs to subtract the fee from.\n"
1606  "The fee will be equally deducted from the amount of each specified output.\n"
1607  "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
1608  "If no outputs are specified here, the sender pays the fee.",
1609  {
1610  {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
1611  },
1612  },
1613  },
1614  FundTxDoc()),
1615  "options"},
1616  {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"},
1617  },
1618  RPCResult{
1619  RPCResult::Type::OBJ, "", "",
1620  {
1621  {RPCResult::Type::STR, "psbt", "The resulting raw transaction (base64-encoded string)"},
1622  {RPCResult::Type::STR_AMOUNT, "fee", "Fee in " + CURRENCY_UNIT + " the resulting transaction pays"},
1623  {RPCResult::Type::NUM, "changepos", "The position of the added change output, or -1"},
1624  }
1625  },
1626  RPCExamples{
1627  "\nCreate a transaction with no inputs\n"
1628  + HelpExampleCli("walletcreatefundedpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
1629  },
1630  [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue
1631 {
1632  std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
1633  if (!pwallet) return UniValue::VNULL;
1634 
1635  CWallet& wallet{*pwallet};
1636  // Make sure the results are valid at least up to the most recent block
1637  // the user could have gotten from another RPC command prior to now
1638  wallet.BlockUntilSyncedToCurrentChain();
1639 
1640  RPCTypeCheck(request.params, {
1641  UniValue::VARR,
1642  UniValueType(), // ARR or OBJ, checked later
1643  UniValue::VNUM,
1644  UniValue::VOBJ,
1645  UniValue::VBOOL
1646  }, true
1647  );
1648 
1649  UniValue options{request.params[3].isNull() ? UniValue::VOBJ : request.params[3]};
1650 
1651  CAmount fee;
1652  int change_position;
1653  bool rbf{wallet.m_signal_rbf};
1654  const UniValue &replaceable_arg = options["replaceable"];
1655  if (!replaceable_arg.isNull()) {
1656  RPCTypeCheckArgument(replaceable_arg, UniValue::VBOOL);
1657  rbf = replaceable_arg.isTrue();
1658  }
1659  CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf);
1660  CCoinControl coin_control;
1661  // Automatically select coins, unless at least one is manually selected. Can
1662  // be overridden by options.add_inputs.
1663  coin_control.m_allow_other_inputs = rawTx.vin.size() == 0;
1664  SetOptionsInputWeights(request.params[0], options);
1665  FundTransaction(wallet, rawTx, fee, change_position, options, coin_control, /*override_min_fee=*/true);
1666 
1667  // Make a blank psbt
1668  PartiallySignedTransaction psbtx(rawTx);
1669 
1670  // Fill transaction with out data but don't sign
1671  bool bip32derivs = request.params[4].isNull() ? true : request.params[4].get_bool();
1672  bool complete = true;
1673  const TransactionError err{wallet.FillPSBT(psbtx, complete, 1, false, bip32derivs)};
1674  if (err != TransactionError::OK) {
1675  throw JSONRPCTransactionError(err);
1676  }
1677 
1678  // Serialize the PSBT
1680  ssTx << psbtx;
1681 
1682  UniValue result(UniValue::VOBJ);
1683  result.pushKV("psbt", EncodeBase64(ssTx.str()));
1684  result.pushKV("fee", ValueFromAmount(fee));
1685  result.pushKV("changepos", change_position);
1686  return result;
1687 },
1688  };
1689 }
1690 } // namespace wallet
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:414
CAmount nValue
Definition: transaction.h:159
static RPCHelpMan bumpfee_helper(std::string method_name)
Definition: spend.cpp:934
void FundTransaction(CWallet &wallet, CMutableTransaction &tx, CAmount &fee_out, int &change_position, const UniValue &options, CCoinControl &coinControl, bool override_min_fee)
Definition: spend.cpp:489
void push_back(UniValue val)
Definition: univalue.cpp:104
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
Definition: coincontrol.h:52
std::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
Definition: coincontrol.h:48
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
Definition: policy.h:35
const std::vector< UniValue > & getValues() const
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
Definition: standard.cpp:237
RPCHelpMan sendmany()
Definition: spend.cpp:314
CScript scriptPubKey
Definition: transaction.h:160
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
Definition: util.cpp:58
bool get_bool() const
void ParsePrevouts(const UniValue &prevTxsUnival, FillableSigningProvider *keystore, std::map< COutPoint, Coin > &coins)
Parse a prevtxs UniValue array and get the map of coins from it.
Required arg.
Bilingual messages:
Definition: translation.h:18
CoinsResult AvailableCoins(const CWallet &wallet, const CCoinControl *coinControl, std::optional< CFeeRate > feerate, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount, bool only_spendable)
Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
Definition: spend.cpp:144
CTxDestination destChange
Custom change destination, if not set an address is generated.
Definition: coincontrol.h:33
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
std::map< std::string, std::string > mapValue_t
Definition: transaction.h:111
RPCHelpMan sendtoaddress()
Definition: spend.cpp:212
std::vector< CTxIn > vin
Definition: transaction.h:374
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
Definition: transaction.h:88
std::string str() const
Definition: streams.h:224
#define CHECK_NONFATAL(condition)
Identity function.
Definition: check.h:47
RPCHelpMan psbtbumpfee()
Definition: spend.cpp:1109
bool IsHex(std::string_view str)
FeeReason reason
Definition: fees.h:79
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
Definition: standard.cpp:356
bool ParseIncludeWatchonly(const UniValue &include_watchonly, const CWallet &wallet)
Used by RPC commands that have an include_watchonly parameter.
Definition: util.cpp:34
static std::vector< RPCArg > FundTxDoc(bool solving_data=true)
Definition: spend.cpp:450
std::string EncodeBase64(Span< const unsigned char > input)
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
Definition: coincontrol.h:42
const std::string & get_str() const
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Definition: util.cpp:21
Use sat/vB fee rate unit.
bool isNum() const
Definition: univalue.h:79
const UniValue & get_array() const
unsigned int ParseConfirmTarget(const UniValue &value, unsigned int max_target)
Parse a confirm target option and raise an RPC error if it is invalid.
Definition: util.cpp:340
bilingual_str TransactionErrorString(const TransactionError err)
Definition: error.cpp:13
FlatSigningProvider m_external_provider
SigningProvider that has pubkeys and scripts to do spend size estimation for external inputs...
Definition: coincontrol.h:62
A version of CTransaction with the PSBT format.
Definition: psbt.h:946
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:185
static void SetOptionsInputWeights(const UniValue &inputs, UniValue &options)
Definition: spend.cpp:707
const std::vector< std::string > & getKeys() const
RPCHelpMan send()
Definition: spend.cpp:1111
Int getInt() const
Definition: univalue.h:137
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:33
bool FinalizeAndExtractPSBT(PartiallySignedTransaction &psbtx, CMutableTransaction &result)
Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized...
Definition: psbt.cpp:417
RPCHelpMan sendall()
Definition: spend.cpp:1235
void SignTransactionResultToJSON(CMutableTransaction &mtx, bool complete, const std::map< COutPoint, Coin > &coins, const std::map< int, bilingual_str > &input_errors, UniValue &result)
ArgsManager args
Invalid, missing or duplicate parameter.
Definition: protocol.h:43
Result CommitTransaction(CWallet &wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
Definition: feebumper.cpp:299
const UniValue & find_value(const UniValue &obj, const std::string &name)
Definition: univalue.cpp:233
std::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
Definition: coincontrol.h:35
RPCHelpMan walletcreatefundedpsbt()
Definition: spend.cpp:1549
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
A transaction with a bunch of additional info that only the owner cares about.
Definition: transaction.h:137
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
Definition: util.cpp:50
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Special type that is a STR with only hex chars.
static void SetFeeEstimateMode(const CWallet &wallet, CCoinControl &cc, const UniValue &conf_target, const UniValue &estimate_mode, const UniValue &fee_rate, bool override_min_fee)
Update coin control with fee estimation based on the given parameters.
Definition: spend.cpp:188
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
Definition: util.cpp:184
RPCHelpMan fundrawtransaction()
Definition: spend.cpp:724
void push_back(const T &value)
Definition: prevector.h:431
std::vector< Byte > ParseHex(std::string_view str)
Parse the hex string into bytes (uint8_t or std::byte).
uint256 ParseHashO(const UniValue &o, std::string strKey)
Definition: util.cpp:109
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
Definition: rbf.h:12
UniValue JSONRPCError(int code, const std::string &message)
Definition: request.cpp:56
RPCHelpMan signrawtransactionwithwallet()
Definition: spend.cpp:837
Special string with only hex chars.
const std::string CURRENCY_ATOM
Definition: feerate.h:18
static CAmount AmountFromValue(const UniValue &value)
Definition: bitcoin-tx.cpp:550
RPCHelpMan walletprocesspsbt()
Definition: spend.cpp:1473
static void ParseRecipients(const UniValue &address_amounts, const UniValue &subtract_fee_outputs, std::vector< CRecipient > &recipients)
Definition: spend.cpp:26
std::map< CScriptID, CScript > scripts
int ParseSighashString(const UniValue &sighash)
Definition: core_read.cpp:255
An input of a transaction.
Definition: transaction.h:73
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:458
static int64_t GetTransactionInputWeight(const CTxIn &txin)
Definition: validation.h:156
#define LOCK(cs)
Definition: sync.h:261
bool exists(const std::string &key) const
Definition: univalue.h:72
std::optional< OutputType > ParseOutputType(const std::string &type)
Definition: outputtype.cpp:25
Fast randomness source.
Definition: random.h:142
An encapsulated public key.
Definition: pubkey.h:33
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
Definition: feerate.cpp:39
std::map< CKeyID, CPubKey > pubkeys
static constexpr unsigned int MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we&#39;re willing to relay/mine.
Definition: policy.h:27
uint32_t n
Definition: transaction.h:38
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e...
bool fOverrideFeeRate
Override automatic min/max checks on fee, m_feerate must be set if true.
Definition: coincontrol.h:44
const std::string CURRENCY_UNIT
Definition: feerate.h:17
void SetInputWeight(const COutPoint &outpoint, int64_t weight)
Definition: coincontrol.h:117
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
Definition: wallet.h:235
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
Definition: standard.h:149
General application defined errors.
Definition: protocol.h:39
CMutableTransaction ConstructTransaction(const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime, std::optional< bool > rbf)
Create a transaction from univalue parameters.
std::string DefaultHint
Definition: util.h:169
An output of a transaction.
Definition: transaction.h:156
std::string ToString() const
Definition: uint256.cpp:64
Invalid address or key.
Definition: protocol.h:41
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
Definition: standard.cpp:334
const std::string InvalidEstimateModeErrorMessage()
Definition: fees.cpp:52
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:34
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
Definition: util.cpp:166
std::vector< CTxOut > vout
Definition: transaction.h:375
Definition: node.h:39
const std::string HELP_REQUIRING_PASSPHRASE
Definition: util.cpp:17
bool isNull() const
Definition: univalue.h:74
bool isTrue() const
Definition: univalue.h:75
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector< CTxOut > &txouts, const CCoinControl *coin_control)
Calculate the size of the transaction using CoinControl to determine whether to expect signature grin...
Definition: spend.cpp:47
Optional arg that is a named argument and has a default value of null.
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
Definition: coincontrol.h:54
std::string FeeModes(const std::string &delimiter)
Definition: fees.cpp:47
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee rate considering user set parameters and the required fee.
Definition: fees.cpp:29
FlatSigningProvider & Merge(FlatSigningProvider &&b) LIFETIMEBOUND
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:415
static void PreventOutdatedOptions(const UniValue &options)
Definition: spend.cpp:122
bool SignTransaction(CWallet &wallet, CMutableTransaction &mtx)
Sign the new transaction,.
Definition: feebumper.cpp:294
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Definition: util.cpp:100
256-bit opaque blob.
Definition: uint256.h:119
Optional argument with default value omitted because they are implicitly clear.
enum VType type() const
Definition: univalue.h:125
Special string to represent a floating point amount.
void pushKV(std::string key, UniValue val)
Definition: univalue.cpp:126
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:410
bool m_include_unsafe_inputs
If false, only safe inputs will be used.
Definition: coincontrol.h:37
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
Not enough funds in wallet or account.
Definition: protocol.h:72
FeeEstimateMode m_fee_mode
Fee estimation mode to control arguments to estimateSmartFee.
Definition: coincontrol.h:56
const UniValue & get_obj() const
Special type representing a floating point amount (can be either NUM or STR)
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
Definition: core_read.cpp:195
std::string GetHex() const
Definition: uint256.cpp:20
bool m_allow_other_inputs
If true, the selection process can add extra unselected inputs from the wallet while requires all sel...
Definition: coincontrol.h:40
UniValue ValueFromAmount(const CAmount amount)
Definition: core_write.cpp:26
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Definition: core_write.cpp:143
TransactionError
Definition: error.h:22
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
Definition: feerate.h:32
const UniValue NullUniValue
Definition: univalue.cpp:16
bool GetAvoidReuseFlag(const CWallet &wallet, const UniValue &param)
Definition: util.cpp:19
void EnsureWalletIsUnlocked(const CWallet &wallet)
Definition: util.cpp:79
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, int change_pos, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
Definition: spend.cpp:1050
bilingual_str ErrorString(const Result< T > &result)
Definition: result.h:78
A reference to a CScript: the Hash160 of its serialization (see script.h)
Definition: standard.h:26
std::string EncodeDestination(const CTxDestination &dest)
Definition: key_io.cpp:276
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Definition: policy.cpp:65
Standard JSON-RPC 2.0 errors.
Definition: protocol.h:28
A mutable version of CTransaction.
Definition: transaction.h:372
Wallet errors.
Definition: protocol.h:71
size_t size() const
Definition: univalue.h:65
The basic transaction that is broadcasted on the network and contained in blocks. ...
Definition: transaction.h:287
static void InterpretFeeEstimationInstructions(const UniValue &conf_target, const UniValue &estimate_mode, const UniValue &fee_rate, UniValue &options)
Definition: spend.cpp:57
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
Definition: util.cpp:369
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Definition: fees.cpp:57
RPCHelpMan bumpfee()
Definition: spend.cpp:1108
Result CreateRateBumpTransaction(CWallet &wallet, const uint256 &txid, const CCoinControl &coin_control, std::vector< bilingual_str > &errors, CAmount &old_fee, CAmount &new_fee, CMutableTransaction &mtx, bool require_mine)
Create bumpfee transaction based on feerate estimates.
Definition: feebumper.cpp:157
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
Definition: key_io.cpp:281
static UniValue FinishTransaction(const std::shared_ptr< CWallet > pwallet, const UniValue &options, const CMutableTransaction &rawTx)
Definition: spend.cpp:79
std::optional< bool > m_signal_bip125_rbf
Override the wallet&#39;s m_signal_rbf if set.
Definition: coincontrol.h:50
COutPoint prevout
Definition: transaction.h:76
A UTXO under consideration for use in funding a new transaction.
Definition: coinselection.h:22
std::optional< CFeeRate > m_feerate
Override the wallet&#39;s m_pay_tx_fee if set.
Definition: coincontrol.h:46
bool error(const char *fmt, const Args &... args)
Definition: system.h:48
std::string StringForFeeReason(FeeReason reason)
Definition: fees.cpp:17
Coin Control Features.
Definition: coincontrol.h:29
Wrapper for UniValue::VType, which includes typeAny: Used to denote don&#39;t care type.
Definition: util.h:58
std::shared_ptr< CWallet > GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
Definition: util.cpp:55
UniValue SendMoney(CWallet &wallet, const CCoinControl &coin_control, std::vector< CRecipient > &recipients, mapValue_t map_value, bool verbose)
Definition: spend.cpp:144
Error parsing or validating structure in raw format.
Definition: protocol.h:45
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
Definition: vector.h:32
void RPCTypeCheck(const UniValue &params, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.
Definition: util.cpp:33
RPCHelpMan settxfee()
Definition: spend.cpp:407
uint256 hash
Definition: transaction.h:37