28 std::set<CTxDestination> destinations;
30 for (
const std::string& address: address_amounts.
getKeys()) {
36 if (destinations.count(dest)) {
39 destinations.insert(dest);
44 bool subtract_fee =
false;
45 for (
unsigned int idx = 0; idx < subtract_fee_outputs.
size(); idx++) {
46 const UniValue& addr = subtract_fee_outputs[idx];
47 if (addr.
get_str() == address) {
52 CRecipient recipient = {script_pub_key, amount, subtract_fee};
59 if (options.
exists(
"conf_target") || options.
exists(
"estimate_mode")) {
64 options.
pushKV(
"conf_target", conf_target);
65 options.
pushKV(
"estimate_mode", estimate_mode);
67 if (options.
exists(
"fee_rate")) {
72 options.
pushKV(
"fee_rate", fee_rate);
74 if (!options[
"conf_target"].isNull() && (options[
"estimate_mode"].isNull() || (options[
"estimate_mode"].get_str() ==
"unset"))) {
98 const bool psbt_opt_in{options.
exists(
"psbt") && options[
"psbt"].
get_bool()};
99 bool add_to_wallet{options.
exists(
"add_to_wallet") ? options[
"add_to_wallet"].
get_bool() :
true};
100 if (psbt_opt_in || !complete || !add_to_wallet) {
110 result.
pushKV(
"txid", tx->GetHash().GetHex());
111 if (add_to_wallet && !psbt_opt_in) {
112 pwallet->CommitTransaction(tx, {}, {});
114 result.
pushKV(
"hex", hex);
117 result.
pushKV(
"complete", complete);
124 if (options.
exists(
"feeRate")) {
127 if (options.
exists(
"changeAddress")) {
130 if (options.
exists(
"changePosition")) {
133 if (options.
exists(
"includeWatching")) {
136 if (options.
exists(
"lockUnspents")) {
139 if (options.
exists(
"subtractFeeFromOutputs")) {
158 constexpr
int RANDOM_CHANGE_POSITION = -1;
164 wallet.CommitTransaction(tx, std::move(map_value), {} );
167 entry.
pushKV(
"txid", tx->GetHash().GetHex());
171 return tx->GetHash().GetHex();
191 if (!conf_target.
isNull()) {
192 throw JSONRPCError(
RPC_INVALID_PARAMETER,
"Cannot specify both conf_target and fee_rate. Please provide either a confirmation target in blocks for automatic fee estimation, or an explicit fee rate.");
194 if (!estimate_mode.
isNull() && estimate_mode.
get_str() !=
"unset") {
207 if (!conf_target.
isNull()) {
215 "\nSend an amount to a given address." +
221 "This is not part of the transaction, just kept in your wallet."},
223 "to which you're sending the transaction. This is not part of the \n" 224 "transaction, just kept in your wallet."},
226 "The recipient will receive less bitcoins than you enter in the amount field."},
231 {
"avoid_reuse",
RPCArg::Type::BOOL,
RPCArg::Default{
true},
"(only available if avoid_reuse wallet flag is set) Avoid spending from dirty addresses; addresses are considered\n" 232 "dirty if they have previously been used in a transaction. If true, this also activates avoidpartialspends, grouping outputs by their addresses."},
237 RPCResult{
"if verbose is not set or set to false",
251 "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode using positional arguments\n" 253 "\nSend 0.1 BTC with a fee rate of 1.1 " +
CURRENCY_ATOM +
"/vB, subtract fee from amount, BIP125-replaceable, using positional arguments\n" 255 "\nSend 0.2 BTC with a confirmation target of 6 blocks in economical fee estimate mode using named arguments\n" 257 "\nSend 0.5 BTC with a fee rate of 25 " +
CURRENCY_ATOM +
"/vB using named arguments\n" 259 +
HelpExampleCli(
"-named sendtoaddress",
"address=\"" +
EXAMPLE_ADDRESS[0] +
"\" amount=0.5 fee_rate=25 subtractfeefromamount=false replaceable=true avoid_reuse=true comment=\"2 pizzas\" comment_to=\"jeremy\" verbose=true")
268 pwallet->BlockUntilSyncedToCurrentChain();
270 LOCK(pwallet->cs_wallet);
274 if (!request.params[2].isNull() && !request.params[2].get_str().empty())
275 mapValue[
"comment"] = request.params[2].get_str();
276 if (!request.params[3].isNull() && !request.params[3].get_str().empty())
277 mapValue[
"to"] = request.params[3].get_str();
279 bool fSubtractFeeFromAmount =
false;
280 if (!request.params[4].isNull()) {
281 fSubtractFeeFromAmount = request.params[4].get_bool();
285 if (!request.params[5].isNull()) {
293 SetFeeEstimateMode(*pwallet, coin_control, request.params[6], request.params[7], request.params[9],
false);
298 const std::string address = request.params[0].get_str();
299 address_amounts.
pushKV(address, request.params[1]);
301 if (fSubtractFeeFromAmount) {
302 subtractFeeFromAmount.
push_back(address);
305 std::vector<CRecipient> recipients;
307 const bool verbose{request.params[10].isNull() ? false : request.params[10].get_bool()};
309 return SendMoney(*pwallet, coin_control, recipients, mapValue, verbose);
317 "\nSend multiple times. Amounts are double-precision floating point numbers." +
329 "The fee will be equally deducted from the amount of each selected address.\n" 330 "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" 331 "If no addresses are specified here, the sender pays the fee.",
344 RPCResult{
"if verbose is not set or set to false",
346 "the number of addresses." 352 "the number of addresses."},
358 "\nSend two amounts to two different addresses:\n" 360 "\nSend two amounts to two different addresses setting the confirmation and comment:\n" 362 "\nSend two amounts to two different addresses, subtract fee from amount:\n" 364 "\nAs a JSON-RPC call\n" 374 pwallet->BlockUntilSyncedToCurrentChain();
376 LOCK(pwallet->cs_wallet);
378 if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
384 if (!request.params[3].isNull() && !request.params[3].get_str().empty())
385 mapValue[
"comment"] = request.params[3].
get_str();
388 if (!request.params[4].isNull())
389 subtractFeeFromAmount = request.params[4].
get_array();
392 if (!request.params[5].isNull()) {
396 SetFeeEstimateMode(*pwallet, coin_control, request.params[6], request.params[7], request.params[8],
false);
398 std::vector<CRecipient> recipients;
400 const bool verbose{request.params[9].isNull() ? false : request.params[9].get_bool()};
402 return SendMoney(*pwallet, coin_control, recipients, std::move(mapValue), verbose);
410 "\nSet the transaction fee rate in " +
CURRENCY_UNIT +
"/kvB for this wallet. Overrides the global -paytxfee command line parameter.\n" 411 "Can be deactivated by passing 0 as the fee. In that case automatic fee selection will be used by default.\n",
427 LOCK(pwallet->cs_wallet);
430 CFeeRate tx_fee_rate(nAmount, 1000);
431 CFeeRate max_tx_fee_rate(pwallet->m_default_max_tx_fee, 1000);
434 }
else if (tx_fee_rate < pwallet->chain().relayMinFee()) {
436 }
else if (tx_fee_rate < pwallet->m_min_fee) {
438 }
else if (tx_fee_rate > max_tx_fee_rate) {
442 pwallet->m_pay_tx_fee = tx_fee_rate;
450 static std::vector<RPCArg>
FundTxDoc(
bool solving_data =
true)
452 std::vector<RPCArg>
args = {
458 "Allows this transaction to be replaced by a transaction with higher fees" 463 "Used for fee estimation during coin selection.",
493 wallet.BlockUntilSyncedToCurrentChain();
495 change_position = -1;
496 bool lockUnspents =
false;
498 std::set<int> setSubtractFeeFromOutputs;
536 if (options.
exists(
"add_inputs")) {
540 if (options.
exists(
"changeAddress") || options.
exists(
"change_address")) {
541 const std::string change_address_str = (options.
exists(
"change_address") ? options[
"change_address"] : options[
"changeAddress"]).get_str();
551 if (options.
exists(
"changePosition") || options.
exists(
"change_position")) {
552 change_position = (options.
exists(
"change_position") ? options[
"change_position"] : options[
"changePosition"]).getInt<int>();
555 if (options.
exists(
"change_type")) {
556 if (options.
exists(
"changeAddress") || options.
exists(
"change_address")) {
559 if (std::optional<OutputType> parsed =
ParseOutputType(options[
"change_type"].get_str())) {
566 const UniValue include_watching_option = options.
exists(
"include_watching") ? options[
"include_watching"] : options[
"includeWatching"];
569 if (options.
exists(
"lockUnspents") || options.
exists(
"lock_unspents")) {
570 lockUnspents = (options.
exists(
"lock_unspents") ? options[
"lock_unspents"] : options[
"lockUnspents"]).get_bool();
573 if (options.
exists(
"include_unsafe")) {
577 if (options.
exists(
"feeRate")) {
578 if (options.
exists(
"fee_rate")) {
581 if (options.
exists(
"conf_target")) {
582 throw JSONRPCError(
RPC_INVALID_PARAMETER,
"Cannot specify both conf_target and feeRate. Please provide either a confirmation target in blocks for automatic fee estimation, or an explicit fee rate.");
584 if (options.
exists(
"estimate_mode")) {
591 if (options.
exists(
"subtractFeeFromOutputs") || options.
exists(
"subtract_fee_from_outputs") )
592 subtractFeeFromOutputs = (options.
exists(
"subtract_fee_from_outputs") ? options[
"subtract_fee_from_outputs"] : options[
"subtractFeeFromOutputs"]).get_array();
594 if (options.
exists(
"replaceable")) {
597 SetFeeEstimateMode(
wallet, coinControl, options[
"conf_target"], options[
"estimate_mode"], options[
"fee_rate"], override_min_fee);
604 if (options.
exists(
"solving_data")) {
606 if (solving_data.
exists(
"pubkeys")) {
607 for (
const UniValue& pk_univ : solving_data[
"pubkeys"].get_array().
getValues()) {
608 const std::string& pk_str = pk_univ.
get_str();
609 if (!
IsHex(pk_str)) {
612 const std::vector<unsigned char> data(
ParseHex(pk_str));
613 const CPubKey pubkey(data.begin(), data.end());
614 if (!pubkey.IsFullyValid()) {
624 if (solving_data.
exists(
"scripts")) {
625 for (
const UniValue& script_univ : solving_data[
"scripts"].get_array().
getValues()) {
626 const std::string& script_str = script_univ.get_str();
627 if (!
IsHex(script_str)) {
630 std::vector<unsigned char> script_data(
ParseHex(script_str));
631 const CScript script(script_data.begin(), script_data.end());
636 if (solving_data.
exists(
"descriptors")) {
637 for (
const UniValue& desc_univ : solving_data[
"descriptors"].get_array().
getValues()) {
638 const std::string& desc_str = desc_univ.get_str();
641 std::vector<CScript> scripts_temp;
642 std::unique_ptr<Descriptor> desc =
Parse(desc_str, desc_out,
error,
true);
646 desc->Expand(0, desc_out, scripts_temp, desc_out);
652 if (options.
exists(
"input_weights")) {
657 if (!vout_v.
isNum()) {
660 int vout = vout_v.
getInt<
int>();
666 if (!weight_v.
isNum()) {
669 int64_t weight = weight_v.
getInt<int64_t>();
672 if (weight < min_input_weight) {
673 throw JSONRPCError(
RPC_INVALID_PARAMETER,
"Invalid parameter, weight cannot be less than 165 (41 bytes (size of outpoint + sequence + empty scriptSig) * 4 (witness scaling factor)) + 1 (empty witness)");
683 if (tx.
vout.size() == 0)
686 if (change_position != -1 && (change_position < 0 || (
unsigned int)change_position > tx.
vout.size()))
689 for (
unsigned int idx = 0; idx < subtractFeeFromOutputs.
size(); idx++) {
690 int pos = subtractFeeFromOutputs[idx].
getInt<
int>();
691 if (setSubtractFeeFromOutputs.count(pos))
695 if (pos >=
int(tx.
vout.size()))
697 setSubtractFeeFromOutputs.insert(pos);
709 if (options.
exists(
"input_weights")) {
712 if (inputs.
size() == 0) {
717 if (input.exists(
"weight")) {
721 options.
pushKV(
"input_weights", weights);
727 "\nIf the transaction has no inputs, they will be automatically selected to meet its out value.\n" 728 "It will add at most one change output to the outputs.\n" 729 "No existing outputs will be modified unless \"subtractFeeFromOutputs\" is specified.\n" 730 "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n" 731 "The inputs added will not be signed, use signrawtransactionwithkey\n" 732 "or signrawtransactionwithwallet for that.\n" 733 "All existing inputs must either have their previous output transaction be in the wallet\n" 734 "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n" 735 "Note that all inputs selected must be of standard form and P2SH scripts must be\n" 736 "in the wallet using importaddress or addmultisigaddress (to calculate fees).\n" 737 "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n" 738 "Only pay-to-pubkey, multisig, and P2SH versions thereof are currently supported for watch-only\n",
742 Cat<std::vector<RPCArg>>(
745 {
"include_unsafe",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n" 746 "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n" 747 "If that happens, you will need to fund the transaction with different inputs and republish it."},
750 {
"change_type",
RPCArg::Type::STR,
RPCArg::DefaultHint{
"set by -changetype"},
"The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."},
752 "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n" 753 "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."},
758 "The fee will be equally deducted from the amount of each specified output.\n" 759 "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" 760 "If no outputs are specified here, the sender pays the fee.",
770 "including the weight of the outpoint and sequence number. " 771 "Note that serialized signature sizes are not guaranteed to be consistent, " 772 "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures." 773 "Remember to convert serialized sizes to weight units when necessary."},
780 "If iswitness is not present, heuristic tests will be used in decoding.\n" 781 "If true, only witness deserialization will be tried.\n" 782 "If false, only non-witness deserialization will be tried.\n" 783 "This boolean should reflect whether the transaction has inputs\n" 784 "(e.g. fully valid, or on-chain transactions), if known by the caller." 796 "\nCreate a transaction with no inputs\n" 797 +
HelpExampleCli(
"createrawtransaction",
"\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
798 "\nAdd sufficient unsigned inputs to meet the output value\n" 800 "\nSign the transaction\n" 801 +
HelpExampleCli(
"signrawtransactionwithwallet",
"\"fundedtransactionhex\"") +
802 "\nSend the transaction\n" 803 +
HelpExampleCli(
"sendrawtransaction",
"\"signedtransactionhex\"")
810 RPCTypeCheck(request.params, {UniValue::VSTR, UniValueType(), UniValue::VBOOL});
814 bool try_witness = request.params[2].isNull() ? true : request.params[2].get_bool();
815 bool try_no_witness = request.params[2].isNull() ? true : !request.params[2].get_bool();
816 if (!
DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
825 FundTransaction(*pwallet, tx, fee, change_position, request.params[1], coin_control,
true);
830 result.
pushKV(
"changepos", change_position);
839 return RPCHelpMan{
"signrawtransactionwithwallet",
840 "\nSign inputs for raw transaction (serialized, hex-encoded).\n" 841 "The second optional argument (may be null) is an array of previous transaction outputs that\n" 842 "this transaction depends on but may not yet be in the block chain." +
865 " \"ALL|ANYONECANPAY\"\n" 866 " \"NONE|ANYONECANPAY\"\n" 867 " \"SINGLE|ANYONECANPAY\""},
900 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR, UniValue::VSTR},
true);
903 if (!
DecodeHexTx(mtx, request.params[0].get_str())) {
908 LOCK(pwallet->cs_wallet);
912 std::map<COutPoint, Coin> coins;
916 pwallet->chain().findCoins(coins);
924 std::map<int, bilingual_str> input_errors;
926 bool complete = pwallet->SignTransaction(mtx, coins, nHashType, input_errors);
936 const bool want_psbt = method_name ==
"psbtbumpfee";
940 "\nBumps the fee of an opt-in-RBF transaction T, replacing it with a new transaction B.\n" 941 + std::string(want_psbt ?
"Returns a PSBT instead of creating and signing a new transaction.\n" :
"") +
942 "An opt-in RBF transaction with the given txid must be in the wallet.\n" 943 "The command will pay the additional fee by reducing change outputs or adding inputs when necessary.\n" 944 "It may add a new change output if one does not already exist.\n" 945 "All inputs in the original transaction will be included in the replacement transaction.\n" 946 "The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n" 947 "By default, the new fee will be calculated automatically using the estimatesmartfee RPC.\n" 948 "The user can specify a confirmation target for estimatesmartfee.\n" 949 "Alternatively, the user can specify a fee rate in " +
CURRENCY_ATOM +
"/vB for the new transaction.\n" 950 "At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n" 951 "returned by getnetworkinfo) to enter the node's mempool.\n" 952 "* WARNING: before version 0.21, fee_rate was in " +
CURRENCY_UNIT +
"/kvB. As of 0.21, fee_rate is in " +
CURRENCY_ATOM +
"/vB. *\n",
959 "\nSpecify a fee rate in " +
CURRENCY_ATOM +
"/vB instead of relying on the built-in fee estimator.\n" 960 "Must be at least " + incremental_fee +
" higher than the current transaction fee rate.\n" 961 "WARNING: before version 0.21, fee_rate was in " +
CURRENCY_UNIT +
"/kvB. As of 0.21, fee_rate is in " +
CURRENCY_ATOM +
"/vB.\n"},
963 "marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n" 964 "be left unchanged from the original. If false, any input sequence numbers in the\n" 965 "original transaction that were less than 0xfffffffe will be increased to 0xfffffffe\n" 966 "so the new transaction will not be explicitly bip-125 replaceable (though it may\n" 967 "still be replaceable in practice, for example if it has unconfirmed ancestors which\n" 968 "are replaceable).\n"},
977 std::vector<RPCResult>{{
RPCResult::Type::STR,
"psbt",
"The base64-encoded unsigned PSBT of the new transaction."}} :
989 "\nBump the fee, get the new transaction\'s " + std::string(want_psbt ?
"psbt" :
"txid") +
"\n" +
998 throw JSONRPCError(
RPC_WALLET_ERROR,
"bumpfee is not available with wallets that have private keys disabled. Use psbtbumpfee instead.");
1001 RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VOBJ});
1009 if (!request.params[1].isNull()) {
1010 UniValue options = request.params[1];
1021 if (options.
exists(
"confTarget") && options.
exists(
"conf_target")) {
1025 auto conf_target = options.
exists(
"confTarget") ? options[
"confTarget"] : options[
"conf_target"];
1027 if (options.
exists(
"replaceable")) {
1030 SetFeeEstimateMode(*pwallet, coin_control, conf_target, options[
"estimate_mode"], options[
"fee_rate"],
false);
1035 pwallet->BlockUntilSyncedToCurrentChain();
1037 LOCK(pwallet->cs_wallet);
1042 std::vector<bilingual_str> errors;
1086 bool complete =
false;
1101 result.
pushKV(
"errors", result_errors);
1114 "\nEXPERIMENTAL warning: this call may be changed in future releases.\n" 1115 "\nSend a transaction.\n",
1118 "That is, each address can only appear once and there can only be one 'data' object.\n" 1119 "For convenience, a dictionary, which holds the key-value pairs directly, is also accepted.",
1138 Cat<std::vector<RPCArg>>(
1140 {
"add_inputs",
RPCArg::Type::BOOL,
RPCArg::DefaultHint{
"false when \"inputs\" are specified, true otherwise"},
"Automatically include coins from the wallet to cover the target amount.\n"},
1141 {
"include_unsafe",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n" 1142 "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n" 1143 "If that happens, you will need to fund the transaction with different inputs and republish it."},
1144 {
"add_to_wallet",
RPCArg::Type::BOOL,
RPCArg::Default{
true},
"When false, returns a serialized transaction which will not be added to the wallet or broadcast"},
1147 {
"change_type",
RPCArg::Type::STR,
RPCArg::DefaultHint{
"set by -changetype"},
"The output type to use. Only valid if change_address is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\" and \"bech32m\"."},
1150 "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n" 1151 "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."},
1158 "including the weight of the outpoint and sequence number. " 1159 "Note that signature sizes are not guaranteed to be consistent, " 1160 "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures." 1161 "Remember to convert serialized sizes to weight units when necessary."},
1168 "The fee will be equally deducted from the amount of each specified output.\n" 1169 "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" 1170 "If no outputs are specified here, the sender pays the fee.",
1183 {
RPCResult::Type::STR_HEX,
"txid",
true,
"The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."},
1184 {
RPCResult::Type::STR_HEX,
"hex",
true,
"If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
1185 {
RPCResult::Type::STR,
"psbt",
true,
"If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"}
1189 "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode\n" 1191 "Send 0.2 BTC with a fee rate of 1.1 " +
CURRENCY_ATOM +
"/vB using positional arguments\n" 1193 "Send 0.2 BTC with a fee rate of 1 " +
CURRENCY_ATOM +
"/vB using the options argument\n" 1195 "Send 0.3 BTC with a fee rate of 25 " +
CURRENCY_ATOM +
"/vB using named arguments\n" 1197 "Create a transaction that should confirm the next block, with a specific input, and return result without adding to wallet or broadcasting to the network\n" 1198 +
HelpExampleCli(
"send",
"'{\"" +
EXAMPLE_ADDRESS[0] +
"\": 0.1}' 1 economical '{\"add_to_wallet\": false, \"inputs\": [{\"txid\":\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\", \"vout\":1}]}'")
1220 int change_position;
1221 bool rbf{options.exists(
"replaceable") ? options[
"replaceable"].get_bool() : pwallet->m_signal_rbf};
1228 FundTransaction(*pwallet, rawTx, fee, change_position, options, coin_control,
false);
1238 "EXPERIMENTAL warning: this call may be changed in future releases.\n" 1239 "\nSpend the value of all (or specific) confirmed UTXOs in the wallet to one or more recipients.\n" 1240 "Unconfirmed inbound UTXOs and locked UTXOs will not be spent. Sendall will respect the avoid_reuse wallet flag.\n" 1241 "If your wallet contains many small inputs, either because it received tiny payments or as a result of accumulating change, consider using `send_max` to exclude inputs that are worth less than the fees needed to spend them.\n",
1244 "Optionally some recipients can be specified with an amount to perform payments, but at least one address must appear without a specified amount.\n",
1260 Cat<std::vector<RPCArg>>(
1265 "Only solvable inputs can be used. Watch-only destinations are solvable if the public key and/or output script was imported,\n" 1266 "e.g. with 'importpubkey' or 'importmulti' with the 'pubkeys' or 'desc' field."},
1281 {
"send_max",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"When true, only use UTXOs that can pay for their own fees to maximize the output amount. When 'false' (default), no UTXO is left behind. send_max is incompatible with providing specific inputs."},
1292 {
RPCResult::Type::STR_HEX,
"txid",
true,
"The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."},
1293 {
RPCResult::Type::STR_HEX,
"hex",
true,
"If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
1294 {
RPCResult::Type::STR,
"psbt",
true,
"If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"}
1298 "\nSpend all UTXOs from the wallet with a fee rate of 1Â " +
CURRENCY_ATOM +
"/vB using named arguments\n" 1300 "Spend all UTXOs with a fee rate of 1.1 " +
CURRENCY_ATOM +
"/vB using positional arguments\n" 1302 "Spend all UTXOs split into equal amounts to two addresses with a fee rate of 1.5 " +
CURRENCY_ATOM +
"/vB using the options argument\n" 1304 "Leave dust UTXOs in wallet, spend only UTXOs with positive effective value with a fee rate of 10 " +
CURRENCY_ATOM +
"/vB using the options argument\n" 1306 "Spend all UTXOs with a fee rate of 1.3 " +
CURRENCY_ATOM +
"/vB using named arguments and sending a 0.25 " +
CURRENCY_UNIT +
" to another recipient\n" 1324 pwallet->BlockUntilSyncedToCurrentChain();
1331 std::set<std::string> addresses_without_amount;
1333 const UniValue& recipients{request.params[0]};
1334 for (
unsigned int i = 0; i < recipients.size(); ++i) {
1335 const UniValue& recipient{recipients[i]};
1336 if (recipient.isStr()) {
1338 rkvp.
pushKV(recipient.get_str(), 0);
1339 recipient_key_value_pairs.
push_back(rkvp);
1340 addresses_without_amount.insert(recipient.get_str());
1342 recipient_key_value_pairs.
push_back(recipient);
1346 if (addresses_without_amount.size() == 0) {
1352 SetFeeEstimateMode(*pwallet, coin_control, options[
"conf_target"], options[
"estimate_mode"], options[
"fee_rate"],
false);
1356 const bool rbf{options.exists(
"replaceable") ? options[
"replaceable"].get_bool() : pwallet->m_signal_rbf};
1371 LOCK(pwallet->cs_wallet);
1374 bool send_max{options.exists(
"send_max") ? options[
"send_max"].get_bool() :
false};
1375 if (options.exists(
"inputs") && options.exists(
"send_max")) {
1377 }
else if (options.exists(
"inputs")) {
1378 for (
const CTxIn& input : rawTx.vin) {
1379 if (pwallet->IsSpent(input.
prevout)) {
1386 total_input_value += tx->tx->vout[input.
prevout.
n].nValue;
1391 if (send_max && fee_rate.GetFee(output.input_bytes) > output.txout.nValue) {
1395 rawTx.vin.push_back(input);
1396 total_input_value += output.txout.nValue;
1402 const CAmount fee_from_size{fee_rate.GetFee(tx_size.vsize)};
1403 const CAmount effective_value{total_input_value - fee_from_size};
1405 if (fee_from_size > pwallet->m_default_max_tx_fee) {
1409 if (effective_value <= 0) {
1422 CAmount output_amounts_claimed{0};
1423 for (
const CTxOut& out : rawTx.vout) {
1424 output_amounts_claimed += out.
nValue;
1427 if (output_amounts_claimed > total_input_value) {
1431 const CAmount remainder{effective_value - output_amounts_claimed};
1432 if (remainder < 0) {
1436 const CAmount per_output_without_amount{remainder / (long)addresses_without_amount.size()};
1438 bool gave_remaining_to_first{
false};
1439 for (
CTxOut& out : rawTx.vout) {
1443 if (addresses_without_amount.count(addr) > 0) {
1444 out.
nValue = per_output_without_amount;
1445 if (!gave_remaining_to_first) {
1446 out.
nValue += remainder % addresses_without_amount.size();
1447 gave_remaining_to_first =
true;
1449 if (
IsDust(out, pwallet->chain().relayDustFee())) {
1454 if (
IsDust(out, pwallet->chain().relayDustFee())) {
1461 const bool lock_unspents{options.exists(
"lock_unspents") ? options[
"lock_unspents"].get_bool() :
false};
1462 if (lock_unspents) {
1463 for (
const CTxIn& txin : rawTx.vin) {
1464 pwallet->LockCoin(txin.
prevout);
1476 "\nUpdate a PSBT with input information from our wallet and then sign inputs\n" 1477 "that we can sign for." +
1482 {
"sighashtype",
RPCArg::Type::STR,
RPCArg::Default{
"DEFAULT for Taproot, ALL otherwise"},
"The signature hash type to sign with if not specified by the PSBT. Must be one of\n" 1487 " \"ALL|ANYONECANPAY\"\n" 1488 " \"NONE|ANYONECANPAY\"\n" 1489 " \"SINGLE|ANYONECANPAY\""},
1511 wallet.BlockUntilSyncedToCurrentChain();
1526 bool sign = request.params[1].isNull() ? true : request.params[1].get_bool();
1527 bool bip32derivs = request.params[3].isNull() ? true : request.params[3].get_bool();
1528 bool finalize = request.params[4].isNull() ? true : request.params[4].get_bool();
1529 bool complete =
true;
1533 const TransactionError err{
wallet.FillPSBT(psbtx, complete, nHashType, sign, bip32derivs,
nullptr, finalize)};
1542 result.
pushKV(
"complete", complete);
1552 "\nCreates and funds a transaction in the Partially Signed Transaction format.\n" 1553 "Implements the Creator and Updater roles.\n" 1554 "All existing inputs must either have their previous output transaction be in the wallet\n" 1555 "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n",
1565 "including the weight of the outpoint and sequence number. " 1566 "Note that signature sizes are not guaranteed to be consistent, " 1567 "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures." 1568 "Remember to convert serialized sizes to weight units when necessary."},
1574 "That is, each address can only appear once and there can only be one 'data' object.\n" 1575 "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n" 1576 "accepted as second parameter.",
1592 Cat<std::vector<RPCArg>>(
1594 {
"add_inputs",
RPCArg::Type::BOOL,
RPCArg::DefaultHint{
"false when \"inputs\" are specified, true otherwise"},
"Automatically include coins from the wallet to cover the target amount.\n"},
1595 {
"include_unsafe",
RPCArg::Type::BOOL,
RPCArg::Default{
false},
"Include inputs that are not safe to spend (unconfirmed transactions from outside keys and unconfirmed replacement transactions).\n" 1596 "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n" 1597 "If that happens, you will need to fund the transaction with different inputs and republish it."},
1600 {
"change_type",
RPCArg::Type::STR,
RPCArg::DefaultHint{
"set by -changetype"},
"The output type to use. Only valid if changeAddress is not specified. Options are \"legacy\", \"p2sh-segwit\", \"bech32\", and \"bech32m\"."},
1606 "The fee will be equally deducted from the amount of each specified output.\n" 1607 "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n" 1608 "If no outputs are specified here, the sender pays the fee.",
1627 "\nCreate a transaction with no inputs\n" 1628 +
HelpExampleCli(
"walletcreatefundedpsbt",
"\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
1638 wallet.BlockUntilSyncedToCurrentChain();
1652 int change_position;
1653 bool rbf{
wallet.m_signal_rbf};
1654 const UniValue &replaceable_arg = options[
"replaceable"];
1655 if (!replaceable_arg.
isNull()) {
1657 rbf = replaceable_arg.
isTrue();
1671 bool bip32derivs = request.params[4].isNull() ? true : request.params[4].get_bool();
1672 bool complete =
true;
1685 result.
pushKV(
"changepos", change_position);
std::shared_ptr< const CTransaction > CTransactionRef
static RPCHelpMan bumpfee_helper(std::string method_name)
void FundTransaction(CWallet &wallet, CMutableTransaction &tx, CAmount &fee_out, int &change_position, const UniValue &options, CCoinControl &coinControl, bool override_min_fee)
void push_back(UniValue val)
bool m_avoid_partial_spends
Avoid partial use of funds sent to a given address.
std::optional< unsigned int > m_confirm_target
Override the default confirmation target if set.
static constexpr unsigned int DEFAULT_INCREMENTAL_RELAY_FEE
Default for -incrementalrelayfee, which sets the minimum feerate increase for mempool limiting or rep...
const std::vector< UniValue > & getValues() const
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a standard scriptPubKey for the destination address.
void RPCTypeCheckObj(const UniValue &o, const std::map< std::string, UniValueType > &typesExpected, bool fAllowNull, bool fStrict)
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.
CoinsResult AvailableCoins(const CWallet &wallet, const CCoinControl *coinControl, std::optional< CFeeRate > feerate, const CAmount &nMinimumAmount, const CAmount &nMaximumAmount, const CAmount &nMinimumSumAmount, const uint64_t nMaximumCount, bool only_spendable)
Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
CTxDestination destChange
Custom change destination, if not set an address is generated.
std::map< std::string, std::string > mapValue_t
RPCHelpMan sendtoaddress()
static const uint32_t SEQUENCE_FINAL
Setting nSequence to this value for every input in a transaction disables nLockTime/IsFinalTx().
#define CHECK_NONFATAL(condition)
Identity function.
bool IsHex(std::string_view str)
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination is a CNoDestination.
bool ParseIncludeWatchonly(const UniValue &include_watchonly, const CWallet &wallet)
Used by RPC commands that have an include_watchonly parameter.
static std::vector< RPCArg > FundTxDoc(bool solving_data=true)
std::string EncodeBase64(Span< const unsigned char > input)
bool fAllowWatchOnly
Includes watch only addresses which are solvable.
const std::string & get_str() const
const std::string EXAMPLE_ADDRESS[2]
Example bech32 addresses for the RPCExamples help documentation.
Use sat/vB fee rate unit.
const UniValue & get_array() const
unsigned int ParseConfirmTarget(const UniValue &value, unsigned int max_target)
Parse a confirm target option and raise an RPC error if it is invalid.
bilingual_str TransactionErrorString(const TransactionError err)
FlatSigningProvider m_external_provider
SigningProvider that has pubkeys and scripts to do spend size estimation for external inputs...
A version of CTransaction with the PSBT format.
Double ended buffer combining vector and stream-like interfaces.
static void SetOptionsInputWeights(const UniValue &inputs, UniValue &options)
const std::vector< std::string > & getKeys() const
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
bool FinalizeAndExtractPSBT(PartiallySignedTransaction &psbtx, CMutableTransaction &result)
Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized...
void SignTransactionResultToJSON(CMutableTransaction &mtx, bool complete, const std::map< COutPoint, Coin > &coins, const std::map< int, bilingual_str > &input_errors, UniValue &result)
Invalid, missing or duplicate parameter.
Result CommitTransaction(CWallet &wallet, const uint256 &txid, CMutableTransaction &&mtx, std::vector< bilingual_str > &errors, uint256 &bumped_txid)
Commit the bumpfee transaction.
const UniValue & find_value(const UniValue &obj, const std::string &name)
std::optional< OutputType > m_change_type
Override the default change type if set, ignored if destChange is set.
RPCHelpMan walletcreatefundedpsbt()
int64_t CAmount
Amount in satoshis (Can be negative)
A transaction with a bunch of additional info that only the owner cares about.
void RPCTypeCheckArgument(const UniValue &value, const UniValueType &typeExpected)
Type-check one argument; throws JSONRPCError if wrong type given.
std::unique_ptr< Descriptor > Parse(const std::string &descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
Special type that is a STR with only hex chars.
static void SetFeeEstimateMode(const CWallet &wallet, CCoinControl &cc, const UniValue &conf_target, const UniValue &estimate_mode, const UniValue &fee_rate, bool override_min_fee)
Update coin control with fee estimation based on the given parameters.
std::string HelpExampleRpc(const std::string &methodname, const std::string &args)
RPCHelpMan fundrawtransaction()
void push_back(const T &value)
std::vector< Byte > ParseHex(std::string_view str)
Parse the hex string into bytes (uint8_t or std::byte).
uint256 ParseHashO(const UniValue &o, std::string strKey)
static constexpr uint32_t MAX_BIP125_RBF_SEQUENCE
UniValue JSONRPCError(int code, const std::string &message)
RPCHelpMan signrawtransactionwithwallet()
Special string with only hex chars.
const std::string CURRENCY_ATOM
static CAmount AmountFromValue(const UniValue &value)
RPCHelpMan walletprocesspsbt()
static void ParseRecipients(const UniValue &address_amounts, const UniValue &subtract_fee_outputs, std::vector< CRecipient > &recipients)
std::map< CScriptID, CScript > scripts
int ParseSighashString(const UniValue &sighash)
An input of a transaction.
bool DecodeBase64PSBT(PartiallySignedTransaction &psbt, const std::string &base64_tx, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
static int64_t GetTransactionInputWeight(const CTxIn &txin)
bool exists(const std::string &key) const
std::optional< OutputType > ParseOutputType(const std::string &type)
An encapsulated public key.
std::string ToString(const FeeEstimateMode &fee_estimate_mode=FeeEstimateMode::BTC_KVB) const
std::map< CKeyID, CPubKey > pubkeys
static constexpr unsigned int MAX_STANDARD_TX_WEIGHT
The maximum weight for transactions we're willing to relay/mine.
Special type where the user must set the keys e.g. to define multiple addresses; as opposed to e...
bool fOverrideFeeRate
Override automatic min/max checks on fee, m_feerate must be set if true.
const std::string CURRENCY_UNIT
void SetInputWeight(const COutPoint &outpoint, int64_t weight)
A CWallet maintains a set of transactions and balances, and provides the ability to create new transa...
std::variant< CNoDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, WitnessUnknown > CTxDestination
A txout script template with a specific destination.
General application defined errors.
CMutableTransaction ConstructTransaction(const UniValue &inputs_in, const UniValue &outputs_in, const UniValue &locktime, std::optional< bool > rbf)
Create a transaction from univalue parameters.
An output of a transaction.
std::string ToString() const
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
const std::string InvalidEstimateModeErrorMessage()
An outpoint - a combination of a transaction hash and an index n into its vout.
std::string HelpExampleCli(const std::string &methodname, const std::string &args)
std::vector< CTxOut > vout
const std::string HELP_REQUIRING_PASSPHRASE
TxSize CalculateMaximumSignedTxSize(const CTransaction &tx, const CWallet *wallet, const std::vector< CTxOut > &txouts, const CCoinControl *coin_control)
Calculate the size of the transaction using CoinControl to determine whether to expect signature grin...
Optional arg that is a named argument and has a default value of null.
bool m_avoid_address_reuse
Forbids inclusion of dirty (previously used) addresses.
std::string FeeModes(const std::string &delimiter)
CFeeRate GetMinimumFeeRate(const CWallet &wallet, const CCoinControl &coin_control, FeeCalculation *feeCalc)
Estimate the minimum fee rate considering user set parameters and the required fee.
FlatSigningProvider & Merge(FlatSigningProvider &&b) LIFETIMEBOUND
static CTransactionRef MakeTransactionRef(Tx &&txIn)
static void PreventOutdatedOptions(const UniValue &options)
bool SignTransaction(CWallet &wallet, CMutableTransaction &mtx)
Sign the new transaction,.
uint256 ParseHashV(const UniValue &v, std::string strName)
Utilities: convert hex-encoded Values (throws error if not hex).
Optional argument with default value omitted because they are implicitly clear.
Special string to represent a floating point amount.
void pushKV(std::string key, UniValue val)
Serialized script, used inside transaction inputs and outputs.
bool m_include_unsafe_inputs
If false, only safe inputs will be used.
static const int PROTOCOL_VERSION
network protocol versioning
Not enough funds in wallet or account.
FeeEstimateMode m_fee_mode
Fee estimation mode to control arguments to estimateSmartFee.
const UniValue & get_obj() const
Special type representing a floating point amount (can be either NUM or STR)
bool DecodeHexTx(CMutableTransaction &tx, const std::string &hex_tx, bool try_no_witness=false, bool try_witness=true)
std::string GetHex() const
bool m_allow_other_inputs
If true, the selection process can add extra unselected inputs from the wallet while requires all sel...
UniValue ValueFromAmount(const CAmount amount)
std::string EncodeHexTx(const CTransaction &tx, const int serializeFlags=0)
Fee rate in satoshis per kilovirtualbyte: CAmount / kvB.
const UniValue NullUniValue
bool GetAvoidReuseFlag(const CWallet &wallet, const UniValue ¶m)
void EnsureWalletIsUnlocked(const CWallet &wallet)
util::Result< CreatedTransactionResult > CreateTransaction(CWallet &wallet, const std::vector< CRecipient > &vecSend, int change_pos, const CCoinControl &coin_control, bool sign)
Create a new transaction paying the recipients with a set of coins selected by SelectCoins(); Also cr...
bilingual_str ErrorString(const Result< T > &result)
A reference to a CScript: the Hash160 of its serialization (see script.h)
std::string EncodeDestination(const CTxDestination &dest)
bool IsDust(const CTxOut &txout, const CFeeRate &dustRelayFeeIn)
Standard JSON-RPC 2.0 errors.
A mutable version of CTransaction.
The basic transaction that is broadcasted on the network and contained in blocks. ...
static void InterpretFeeEstimationInstructions(const UniValue &conf_target, const UniValue &estimate_mode, const UniValue &fee_rate, UniValue &options)
UniValue JSONRPCTransactionError(TransactionError terr, const std::string &err_string)
bool FeeModeFromString(const std::string &mode_string, FeeEstimateMode &fee_estimate_mode)
Result CreateRateBumpTransaction(CWallet &wallet, const uint256 &txid, const CCoinControl &coin_control, std::vector< bilingual_str > &errors, CAmount &old_fee, CAmount &new_fee, CMutableTransaction &mtx, bool require_mine)
Create bumpfee transaction based on feerate estimates.
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
static UniValue FinishTransaction(const std::shared_ptr< CWallet > pwallet, const UniValue &options, const CMutableTransaction &rawTx)
std::optional< bool > m_signal_bip125_rbf
Override the wallet's m_signal_rbf if set.
A UTXO under consideration for use in funding a new transaction.
std::optional< CFeeRate > m_feerate
Override the wallet's m_pay_tx_fee if set.
bool error(const char *fmt, const Args &... args)
std::string StringForFeeReason(FeeReason reason)
Wrapper for UniValue::VType, which includes typeAny: Used to denote don't care type.
std::shared_ptr< CWallet > GetWalletForJSONRPCRequest(const JSONRPCRequest &request)
Figures out what wallet, if any, to use for a JSONRPCRequest.
UniValue SendMoney(CWallet &wallet, const CCoinControl &coin_control, std::vector< CRecipient > &recipients, mapValue_t map_value, bool verbose)
Error parsing or validating structure in raw format.
V Cat(V v1, V &&v2)
Concatenate two vectors, moving elements.
void RPCTypeCheck(const UniValue ¶ms, const std::list< UniValueType > &typesExpected, bool fAllowNull)
Type-check arguments; throws JSONRPCError if wrong type given.