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