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