Branch data Line data Source code
1 : : // Copyright (c) 2011-present 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 <common/messages.h>
6 : : #include <consensus/validation.h>
7 : : #include <core_io.h>
8 : : #include <key_io.h>
9 : : #include <node/types.h>
10 : : #include <policy/policy.h>
11 : : #include <policy/truc_policy.h>
12 : : #include <rpc/rawtransaction_util.h>
13 : : #include <rpc/util.h>
14 : : #include <script/script.h>
15 : : #include <util/hasher.h>
16 : : #include <util/rbf.h>
17 : : #include <util/translation.h>
18 : : #include <util/vector.h>
19 : : #include <wallet/coincontrol.h>
20 : : #include <wallet/feebumper.h>
21 : : #include <wallet/fees.h>
22 : : #include <wallet/rpc/util.h>
23 : : #include <wallet/spend.h>
24 : : #include <wallet/wallet.h>
25 : :
26 : : #include <univalue.h>
27 : :
28 : : #include <unordered_set>
29 : :
30 : : using common::FeeModeFromString;
31 : : using common::FeeModesDetail;
32 : : using common::FeeReasons;
33 : : using common::InvalidEstimateModeErrorMessage;
34 : : using common::StringForFeeReason;
35 : : using common::TransactionErrorString;
36 : : using node::TransactionError;
37 : :
38 : : namespace wallet {
39 : 2040 : std::vector<CRecipient> CreateRecipients(const std::vector<std::pair<CTxDestination, CAmount>>& outputs, const std::set<int>& subtract_fee_outputs)
40 : : {
41 : 2040 : std::vector<CRecipient> recipients;
42 [ - + + + ]: 23160 : for (size_t i = 0; i < outputs.size(); ++i) {
43 [ + - + - ]: 21120 : const auto& [destination, amount] = outputs.at(i);
44 [ + - ]: 42240 : CRecipient recipient{destination, amount, subtract_fee_outputs.contains(i)};
45 [ + - ]: 21120 : recipients.push_back(recipient);
46 : 21120 : }
47 : 2040 : return recipients;
48 : 0 : }
49 : :
50 : 455 : static void InterpretFeeEstimationInstructions(const UniValue& conf_target, const UniValue& estimate_mode, const UniValue& fee_rate, UniValue& options)
51 : : {
52 [ + - + - : 1342 : if (options.exists("conf_target") || options.exists("estimate_mode")) {
+ + + - +
- + + + +
- - ]
53 [ + + - + ]: 24 : if (!conf_target.isNull() || !estimate_mode.isNull()) {
54 [ + - + - ]: 6 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass conf_target and estimate_mode either as arguments or in the options object, but not both");
55 : : }
56 : : } else {
57 [ + - + - ]: 862 : options.pushKV("conf_target", conf_target);
58 [ + - + - ]: 862 : options.pushKV("estimate_mode", estimate_mode);
59 : : }
60 [ + + ]: 904 : if (options.exists("fee_rate")) {
61 [ + + ]: 28 : if (!fee_rate.isNull()) {
62 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass the fee_rate either as an argument, or in the options object, but not both");
63 : : }
64 : : } else {
65 [ + - + - ]: 848 : options.pushKV("fee_rate", fee_rate);
66 : : }
67 [ + - + - : 960 : if (!options["conf_target"].isNull() && (options["estimate_mode"].isNull() || (options["estimate_mode"].get_str() == "unset"))) {
+ + + - +
- + - + -
+ - + - -
+ + + - +
- - - - ]
68 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Specify estimate_mode");
69 : : }
70 : 451 : }
71 : :
72 : 773 : std::set<int> InterpretSubtractFeeFromOutputInstructions(const UniValue* sffo_instructions, const std::vector<std::string>& destinations)
73 : : {
74 [ + + ]: 773 : std::set<int> sffo_set;
75 [ + + + + ]: 773 : if (!sffo_instructions || sffo_instructions->isNull()) return sffo_set;
76 : :
77 [ + - + + ]: 200 : for (const auto& sffo : sffo_instructions->getValues()) {
78 : 105 : int pos{-1};
79 [ + + ]: 105 : if (sffo.isStr()) {
80 [ + - ]: 9 : auto it = find(destinations.begin(), destinations.end(), sffo.get_str());
81 [ + + + - : 10 : if (it == destinations.end()) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', destination %s not found in tx outputs", sffo.get_str()));
+ - + - ]
82 : 8 : pos = it - destinations.begin();
83 [ + + ]: 96 : } else if (sffo.isNum()) {
84 [ + - ]: 95 : pos = sffo.getInt<int>();
85 : : } else {
86 [ + - + - : 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', invalid value type: %s", uvTypeName(sffo.type())));
+ - ]
87 : : }
88 : :
89 [ + + ]: 103 : if (sffo_set.contains(pos))
90 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', duplicated position: %d", pos));
91 [ + + ]: 101 : if (pos < 0)
92 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', negative position: %d", pos));
93 [ - + + + ]: 100 : if (pos >= int(destinations.size()))
94 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', position too large: %d", pos));
95 [ + - ]: 99 : sffo_set.insert(pos);
96 : : }
97 : : return sffo_set;
98 : 6 : }
99 : :
100 : 307 : static UniValue FinishTransaction(const std::shared_ptr<CWallet> pwallet, const UniValue& options, CMutableTransaction& rawTx)
101 : : {
102 : 614 : bool can_anti_fee_snipe = !options.exists("locktime");
103 : :
104 [ + + ]: 1769 : for (const CTxIn& tx_in : rawTx.vin) {
105 : : // Checks sequence values consistent with DiscourageFeeSniping
106 [ + + + + ]: 1470 : can_anti_fee_snipe = can_anti_fee_snipe && (tx_in.nSequence == CTxIn::MAX_SEQUENCE_NONFINAL || tx_in.nSequence == MAX_BIP125_RBF_SEQUENCE);
107 : : }
108 : :
109 [ + + ]: 307 : if (can_anti_fee_snipe) {
110 : 301 : LOCK(pwallet->cs_wallet);
111 : 301 : FastRandomContext rng_fast;
112 [ + - ]: 301 : DiscourageFeeSniping(rawTx, rng_fast, pwallet->chain(), pwallet->GetLastBlockHash(), pwallet->GetLastBlockHeight());
113 [ + - ]: 602 : }
114 : :
115 : : // Make a blank psbt
116 : 307 : PartiallySignedTransaction psbtx(rawTx, /*version=*/2);
117 : :
118 : : // First fill transaction with our data without signing,
119 : : // so external signers are not asked to sign more than once.
120 : 307 : bool complete;
121 [ + - ]: 307 : pwallet->FillPSBT(psbtx, {.sign = false, .bip32_derivs = true}, complete);
122 [ + - ]: 307 : const auto err{pwallet->FillPSBT(psbtx, {.sign = true, .bip32_derivs = false}, complete)};
123 [ + + ]: 307 : if (err) {
124 [ + - ]: 1 : throw JSONRPCPSBTError(*err);
125 : : }
126 : :
127 [ + - ]: 306 : CMutableTransaction mtx;
128 [ + - ]: 306 : complete = FinalizeAndExtractPSBT(psbtx, mtx);
129 : :
130 : 306 : UniValue result(UniValue::VOBJ);
131 : :
132 [ + - + - : 327 : const bool psbt_opt_in{options.exists("psbt") && options["psbt"].get_bool()};
+ + + - +
- + - + -
- - ]
133 [ + - + + : 645 : bool add_to_wallet{options.exists("add_to_wallet") ? options["add_to_wallet"].get_bool() : true};
+ - + - +
- ]
134 [ + + + + : 306 : if (psbt_opt_in || !complete || !add_to_wallet) {
+ + ]
135 : : // Serialize the PSBT
136 : 60 : DataStream ssTx{};
137 [ + - ]: 60 : ssTx << psbtx;
138 [ + - + - : 180 : result.pushKV("psbt", EncodeBase64(ssTx.str()));
+ - + - +
- ]
139 : 60 : }
140 : :
141 [ + + ]: 306 : if (complete) {
142 [ + - + - ]: 278 : std::string hex{EncodeHexTx(CTransaction(mtx))};
143 [ + - ]: 278 : CTransactionRef tx(MakeTransactionRef(std::move(mtx)));
144 [ + - + - : 556 : result.pushKV("txid", tx->GetHash().GetHex());
+ - + - ]
145 [ + + ]: 278 : if (add_to_wallet && !psbt_opt_in) {
146 [ + - + - ]: 984 : pwallet->CommitTransaction(tx);
147 : : } else {
148 [ + - + - : 64 : result.pushKV("hex", hex);
+ - ]
149 : : }
150 : 278 : }
151 [ + - + - : 612 : result.pushKV("complete", complete);
+ - ]
152 : :
153 : 612 : return result;
154 : 307 : }
155 : :
156 : 233 : static void PreventOutdatedOptions(const UniValue& options)
157 : : {
158 [ + + ]: 466 : if (options.exists("feeRate")) {
159 [ + - + - ]: 3 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Use fee_rate (" + CURRENCY_ATOM + "/vB) instead of feeRate");
160 : : }
161 [ - + ]: 464 : if (options.exists("changeAddress")) {
162 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_address instead of changeAddress");
163 : : }
164 [ - + ]: 464 : if (options.exists("changePosition")) {
165 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_position instead of changePosition");
166 : : }
167 [ - + ]: 464 : if (options.exists("lockUnspents")) {
168 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Use lock_unspents instead of lockUnspents");
169 : : }
170 [ - + ]: 464 : if (options.exists("subtractFeeFromOutputs")) {
171 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Use subtract_fee_from_outputs instead of subtractFeeFromOutputs");
172 : : }
173 : 232 : }
174 : :
175 : : const UniValue* GetOptionWithAlias(
176 : : const UniValue& options,
177 : : const std::string& canonical_name,
178 : : const std::string& deprecated_name);
179 : :
180 : 1329 : UniValue SendMoney(CWallet& wallet, const CCoinControl &coin_control, std::vector<CRecipient> &recipients, std::optional<std::string> comment, std::optional<std::string> comment_to, bool verbose)
181 : : {
182 : 1329 : EnsureWalletIsUnlocked(wallet);
183 : :
184 : : // This function is only used by sendtoaddress and sendmany.
185 : : // This should always try to sign, if we don't have (all) private keys, don't
186 : : // try to do anything here.
187 [ + + ]: 1329 : if (wallet.IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
188 [ + - + - ]: 4 : throw JSONRPCError(RPC_WALLET_ERROR, "Error: sendtoaddress and sendmany are not supported for wallets with external signers; use send instead");
189 : : }
190 [ + + ]: 1327 : if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
191 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
192 : : }
193 : :
194 : : // Shuffle recipient list
195 : 1326 : std::shuffle(recipients.begin(), recipients.end(), FastRandomContext());
196 : :
197 : : // Send
198 : 1326 : auto res = CreateTransaction(wallet, recipients, /*change_pos=*/std::nullopt, coin_control, true);
199 [ + + ]: 1326 : if (!res) {
200 [ + - + - ]: 38 : throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, util::ErrorString(res).original);
201 : : }
202 : 1307 : const CTransactionRef& tx = res->tx;
203 [ + - + - : 6535 : wallet.CommitTransaction(tx, /*replaces_txid=*/std::nullopt, comment, comment_to);
+ - + - ]
204 [ + + ]: 1307 : if (verbose) {
205 : 8 : UniValue entry(UniValue::VOBJ);
206 [ + - + - : 16 : entry.pushKV("txid", tx->GetHash().GetHex());
+ - + - ]
207 [ + - + - : 16 : entry.pushKV("fee_reason", StringForFeeReason(res->fee_reason));
+ - + - ]
208 : 8 : return entry;
209 : 0 : }
210 [ + - + - ]: 1299 : return tx->GetHash().GetHex();
211 : 1307 : }
212 : :
213 : :
214 : : /**
215 : : * Update coin control with fee estimation based on the given parameters
216 : : *
217 : : * @param[in] wallet Wallet reference
218 : : * @param[in,out] cc Coin control to be updated
219 : : * @param[in] conf_target UniValue integer; confirmation target in blocks, values between 1 and 1008 are valid per policy/fees/block_policy_estimator.h;
220 : : * @param[in] estimate_mode UniValue string; fee estimation mode, valid values are "unset", "economical" or "conservative";
221 : : * @param[in] fee_rate UniValue real; fee rate in sat/vB;
222 : : * if present, both conf_target and estimate_mode must either be null, or "unset"
223 : : * @param[in] override_min_fee bool; whether to set fOverrideFeeRate to true to disable minimum fee rate checks and instead
224 : : * verify only that fee_rate is greater than 0
225 : : * @throws a JSONRPCError if conf_target, estimate_mode, or fee_rate contain invalid values or are in conflict
226 : : */
227 : 2280 : static void SetFeeEstimateMode(const CWallet& wallet, CCoinControl& cc, const UniValue& conf_target, const UniValue& estimate_mode, const UniValue& fee_rate, bool override_min_fee)
228 : : {
229 [ + + ]: 2280 : if (!fee_rate.isNull()) {
230 [ + + ]: 614 : if (!conf_target.isNull()) {
231 [ + - + - ]: 6 : 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.");
232 : : }
233 [ + + + + ]: 611 : if (!estimate_mode.isNull() && estimate_mode.get_str() != "unset") {
234 [ + - + - ]: 6 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and fee_rate");
235 : : }
236 : : // Fee rates in sat/vB cannot represent more than 3 significant digits.
237 [ - + ]: 608 : cc.m_feerate = CFeeRate{AmountFromValue(fee_rate, /*decimals=*/3)};
238 [ + + ]: 532 : if (override_min_fee) cc.fOverrideFeeRate = true;
239 : : // Default RBF to true for explicit fee_rate, if unset.
240 [ + + ]: 532 : if (!cc.m_signal_bip125_rbf) cc.m_signal_bip125_rbf = true;
241 : 532 : return;
242 : : }
243 [ + + - + : 1666 : if (!estimate_mode.isNull() && !FeeModeFromString(estimate_mode.get_str(), cc.m_fee_mode)) {
+ + ]
244 [ + - + - ]: 54 : throw JSONRPCError(RPC_INVALID_PARAMETER, InvalidEstimateModeErrorMessage());
245 : : }
246 [ + + ]: 1639 : if (!conf_target.isNull()) {
247 : 32 : cc.m_confirm_target = ParseConfirmTarget(conf_target, wallet.chain().maximumFeeEstimationTargetBlocks());
248 : : }
249 : : }
250 : :
251 : 2188 : RPCMethod sendtoaddress()
252 : : {
253 : 2188 : return RPCMethod{
254 : 2188 : "sendtoaddress",
255 : 2188 : "Send an amount to a given address." +
256 [ + - ]: 2188 : HELP_REQUIRING_PASSPHRASE,
257 : : {
258 [ + - + - ]: 4376 : {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to send to."},
259 [ + - + - ]: 4376 : {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1"},
260 [ + - + - ]: 4376 : {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment used to store what the transaction is for.\n"
261 : : "This is not part of the transaction, just kept in your wallet."},
262 [ + - + - ]: 4376 : {"comment_to", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment to store the name of the person or organization\n"
263 : : "to which you're sending the transaction. This is not part of the \n"
264 : : "transaction, just kept in your wallet."},
265 [ + - + - : 6564 : {"subtractfeefromamount", RPCArg::Type::BOOL, RPCArg::Default{false}, "The fee will be deducted from the amount being sent.\n"
+ - ]
266 : : "The recipient will receive less bitcoins than you enter in the amount field."},
267 [ + - + - : 6564 : {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Signal that this transaction can be replaced by a transaction (BIP 125)"},
+ - ]
268 [ + - + - : 6564 : {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
+ - ]
269 [ + - + - ]: 4376 : {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
270 [ + - + - : 4376 : + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
+ - ]
271 [ + - + - : 6564 : {"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"
+ - ]
272 : : "dirty if they have previously been used in a transaction. If true, this also activates avoidpartialspends, grouping outputs by their addresses."},
273 [ + - + - : 6564 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
+ - ]
274 [ + - + - : 6564 : {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, return extra information about the transaction."},
+ - ]
275 : : },
276 : : {
277 [ + - ]: 2188 : RPCResult{"if verbose is not set or set to false",
278 [ + - + - ]: 4376 : RPCResult::Type::STR_HEX, "txid", "The transaction id."
279 : 2188 : },
280 [ + - ]: 4376 : RPCResult{"if verbose is set to true",
281 [ + - + - ]: 4376 : RPCResult::Type::OBJ, "", "",
282 : : {
283 [ + - + - ]: 4376 : {RPCResult::Type::STR_HEX, "txid", "The transaction id."},
284 [ + - + - : 4376 : {RPCResult::Type::STR, "fee_reason", "The reason the wallet selected this fee rate (\"" + FeeReasons("\", \"") + "\")."}
+ - + - ]
285 : : },
286 [ + - + + : 13128 : },
- - ]
287 : : },
288 : 2188 : RPCExamples{
289 : : "\nSend 0.1 BTC\n"
290 [ + - + - : 6564 : + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1") +
+ - + - ]
291 : 2188 : "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode using positional arguments\n"
292 [ + - + - : 10940 : + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1 \"donation\" \"sean's outpost\" false true 6 economical") +
+ - + - ]
293 [ + - ]: 4376 : "\nSend 0.1 BTC with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB, subtract fee from amount, BIP125-replaceable, using positional arguments\n"
294 [ + - + - : 10940 : + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1 \"drinks\" \"room77\" true true null \"unset\" null 1.1") +
+ - + - ]
295 : 2188 : "\nSend 0.2 BTC with a confirmation target of 6 blocks in economical fee estimate mode using named arguments\n"
296 [ + - + - : 10940 : + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.2 conf_target=6 estimate_mode=\"economical\"") +
+ - + - ]
297 [ + - ]: 4376 : "\nSend 0.5 BTC with a fee rate of 25 " + CURRENCY_ATOM + "/vB using named arguments\n"
298 [ + - + - : 10940 : + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.5 fee_rate=25")
+ - + - ]
299 [ + - + - : 8752 : + 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")
+ - ]
300 [ + - ]: 2188 : },
301 : 2188 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
302 : : {
303 : 1279 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
304 [ - + ]: 1279 : if (!pwallet) return UniValue::VNULL;
305 : :
306 : : // Make sure the results are valid at least up to the most recent block
307 : : // the user could have gotten from another RPC command prior to now
308 [ + - ]: 1279 : pwallet->BlockUntilSyncedToCurrentChain();
309 : :
310 [ + - ]: 1279 : LOCK(pwallet->cs_wallet);
311 : :
312 : : // Wallet comments
313 : 1279 : std::optional<std::string> comment;
314 : 1279 : std::optional<std::string> comment_to;
315 [ + - + + : 1279 : if (!request.params[2].isNull() && !request.params[2].get_str().empty())
+ - + - +
+ ]
316 [ + - + - : 7 : comment = request.params[2].get_str();
+ - ]
317 [ + - + + : 1279 : if (!request.params[3].isNull() && !request.params[3].get_str().empty())
+ - + - +
+ ]
318 [ + - + - : 1 : comment_to = request.params[3].get_str();
+ - ]
319 : :
320 [ + - ]: 1279 : CCoinControl coin_control;
321 [ + - + + ]: 1279 : if (!request.params[5].isNull()) {
322 [ + - + - ]: 2 : coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
323 : : }
324 : :
325 [ + - + - ]: 1279 : coin_control.m_avoid_address_reuse = GetAvoidReuseFlag(*pwallet, request.params[8]);
326 : : // We also enable partial spend avoidance if reuse avoidance is set.
327 : 1279 : coin_control.m_avoid_partial_spends |= coin_control.m_avoid_address_reuse;
328 : :
329 [ + - + - : 1279 : SetFeeEstimateMode(*pwallet, coin_control, /*conf_target=*/request.params[6], /*estimate_mode=*/request.params[7], /*fee_rate=*/request.params[9], /*override_min_fee=*/false);
+ - + - ]
330 : :
331 [ + + ]: 1279 : EnsureWalletIsUnlocked(*pwallet);
332 : :
333 : 1276 : UniValue address_amounts(UniValue::VOBJ);
334 [ + - + - : 1276 : const std::string address = request.params[0].get_str();
- + ]
335 [ + - + - : 3828 : address_amounts.pushKV(address, request.params[1]);
+ - ]
336 : :
337 [ + - ]: 1276 : std::set<int> sffo_set;
338 [ + - + + ]: 1276 : if (self.Arg<bool>("subtractfeefromamount")) {
339 [ + - ]: 216 : sffo_set.insert(0);
340 : : }
341 : :
342 [ + + + - ]: 1276 : std::vector<CRecipient> recipients{CreateRecipients(ParseOutputs(address_amounts), sffo_set)};
343 [ + - ]: 1274 : const bool verbose{self.Arg<bool>("verbose")};
344 : :
345 [ + - + - : 5105 : return SendMoney(*pwallet, coin_control, recipients, comment, comment_to, verbose);
+ + ]
346 [ + - ]: 3882 : },
347 [ + - + - : 43760 : };
+ - + - +
+ + + - -
- - ]
348 [ + - + - : 65640 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - - - -
- - ]
349 : :
350 : 993 : RPCMethod sendmany()
351 : : {
352 : 993 : return RPCMethod{"sendmany",
353 : 993 : "Send multiple times. Amounts are double-precision floating point numbers." +
354 [ + - ]: 993 : HELP_REQUIRING_PASSPHRASE,
355 : : {
356 [ + - + - : 2979 : {"dummy", RPCArg::Type::STR, RPCArg::Default{"\"\""}, "Must be set to \"\" for backwards compatibility.",
+ - ]
357 [ + - ]: 1986 : RPCArgOptions{
358 : : .oneline_description = "\"\"",
359 : : .placeholder = true,
360 : : }},
361 [ + - + - ]: 1986 : {"amounts", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::NO, "The addresses and amounts",
362 : : {
363 [ + - + - ]: 1986 : {"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"},
364 : : },
365 : : },
366 [ + - + - ]: 1986 : {"minconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Ignored dummy value",
367 [ + - ]: 1986 : RPCArgOptions{.placeholder = true}},
368 [ + - + - ]: 1986 : {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment"},
369 [ + - + - ]: 1986 : {"subtractfeefrom", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The addresses.\n"
370 : : "The fee will be equally deducted from the amount of each selected address.\n"
371 : : "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
372 : : "If no addresses are specified here, the sender pays the fee.",
373 : : {
374 [ + - + - ]: 1986 : {"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Subtract fee from this address"},
375 : : },
376 : : },
377 [ + - + - : 2979 : {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Signal that this transaction can be replaced by a transaction (BIP 125)"},
+ - ]
378 [ + - + - : 2979 : {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
+ - ]
379 [ + - + - ]: 1986 : {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
380 [ + - + - : 1986 : + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
+ - ]
381 [ + - + - : 2979 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
+ - ]
382 [ + - + - : 2979 : {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, return extra information about the transaction."},
+ - ]
383 : : },
384 : : {
385 [ + - ]: 993 : RPCResult{"if verbose is not set or set to false",
386 [ + - + - ]: 1986 : RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n"
387 : : "the number of addresses."
388 : 993 : },
389 [ + - ]: 1986 : RPCResult{"if verbose is set to true",
390 [ + - + - ]: 1986 : RPCResult::Type::OBJ, "", "",
391 : : {
392 [ + - + - ]: 1986 : {RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n"
393 : : "the number of addresses."},
394 [ + - + - : 1986 : {RPCResult::Type::STR, "fee_reason", "The reason the wallet selected this fee rate (\"" + FeeReasons("\", \"") + "\")."}
+ - + - ]
395 : : },
396 [ + - + + : 5958 : },
- - ]
397 : : },
398 : 993 : RPCExamples{
399 : : "\nSend two amounts to two different addresses:\n"
400 [ + - + - : 3972 : + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\"") +
+ - + - +
- ]
401 : 993 : "\nSend two amounts to two different addresses setting the confirmation and comment:\n"
402 [ + - + - : 5958 : + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\" 6 \"testing\"") +
+ - + - +
- ]
403 : 993 : "\nSend two amounts to two different addresses, subtract fee from amount:\n"
404 [ + - + - : 7944 : + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\" 1 \"\" \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") +
+ - + - +
- + - +
- ]
405 : 993 : "\nAs a JSON-RPC call\n"
406 [ + - + - : 4965 : + HelpExampleRpc("sendmany", "\"\", {\"" + EXAMPLE_ADDRESS[0] + "\":0.01,\"" + EXAMPLE_ADDRESS[1] + "\":0.02}, 6, \"testing\"")
+ - + - ]
407 [ + - ]: 993 : },
408 : 993 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
409 : : {
410 : 84 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
411 [ - + ]: 84 : if (!pwallet) return UniValue::VNULL;
412 : :
413 : : // Make sure the results are valid at least up to the most recent block
414 : : // the user could have gotten from another RPC command prior to now
415 [ + - ]: 84 : pwallet->BlockUntilSyncedToCurrentChain();
416 : :
417 [ + - ]: 84 : LOCK(pwallet->cs_wallet);
418 : :
419 [ + - + + : 84 : if (!request.params[0].isNull() && !request.params[0].get_str().empty()) {
+ - + - -
+ ]
420 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Dummy value must be set to \"\"");
421 : : }
422 [ + - + - : 84 : UniValue sendTo = request.params[1].get_obj();
+ - ]
423 : :
424 : 84 : std::optional<std::string> comment;
425 [ + - + + : 84 : if (!request.params[3].isNull() && !request.params[3].get_str().empty())
+ - + - -
+ ]
426 [ # # # # : 0 : comment = request.params[3].get_str();
# # ]
427 : :
428 [ + - ]: 84 : CCoinControl coin_control;
429 [ + - - + ]: 84 : if (!request.params[5].isNull()) {
430 [ # # # # ]: 0 : coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
431 : : }
432 : :
433 [ + - + - : 84 : SetFeeEstimateMode(*pwallet, coin_control, /*conf_target=*/request.params[6], /*estimate_mode=*/request.params[7], /*fee_rate=*/request.params[8], /*override_min_fee=*/false);
+ - + + ]
434 : :
435 : 61 : std::vector<CRecipient> recipients = CreateRecipients(
436 [ + - ]: 110 : ParseOutputs(sendTo),
437 [ + - + - : 61 : InterpretSubtractFeeFromOutputInstructions(&request.params[4], sendTo.getKeys())
+ + ]
438 [ + - ]: 55 : );
439 [ + - ]: 55 : const bool verbose{self.Arg<bool>("verbose")};
440 : :
441 [ + - + + ]: 178 : return SendMoney(*pwallet, coin_control, recipients, comment, /*comment_to=*/std::nullopt, verbose);
442 [ + - ]: 265 : },
443 [ + - + - : 24825 : };
+ - + - +
- + - + +
+ + + + +
+ - - - -
- - - - ]
444 [ + - + - : 29790 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
- - - - ]
445 : :
446 : : // Only includes key documentation where the key is snake_case in all RPC methods. MixedCase keys can be added later.
447 : 4575 : static std::vector<RPCArg> FundTxDoc(bool solving_data = true)
448 : : {
449 : 4575 : std::vector<RPCArg> args = {
450 [ + - + - : 13725 : {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks", RPCArgOptions{.also_positional = true}},
+ - + - ]
451 [ + - + - ]: 9150 : {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
452 [ + - + - : 9150 : + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used")), RPCArgOptions{.also_positional = true}},
+ - + - ]
453 : : {
454 [ + - + - : 13725 : "replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Marks this transaction as BIP125-replaceable.\n"
+ - ]
455 : : "Allows this transaction to be replaced by a transaction with higher fees"
456 : : },
457 [ + - + + : 22875 : };
- - ]
458 [ + - ]: 4575 : if (solving_data) {
459 [ + - + - : 77775 : args.push_back({"solving_data", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "Keys and scripts needed for producing a final transaction with a dummy signature.\n"
+ - + - +
- + - + -
+ + + + +
+ + + - -
- - - - -
- ]
460 : : "Used for fee estimation during coin selection.",
461 : : {
462 : : {
463 [ + - + - ]: 9150 : "pubkeys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Public keys involved in this transaction.",
464 : : {
465 [ + - + - ]: 9150 : {"pubkey", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A public key"},
466 : : }
467 : : },
468 : : {
469 [ + - + - ]: 9150 : "scripts", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Scripts involved in this transaction.",
470 : : {
471 [ + - + - ]: 9150 : {"script", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A script"},
472 : : }
473 : : },
474 : : {
475 [ + - + - ]: 9150 : "descriptors", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Descriptors that provide solving data for this transaction.",
476 : : {
477 [ + - + - ]: 9150 : {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A descriptor"},
478 : : }
479 : : },
480 : : }
481 : : });
482 : : }
483 : 4575 : return args;
484 [ + - + - : 77775 : }
+ - + - +
- + - + -
+ - + - +
- - - -
- ]
485 : :
486 : 709 : CreatedTransactionResult FundTransaction(CWallet& wallet, const CMutableTransaction& tx, const std::vector<CRecipient>& recipients, const UniValue& options, CCoinControl& coinControl, bool override_min_fee)
487 : : {
488 : : // We want to make sure tx.vout is not used now that we are passing outputs as a vector of recipients.
489 : : // This sets us up to remove tx completely in a future PR in favor of passing the inputs directly.
490 : 709 : CHECK_NONFATAL(tx.vout.empty());
491 : : // Make sure the results are valid at least up to the most recent block
492 : : // the user could have gotten from another RPC command prior to now
493 : 709 : wallet.BlockUntilSyncedToCurrentChain();
494 : :
495 : 709 : std::optional<unsigned int> change_position;
496 : 709 : bool lockUnspents = false;
497 [ + + ]: 709 : if (!options.isNull()) {
498 [ + + + + : 19540 : RPCTypeCheckObj(options,
+ + ]
499 : : {
500 [ + - ]: 673 : {"add_inputs", UniValueType(UniValue::VBOOL)},
501 [ + - ]: 673 : {"include_unsafe", UniValueType(UniValue::VBOOL)},
502 [ + - ]: 673 : {"add_to_wallet", UniValueType(UniValue::VBOOL)},
503 [ + - ]: 673 : {"changeAddress", UniValueType(UniValue::VSTR)},
504 [ + - ]: 673 : {"change_address", UniValueType(UniValue::VSTR)},
505 [ + - ]: 673 : {"changePosition", UniValueType(UniValue::VNUM)},
506 [ + - ]: 673 : {"change_position", UniValueType(UniValue::VNUM)},
507 [ + - ]: 673 : {"change_type", UniValueType(UniValue::VSTR)},
508 [ + - ]: 673 : {"includeWatching", UniValueType(UniValue::VBOOL)},
509 [ + - ]: 673 : {"include_watching", UniValueType(UniValue::VBOOL)},
510 [ + - ]: 673 : {"inputs", UniValueType(UniValue::VARR)},
511 [ + - ]: 673 : {"lockUnspents", UniValueType(UniValue::VBOOL)},
512 [ + - ]: 673 : {"lock_unspents", UniValueType(UniValue::VBOOL)},
513 [ + - ]: 673 : {"locktime", UniValueType(UniValue::VNUM)},
514 [ + - ]: 673 : {"fee_rate", UniValueType()}, // will be checked by AmountFromValue() in SetFeeEstimateMode()
515 [ + - ]: 673 : {"feeRate", UniValueType()}, // will be checked by AmountFromValue() below
516 [ + - ]: 673 : {"psbt", UniValueType(UniValue::VBOOL)},
517 [ + - ]: 673 : {"solving_data", UniValueType(UniValue::VOBJ)},
518 [ + - ]: 673 : {"subtractFeeFromOutputs", UniValueType(UniValue::VARR)},
519 [ + - ]: 673 : {"subtract_fee_from_outputs", UniValueType(UniValue::VARR)},
520 [ + - ]: 673 : {"replaceable", UniValueType(UniValue::VBOOL)},
521 [ + - ]: 673 : {"conf_target", UniValueType(UniValue::VNUM)},
522 [ + - ]: 673 : {"estimate_mode", UniValueType(UniValue::VSTR)},
523 [ + - ]: 673 : {"minconf", UniValueType(UniValue::VNUM)},
524 [ + - ]: 673 : {"maxconf", UniValueType(UniValue::VNUM)},
525 [ + - ]: 673 : {"input_weights", UniValueType(UniValue::VARR)},
526 [ + - ]: 673 : {"max_tx_weight", UniValueType(UniValue::VNUM)},
527 : : },
528 : : true, true);
529 : :
530 [ + + ]: 1300 : if (options.exists("add_inputs")) {
531 [ + - + - ]: 174 : coinControl.m_allow_other_inputs = options["add_inputs"].get_bool();
532 : : }
533 : :
534 [ + - + - : 650 : if (const UniValue* change_address = GetOptionWithAlias(options, "change_address", "changeAddress")) {
+ + ]
535 : 13 : CTxDestination dest{DecodeDestination(change_address->get_str())};
536 : :
537 [ + - + + ]: 13 : if (!IsValidDestination(dest)) {
538 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Change address must be a valid bitcoin address");
539 : : }
540 : :
541 [ + - ]: 22 : coinControl.destChange = dest;
542 : 13 : }
543 : :
544 [ + - + - : 648 : if (const UniValue* change_position_option = GetOptionWithAlias(options, "change_position", "changePosition")) {
+ + ]
545 : 61 : int pos = change_position_option->getInt<int>();
546 [ + - - + : 61 : if (pos < 0 || (unsigned int)pos > recipients.size()) {
+ + ]
547 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds");
548 : : }
549 : 60 : change_position = (unsigned int)pos;
550 : : }
551 : :
552 [ + + ]: 1294 : if (options.exists("change_type")) {
553 [ + - + - : 299 : if (options.exists("changeAddress") || options.exists("change_address")) {
+ + + - +
- + - + +
- - ]
554 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both change address and address type options");
555 : : }
556 [ + - + + : 198 : if (std::optional<OutputType> parsed = ParseOutputType(options["change_type"].get_str())) {
- + + - +
+ ]
557 [ - + ]: 194 : coinControl.m_change_type.emplace(parsed.value());
558 : : } else {
559 [ + - + - : 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown change type '%s'", options["change_type"].get_str()));
+ - + - +
- ]
560 : : }
561 : : }
562 : :
563 [ + - + - : 644 : if (const UniValue* lock_unspents = GetOptionWithAlias(options, "lock_unspents", "lockUnspents")) {
+ + ]
564 : 4 : lockUnspents = lock_unspents->get_bool();
565 : : }
566 : :
567 [ + + ]: 1288 : if (options.exists("include_unsafe")) {
568 [ + - + - ]: 46 : coinControl.m_include_unsafe_inputs = options["include_unsafe"].get_bool();
569 : : }
570 : :
571 [ + + ]: 1288 : if (options.exists("feeRate")) {
572 [ + + ]: 116 : if (options.exists("fee_rate")) {
573 [ + - + - : 8 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both fee_rate (" + CURRENCY_ATOM + "/vB) and feeRate (" + CURRENCY_UNIT + "/kvB)");
+ - ]
574 : : }
575 [ + + ]: 112 : if (options.exists("conf_target")) {
576 [ + - + - ]: 4 : 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.");
577 : : }
578 [ + + ]: 108 : if (options.exists("estimate_mode")) {
579 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and feeRate");
580 : : }
581 [ + - + + : 104 : coinControl.m_feerate = CFeeRate(AmountFromValue(options["feeRate"]));
- + ]
582 : 36 : coinControl.fOverrideFeeRate = true;
583 : : }
584 : :
585 [ + + ]: 1244 : if (options.exists("replaceable")) {
586 [ + - + - ]: 5 : coinControl.m_signal_bip125_rbf = options["replaceable"].get_bool();
587 : : }
588 : :
589 [ + + ]: 1244 : if (options.exists("minconf")) {
590 [ + - + - ]: 9 : coinControl.m_min_depth = options["minconf"].getInt<int>();
591 : :
592 [ + + ]: 9 : if (coinControl.m_min_depth < 0) {
593 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative minconf");
594 : : }
595 : : }
596 : :
597 [ + + ]: 1242 : if (options.exists("maxconf")) {
598 [ + - + - ]: 4 : coinControl.m_max_depth = options["maxconf"].getInt<int>();
599 : :
600 [ - + ]: 4 : if (coinControl.m_max_depth < coinControl.m_min_depth) {
601 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("maxconf can't be lower than minconf: %d < %d", coinControl.m_max_depth, coinControl.m_min_depth));
602 : : }
603 : : }
604 [ + - + - : 1436 : SetFeeEstimateMode(wallet, coinControl, options["conf_target"], options["estimate_mode"], options["fee_rate"], override_min_fee);
+ - + - +
- + + ]
605 : : }
606 : :
607 [ + + ]: 1120 : if (options.exists("solving_data")) {
608 [ + - + - : 14 : const UniValue solving_data = options["solving_data"].get_obj();
+ - ]
609 [ + - + + ]: 28 : if (solving_data.exists("pubkeys")) {
610 [ + - + - : 8 : for (const UniValue& pk_univ : solving_data["pubkeys"].get_array().getValues()) {
+ - + - +
+ ]
611 [ + - + + ]: 5 : const CPubKey pubkey = HexToPubKey(pk_univ.get_str());
612 [ + - + - ]: 3 : coinControl.m_external_provider.pubkeys.emplace(pubkey.GetID(), pubkey);
613 : : // Add witness script for pubkeys
614 [ + - + - ]: 3 : const CScript wit_script = GetScriptForDestination(WitnessV0KeyHash(pubkey));
615 [ + - + - ]: 3 : coinControl.m_external_provider.scripts.emplace(CScriptID(wit_script), wit_script);
616 : 3 : }
617 : : }
618 : :
619 [ + - + + ]: 24 : if (solving_data.exists("scripts")) {
620 [ + - + - : 9 : for (const UniValue& script_univ : solving_data["scripts"].get_array().getValues()) {
+ - + - +
+ ]
621 [ + - ]: 6 : const std::string& script_str = script_univ.get_str();
622 [ - + + - : 6 : if (!IsHex(script_str)) {
+ + ]
623 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not hex", script_str));
624 : : }
625 [ - + + - ]: 5 : std::vector<unsigned char> script_data(ParseHex(script_str));
626 : 5 : const CScript script(script_data.begin(), script_data.end());
627 [ + - + - ]: 5 : coinControl.m_external_provider.scripts.emplace(CScriptID(script), script);
628 : 5 : }
629 : : }
630 : :
631 [ + - + + ]: 22 : if (solving_data.exists("descriptors")) {
632 [ + - + - : 15 : for (const UniValue& desc_univ : solving_data["descriptors"].get_array().getValues()) {
+ - + - +
+ ]
633 [ + - ]: 8 : const std::string& desc_str = desc_univ.get_str();
634 : 8 : FlatSigningProvider desc_out;
635 [ - + ]: 8 : std::string error;
636 : 8 : std::vector<CScript> scripts_temp;
637 [ - + + - ]: 8 : auto descs = Parse(desc_str, desc_out, error, true);
638 [ + + ]: 8 : if (descs.empty()) {
639 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor '%s': %s", desc_str, error));
640 : : }
641 [ + + ]: 14 : for (auto& desc : descs) {
642 [ + - ]: 7 : desc->Expand(0, desc_out, scripts_temp, desc_out);
643 : : }
644 [ + - ]: 7 : coinControl.m_external_provider.Merge(std::move(desc_out));
645 : 10 : }
646 : : }
647 : 14 : }
648 : :
649 [ + + ]: 1112 : if (options.exists("input_weights")) {
650 [ + - + - : 2646 : for (const UniValue& input : options["input_weights"].get_array().getValues()) {
+ - + + ]
651 : 2491 : Txid txid = Txid::FromUint256(ParseHashO(input, "txid"));
652 : :
653 : 2491 : const UniValue& vout_v = input.find_value("vout");
654 [ + + ]: 2491 : if (!vout_v.isNum()) {
655 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
656 : : }
657 : 2490 : int vout = vout_v.getInt<int>();
658 [ + + ]: 2490 : if (vout < 0) {
659 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
660 : : }
661 : :
662 : 2489 : const UniValue& weight_v = input.find_value("weight");
663 [ + + ]: 2489 : if (!weight_v.isNum()) {
664 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing weight key");
665 : : }
666 : 2488 : int64_t weight = weight_v.getInt<int64_t>();
667 : 2488 : const int64_t min_input_weight = GetTransactionInputWeight(CTxIn());
668 : 2488 : CHECK_NONFATAL(min_input_weight == 165);
669 [ + + ]: 2488 : if (weight < min_input_weight) {
670 [ + - + - ]: 4 : 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)");
671 : : }
672 [ + + ]: 2486 : if (weight > MAX_STANDARD_TX_WEIGHT) {
673 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, weight cannot be greater than the maximum standard tx weight of %d", MAX_STANDARD_TX_WEIGHT));
674 : : }
675 : :
676 : 2485 : coinControl.SetInputWeight(COutPoint(txid, vout), weight);
677 : : }
678 : : }
679 : :
680 [ + + ]: 1100 : if (options.exists("max_tx_weight")) {
681 [ + - + - ]: 10 : coinControl.m_max_tx_weight = options["max_tx_weight"].getInt<int>();
682 : : }
683 : :
684 [ + + ]: 550 : if (tx.version == TRUC_VERSION) {
685 [ + + - + ]: 36 : if (!coinControl.m_max_tx_weight.has_value() || coinControl.m_max_tx_weight.value() > TRUC_MAX_WEIGHT) {
686 [ - + ]: 34 : coinControl.m_max_tx_weight = TRUC_MAX_WEIGHT;
687 : : }
688 : : }
689 : :
690 [ - + ]: 550 : if (recipients.empty())
691 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
692 : :
693 [ + - ]: 550 : auto txr = FundTransaction(wallet, tx, recipients, change_position, lockUnspents, coinControl);
694 [ + + ]: 550 : if (!txr) {
695 [ + - + - ]: 182 : throw JSONRPCError(RPC_WALLET_ERROR, ErrorString(txr).original);
696 : : }
697 : 459 : return *txr;
698 [ + - + - : 1155 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - - + ]
699 : :
700 : 467 : static void SetOptionsInputWeights(const UniValue& inputs, UniValue& options)
701 : : {
702 [ + + ]: 934 : if (options.exists("input_weights")) {
703 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Input weights should be specified in inputs rather than in options.");
704 : : }
705 [ - + + + ]: 465 : if (inputs.size() == 0) {
706 : : return;
707 : : }
708 : 191 : UniValue weights(UniValue::VARR);
709 [ + - + + ]: 3001 : for (const UniValue& input : inputs.getValues()) {
710 [ + - + + ]: 5620 : if (input.exists("weight")) {
711 [ + - + - ]: 6 : weights.push_back(input);
712 : : }
713 : : }
714 [ + - + - ]: 382 : options.pushKV("input_weights", std::move(weights));
715 : 191 : }
716 : :
717 : 1155 : RPCMethod fundrawtransaction()
718 : : {
719 : 1155 : return RPCMethod{
720 : 1155 : "fundrawtransaction",
721 [ + - ]: 2310 : "If the transaction has no inputs, they will be automatically selected to meet its out value.\n"
722 : : "It will add at most one change output to the outputs.\n"
723 : : "No existing outputs will be modified unless \"subtract_fee_from_outputs\" is specified.\n"
724 : : "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
725 : : "The inputs added will not be signed, use signrawtransactionwithkey\n"
726 : : "or signrawtransactionwithwallet for that.\n"
727 : : "All existing inputs must either have their previous output transaction be in the wallet\n"
728 : : "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n"
729 : : "Note that all inputs selected must be of standard form and P2SH scripts must be\n"
730 : : "in the wallet using importdescriptors (to calculate fees).\n"
731 : : "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n"
732 : : "Note that if specifying an exact fee rate, the resulting transaction may have a higher fee rate\n"
733 : : "if the transaction has unconfirmed inputs. This is because the wallet will attempt to make the\n"
734 : : "entire package have the given fee rate, not the resulting transaction.\n",
735 : : {
736 [ + - + - ]: 2310 : {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"},
737 [ + - + - ]: 2310 : {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
738 [ + - + - : 31185 : Cat<std::vector<RPCArg>>(
+ - + - +
- + + + +
+ + + + -
- - - - -
- - ]
739 : : {
740 [ + - + - : 3465 : {"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{true}, "For a transaction with existing inputs, automatically include more if they are not enough."},
+ - ]
741 [ + - + - : 3465 : {"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"
+ - ]
742 : : "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
743 : : "If that happens, you will need to fund the transaction with different inputs and republish it."},
744 [ + - + - : 3465 : {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."},
+ - ]
745 [ + - + - ]: 2310 : {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."},
746 [ + - + - : 3465 : {"change_address|changeAddress", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
+ - ]
747 [ + - + - : 3465 : {"change_position|changePosition", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
+ - ]
748 [ + - + - : 3465 : {"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if changeAddress is not specified. Options are " + FormatAllOutputTypes() + "."},
+ - + - ]
749 [ + - + - : 3465 : {"includeWatching", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
+ - ]
750 [ + - + - : 3465 : {"lock_unspents|lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
+ - ]
751 [ + - + - : 3465 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
+ - ]
752 [ + - + - : 3465 : {"feeRate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_UNIT + "/kvB."},
+ - ]
753 [ + - + - ]: 2310 : {"subtract_fee_from_outputs|subtractFeeFromOutputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The output indices to subtract the fee from.\n"
754 : : "The fee will be equally deducted from the amount of each specified output.\n"
755 : : "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
756 : : "If no outputs are specified here, the sender pays the fee.",
757 : : {
758 [ + - + - ]: 2310 : {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
759 : : },
760 : : },
761 [ + - + - ]: 2310 : {"input_weights", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Inputs and their corresponding weights",
762 : : {
763 [ + - + - ]: 2310 : {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
764 : : {
765 [ + - + - ]: 2310 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
766 [ + - + - ]: 2310 : {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output index"},
767 [ + - + - ]: 2310 : {"weight", RPCArg::Type::NUM, RPCArg::Optional::NO, "The maximum weight for this input, "
768 : : "including the weight of the outpoint and sequence number. "
769 : : "Note that serialized signature sizes are not guaranteed to be consistent, "
770 : : "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
771 : : "Remember to convert serialized sizes to weight units when necessary."},
772 : : },
773 : : },
774 : : },
775 : : },
776 [ + - + - : 3465 : {"max_tx_weight", RPCArg::Type::NUM, RPCArg::Default{MAX_STANDARD_TX_WEIGHT}, "The maximum acceptable transaction weight.\n"
+ - ]
777 : : "Transaction building will fail if this can not be satisfied."},
778 : : },
779 [ + - ]: 2310 : FundTxDoc()),
780 [ + - ]: 2310 : RPCArgOptions{
781 : : .oneline_description = "options",
782 : : }},
783 [ + - + - : 3465 : {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
+ - ]
784 : : "If iswitness is not present, heuristic tests will be used in decoding.\n"
785 : : "If true, only witness deserialization will be tried.\n"
786 : : "If false, only non-witness deserialization will be tried.\n"
787 : : "This boolean should reflect whether the transaction has inputs\n"
788 : : "(e.g. fully valid, or on-chain transactions), if known by the caller."
789 : : },
790 : : },
791 [ + - ]: 2310 : RPCResult{
792 [ + - + - ]: 2310 : RPCResult::Type::OBJ, "", "",
793 : : {
794 [ + - + - ]: 2310 : {RPCResult::Type::STR_HEX, "hex", "The resulting raw transaction (hex-encoded string)"},
795 [ + - + - ]: 2310 : {RPCResult::Type::STR_AMOUNT, "fee", "Fee in " + CURRENCY_UNIT + " the resulting transaction pays"},
796 [ + - + - ]: 2310 : {RPCResult::Type::NUM, "changepos", "The position of the added change output, or -1"},
797 : : }
798 [ + - + - : 9240 : },
+ + - - ]
799 : 1155 : RPCExamples{
800 : : "\nCreate a transaction with no inputs\n"
801 [ + - + - : 2310 : + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
+ - + - ]
802 : 1155 : "\nAdd sufficient unsigned inputs to meet the output value\n"
803 [ + - + - : 4620 : + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
+ - + - ]
804 : 1155 : "\nSign the transaction\n"
805 [ + - + - : 4620 : + HelpExampleCli("signrawtransactionwithwallet", "\"fundedtransactionhex\"") +
+ - + - ]
806 : 1155 : "\nSend the transaction\n"
807 [ + - + - : 4620 : + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
+ - + - ]
808 [ + - ]: 1155 : },
809 : 1155 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
810 : : {
811 : 245 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
812 [ - + ]: 245 : if (!pwallet) return UniValue::VNULL;
813 : :
814 : : // parse hex string from parameter
815 [ + - ]: 245 : CMutableTransaction tx;
816 [ + - - + : 245 : bool try_witness = request.params[2].isNull() ? true : request.params[2].get_bool();
- - - - ]
817 [ + - - + : 245 : bool try_no_witness = request.params[2].isNull() ? true : !request.params[2].get_bool();
- - - - ]
818 [ + - + - : 245 : if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
+ - - + ]
819 [ # # # # ]: 0 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
820 : : }
821 [ + - + - ]: 245 : UniValue options = request.params[1];
822 : 245 : std::vector<std::pair<CTxDestination, CAmount>> destinations;
823 [ + + ]: 11712 : for (const auto& tx_out : tx.vout) {
824 : 11467 : CTxDestination dest;
825 [ + - ]: 11467 : ExtractDestination(tx_out.scriptPubKey, dest);
826 [ + - ]: 11467 : destinations.emplace_back(dest, tx_out.nValue);
827 : 11467 : }
828 [ + - + - ]: 490 : std::vector<std::string> dummy(destinations.size(), "dummy");
829 : 245 : std::vector<CRecipient> recipients = CreateRecipients(
830 : : destinations,
831 [ + + + - ]: 489 : InterpretSubtractFeeFromOutputInstructions(
832 [ + - + - ]: 491 : GetOptionWithAlias(options, "subtract_fee_from_outputs", "subtractFeeFromOutputs"), dummy)
833 [ + - ]: 244 : );
834 [ + - ]: 244 : CCoinControl coin_control;
835 : : // Automatically select (additional) coins. Can be overridden by options.add_inputs.
836 : 244 : coin_control.m_allow_other_inputs = true;
837 : : // Clear tx.vout since it is not meant to be used now that we are passing outputs directly.
838 : : // This sets us up for a future PR to completely remove tx from the function signature in favor of passing inputs directly
839 : 244 : tx.vout.clear();
840 [ + + ]: 244 : auto txr = FundTransaction(*pwallet, tx, recipients, options, coin_control, /*override_min_fee=*/true);
841 : :
842 : 145 : UniValue result(UniValue::VOBJ);
843 [ + - + - : 290 : result.pushKV("hex", EncodeHexTx(*txr.tx));
+ - + - ]
844 [ + - + - : 290 : result.pushKV("fee", ValueFromAmount(txr.fee));
+ - ]
845 [ + + + - : 290 : result.pushKV("changepos", txr.change_pos ? (int)*txr.change_pos : -1);
+ - + - ]
846 : :
847 : 145 : return result;
848 [ + - ]: 1178 : },
849 [ + - + - : 8085 : };
+ + - - ]
850 [ + - + - : 56595 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - - - -
- - - - ]
851 : :
852 : 1232 : RPCMethod signrawtransactionwithwallet()
853 : : {
854 : 1232 : return RPCMethod{
855 : 1232 : "signrawtransactionwithwallet",
856 : : "Sign inputs for raw transaction (serialized, hex-encoded).\n"
857 : : "The second optional argument (may be null) is an array of previous transaction outputs that\n"
858 : 1232 : "this transaction depends on but may not yet be in the block chain." +
859 [ + - ]: 1232 : HELP_REQUIRING_PASSPHRASE,
860 : : {
861 [ + - + - ]: 2464 : {"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"},
862 [ + - + - ]: 2464 : {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The previous dependent transaction outputs",
863 : : {
864 [ + - + - ]: 2464 : {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
865 : : {
866 [ + - + - ]: 2464 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
867 [ + - + - ]: 2464 : {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
868 [ + - + - ]: 2464 : {"scriptPubKey", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The output script"},
869 [ + - + - ]: 2464 : {"redeemScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2SH) redeem script"},
870 [ + - + - ]: 2464 : {"witnessScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2WSH or P2SH-P2WSH) witness script"},
871 [ + - + - ]: 2464 : {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "(required for Segwit inputs) the amount spent"},
872 : : },
873 : : },
874 : : },
875 : : },
876 [ + - + - : 3696 : {"sighashtype", RPCArg::Type::STR, RPCArg::DefaultHint{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type. Must be one of\n"
+ - ]
877 : : " \"DEFAULT\"\n"
878 : : " \"ALL\"\n"
879 : : " \"NONE\"\n"
880 : : " \"SINGLE\"\n"
881 : : " \"ALL|ANYONECANPAY\"\n"
882 : : " \"NONE|ANYONECANPAY\"\n"
883 : : " \"SINGLE|ANYONECANPAY\""},
884 : : },
885 [ + - ]: 2464 : RPCResult{
886 [ + - + - ]: 2464 : RPCResult::Type::OBJ, "", "",
887 : : {
888 [ + - + - ]: 2464 : {RPCResult::Type::STR_HEX, "hex", "The hex-encoded raw transaction with signature(s)"},
889 [ + - + - ]: 2464 : {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
890 [ + - + - ]: 2464 : {RPCResult::Type::ARR, "errors", /*optional=*/true, "Script verification errors (if there are any)",
891 : : {
892 [ + - + - ]: 2464 : {RPCResult::Type::OBJ, "", "",
893 : : {
894 [ + - + - ]: 2464 : {RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"},
895 [ + - + - ]: 3696 : {RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"},
896 [ + - + - ]: 2464 : {RPCResult::Type::ARR, "witness", "",
897 : : {
898 [ + - + - ]: 2464 : {RPCResult::Type::STR_HEX, "witness", ""},
899 : : }},
900 [ + - + - ]: 2464 : {RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"},
901 [ + - + - ]: 2464 : {RPCResult::Type::NUM, "sequence", "Script sequence number"},
902 [ + - + - ]: 2464 : {RPCResult::Type::STR, "error", "Verification or signing error related to the input"},
903 : : }},
904 : : }},
905 : : }
906 [ + - + - : 33264 : },
+ - + - +
- + + + +
+ + + + -
- - - - -
- - ]
907 : 1232 : RPCExamples{
908 [ + - + - : 2464 : HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"")
+ - ]
909 [ + - + - : 4928 : + HelpExampleRpc("signrawtransactionwithwallet", "\"myhex\"")
+ - + - ]
910 [ + - ]: 1232 : },
911 : 1232 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
912 : : {
913 [ - + ]: 323 : const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
914 [ - + ]: 323 : if (!pwallet) return UniValue::VNULL;
915 : :
916 [ + - ]: 323 : CMutableTransaction mtx;
917 [ + - + - : 323 : if (!DecodeHexTx(mtx, request.params[0].get_str())) {
+ - - + ]
918 [ # # # # ]: 0 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
919 : : }
920 : :
921 : : // Sign the transaction
922 [ + - ]: 323 : LOCK(pwallet->cs_wallet);
923 [ + + ]: 323 : EnsureWalletIsUnlocked(*pwallet);
924 : :
925 : : // Fetch previous transactions (inputs):
926 : 322 : std::map<COutPoint, Coin> coins;
927 [ + + ]: 729 : for (const CTxIn& txin : mtx.vin) {
928 [ + - ]: 407 : coins[txin.prevout]; // Create empty map entry keyed by prevout.
929 : : }
930 [ + - ]: 322 : pwallet->chain().findCoins(coins);
931 : :
932 : : // Parse the prevtxs array
933 [ + - + + ]: 322 : ParsePrevouts(request.params[1], nullptr, coins);
934 : :
935 [ + - + + ]: 313 : std::optional<int> nHashType = ParseSighashString(request.params[2]);
936 [ + + ]: 312 : if (!nHashType) {
937 : 303 : nHashType = SIGHASH_DEFAULT;
938 : : }
939 : :
940 : : // Script verification errors
941 [ + - ]: 312 : std::map<int, bilingual_str> input_errors;
942 : :
943 [ + - ]: 312 : bool complete = pwallet->SignTransaction(mtx, coins, *nHashType, input_errors);
944 : 312 : UniValue result(UniValue::VOBJ);
945 [ + + ]: 312 : SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
946 : 310 : return result;
947 [ + - ]: 1282 : },
948 [ + - + - : 22176 : };
+ - + - +
+ + + + +
- - - - -
- ]
949 [ + - + - : 51744 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - - -
- - - - -
- ]
950 : :
951 : : // Definition of allowed formats of specifying transaction outputs in
952 : : // `bumpfee`, `psbtbumpfee`, `send` and `walletcreatefundedpsbt` RPCs.
953 : 4288 : static std::vector<RPCArg> OutputsDoc()
954 : : {
955 : 4288 : return
956 : : {
957 [ + - + - ]: 8576 : {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
958 : : {
959 [ + - ]: 8576 : {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address,\n"
960 [ + - ]: 8576 : "the value (float or string) is the amount in " + CURRENCY_UNIT + ""},
961 : : },
962 : : },
963 [ + - + - ]: 8576 : {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
964 : : {
965 [ + - + - ]: 8576 : {"data", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A key-value pair. The key must be \"data\", the value is hex-encoded data that becomes a part of an OP_RETURN output"},
966 : : },
967 : : },
968 [ + - + - : 47168 : };
+ - + + +
+ + + - -
- - - - ]
969 [ + - + - : 34304 : }
+ - + - -
- ]
970 : :
971 : 1997 : static RPCMethod bumpfee_helper(std::string method_name)
972 : : {
973 : 1997 : const bool want_psbt = method_name == "psbtbumpfee";
974 : 1997 : const std::string incremental_fee{CFeeRate(DEFAULT_INCREMENTAL_RELAY_FEE).ToString(FeeRateFormat::SAT_VB)};
975 : :
976 [ - + ]: 1997 : return RPCMethod{method_name,
977 : : "Bumps the fee of a transaction T, replacing it with a new transaction B.\n"
978 [ + - + - ]: 3994 : + std::string(want_psbt ? "Returns a PSBT instead of creating and signing a new transaction.\n" : "") +
979 : : "A transaction with the given txid must be in the wallet.\n"
980 : : "The command will pay the additional fee by reducing change outputs or adding inputs when necessary.\n"
981 : : "It may add a new change output if one does not already exist.\n"
982 : : "All inputs in the original transaction will be included in the replacement transaction.\n"
983 : : "The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n"
984 : : "By default, the new fee will be calculated automatically using the estimatesmartfee RPC.\n"
985 : : "The user can specify a confirmation target for estimatesmartfee.\n"
986 [ + - ]: 3994 : "Alternatively, the user can specify a fee rate in " + CURRENCY_ATOM + "/vB for the new transaction.\n"
987 : : "At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n"
988 : : "returned by getnetworkinfo) to enter the node's mempool.\n"
989 [ + - + - ]: 5991 : "* WARNING: before version 0.21, fee_rate was in " + CURRENCY_UNIT + "/kvB. As of 0.21, fee_rate is in " + CURRENCY_ATOM + "/vB. *\n",
990 : : {
991 [ + - + - ]: 3994 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The txid to be bumped"},
992 [ + - + - ]: 3994 : {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
993 [ + - + - : 15976 : Cat(
+ + - - ]
994 : : {
995 [ + - + - : 5991 : {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks\n"},
+ - ]
996 [ + - + - ]: 3994 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"},
997 [ + - ]: 3994 : "\nSpecify a fee rate in " + CURRENCY_ATOM + "/vB instead of relying on the built-in fee estimator.\n"
998 [ + - ]: 3994 : "Must be at least " + incremental_fee + " higher than the current transaction fee rate.\n"
999 [ + - + - ]: 5991 : "WARNING: before version 0.21, fee_rate was in " + CURRENCY_UNIT + "/kvB. As of 0.21, fee_rate is in " + CURRENCY_ATOM + "/vB.\n"},
1000 [ + - + - ]: 3994 : {"replaceable", RPCArg::Type::BOOL, RPCArg::Default{true},
1001 [ + - ]: 3994 : "Whether the new transaction should be\n"
1002 : : "marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n"
1003 : : "be set to 0xfffffffd. If false, any input sequence numbers in the\n"
1004 : : "transaction will be set to 0xfffffffe\n"
1005 : : "so the new transaction will not be explicitly bip-125 replaceable (though it may\n"
1006 : : "still be replaceable in practice, for example if it has unconfirmed ancestors which\n"
1007 : : "are replaceable).\n"},
1008 [ + - + - ]: 3994 : {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
1009 [ + - + - : 3994 : + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
+ - ]
1010 [ + - + - ]: 3994 : {"outputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The outputs specified as key-value pairs.\n"
1011 : : "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"
1012 : : "At least one output of either type must be specified.\n"
1013 : : "Cannot be provided if 'original_change_index' is specified.",
1014 [ + - ]: 3994 : OutputsDoc(),
1015 [ + - ]: 3994 : RPCArgOptions{.skip_type_check = true}},
1016 [ + - + - : 5991 : {"original_change_index", RPCArg::Type::NUM, RPCArg::DefaultHint{"not set, detect change automatically"}, "The 0-based index of the change output on the original transaction. "
+ - ]
1017 : : "The indicated output will be recycled into the new change output on the bumped transaction. "
1018 : : "The remainder after paying the recipients and fees will be sent to the output script of the "
1019 : : "original change output. The change output’s amount can increase if bumping the transaction "
1020 : : "adds new inputs, otherwise it will decrease. Cannot be used in combination with the 'outputs' option."},
1021 : : },
1022 [ + + + - : 10591 : want_psbt ? std::vector<RPCArg>{{"psbt_version", RPCArg::Type::NUM, RPCArg::Default(2), "The PSBT version number to use."}} : std::vector<RPCArg>()
+ - + - +
- + + + +
+ + + + +
+ + + - -
- - - - -
- - - -
- ]
1023 : : ),
1024 [ + - ]: 3994 : RPCArgOptions{.oneline_description="options"}},
1025 : : },
1026 [ + - ]: 3994 : RPCResult{
1027 [ + - + - : 27958 : RPCResult::Type::OBJ, "", "", Cat(
+ - + - +
- + + + +
- - - - ]
1028 [ + + + - : 9985 : want_psbt ?
+ - + + +
+ + + + +
- - - - -
- - - ]
1029 [ + - + - : 5677 : std::vector<RPCResult>{{RPCResult::Type::STR, "psbt", "The base64-encoded unsigned PSBT of the new transaction."}} :
+ + + + +
+ - - - -
- - ]
1030 [ + - + - : 6305 : std::vector<RPCResult>{{RPCResult::Type::STR_HEX, "txid", "The id of the new transaction."}},
+ + + + +
+ - - - -
- - ]
1031 : : {
1032 [ + - + - ]: 3994 : {RPCResult::Type::STR_AMOUNT, "origfee", "The fee of the replaced transaction."},
1033 [ + - + - ]: 3994 : {RPCResult::Type::STR_AMOUNT, "fee", "The fee of the new transaction."},
1034 [ + - + - ]: 3994 : {RPCResult::Type::ARR, "errors", "Errors encountered during processing (may be empty).",
1035 : : {
1036 [ + - + - ]: 3994 : {RPCResult::Type::STR, "", ""},
1037 : : }},
1038 : : })
1039 [ + - ]: 3994 : },
1040 : 1997 : RPCExamples{
1041 [ + + + - : 5071 : "\nBump the fee, get the new transaction\'s " + std::string(want_psbt ? "psbt" : "txid") + "\n" +
+ - ]
1042 [ + - + - : 5991 : HelpExampleCli(method_name, "<txid>")
+ - ]
1043 : 1997 : },
1044 [ + - ]: 3994 : [want_psbt](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1045 : : {
1046 : 179 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
1047 [ - + ]: 179 : if (!pwallet) return UniValue::VNULL;
1048 : :
1049 [ + - + + : 179 : if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER) && !want_psbt) {
+ - + + +
+ ]
1050 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_ERROR, "bumpfee is not available with wallets that have private keys disabled. Use psbtbumpfee instead.");
1051 : : }
1052 : :
1053 [ + - + - ]: 178 : Txid hash{Txid::FromUint256(ParseHashV(request.params[0], "txid"))};
1054 : :
1055 [ + - ]: 178 : CCoinControl coin_control;
1056 : : // optional parameters
1057 : 178 : coin_control.m_signal_bip125_rbf = true;
1058 : 178 : std::vector<CTxOut> outputs;
1059 : :
1060 : 178 : std::optional<uint32_t> original_change_index;
1061 : :
1062 : 178 : uint32_t psbt_version = 2;
1063 : :
1064 [ + - + + ]: 178 : if (!request.params[1].isNull()) {
1065 [ + - + - ]: 87 : UniValue options = request.params[1];
1066 [ + + + + : 874 : RPCTypeCheckObj(options,
+ + ]
1067 : : {
1068 [ + - ]: 87 : {"confTarget", UniValueType(UniValue::VNUM)}, // Deprecated, undocumented alias.
1069 [ + - ]: 87 : {"conf_target", UniValueType(UniValue::VNUM)},
1070 [ + - ]: 87 : {"fee_rate", UniValueType()}, // will be checked by AmountFromValue() in SetFeeEstimateMode()
1071 [ + - ]: 87 : {"replaceable", UniValueType(UniValue::VBOOL)},
1072 [ + - ]: 87 : {"estimate_mode", UniValueType(UniValue::VSTR)},
1073 [ + - ]: 87 : {"outputs", UniValueType()}, // will be checked by AddOutputs()
1074 [ + - ]: 87 : {"original_change_index", UniValueType(UniValue::VNUM)},
1075 [ + - ]: 87 : {"psbt_version", UniValueType(UniValue::VNUM)},
1076 : : },
1077 : : true, true);
1078 : :
1079 [ + - + - : 169 : if (options.exists("confTarget") && !pwallet->chain().rpcEnableDeprecated("confTarget")) {
+ + + - +
- + + + +
- - ]
1080 [ + - + - ]: 4 : throw JSONRPCError(RPC_METHOD_DEPRECATED, "DEPRECATION WARNING: Use conf_target (confTarget is deprecated and will be removed in the next release). To use it, start the RPC server with the `-deprecatedrpc=confTarget`.");
1081 : : }
1082 : :
1083 [ + - + - : 163 : if (options.exists("confTarget") && options.exists("conf_target")) {
+ + + - +
- + - + +
- - ]
1084 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "confTarget and conf_target options should not both be set. Use conf_target (confTarget is deprecated).");
1085 : : }
1086 : :
1087 [ + - - + : 240 : auto conf_target = options.exists("confTarget") ? options["confTarget"] : options["conf_target"];
- - - - +
- + - + -
+ - - + -
- - - ]
1088 : :
1089 [ + - + + ]: 160 : if (options.exists("replaceable")) {
1090 [ + - + - : 1 : coin_control.m_signal_bip125_rbf = options["replaceable"].get_bool();
+ - ]
1091 : : }
1092 [ + - + - : 179 : SetFeeEstimateMode(*pwallet, coin_control, conf_target, options["estimate_mode"], options["fee_rate"], /*override_min_fee=*/false);
+ - + - +
+ ]
1093 : :
1094 : : // Prepare new outputs by creating a temporary tx and calling AddOutputs().
1095 [ + - + - : 61 : if (!options["outputs"].isNull()) {
+ + ]
1096 [ + - + - : 31 : if (options["outputs"].isArray() && options["outputs"].empty()) {
+ + + - +
- - + + +
+ + - - ]
1097 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output argument cannot be an empty array");
1098 : : }
1099 [ + - ]: 10 : CMutableTransaction tempTx;
1100 [ + - + - : 12 : AddOutputs(tempTx, options["outputs"]);
+ + ]
1101 [ + - ]: 8 : outputs = tempTx.vout;
1102 : 10 : }
1103 : :
1104 [ + - + + ]: 116 : if (options.exists("original_change_index")) {
1105 [ + - + - : 7 : original_change_index = options["original_change_index"].getInt<uint32_t>();
+ + ]
1106 : : }
1107 : :
1108 [ + - + + ]: 114 : if (options.exists("psbt_version")) {
1109 [ + - + - : 3 : psbt_version = options["psbt_version"].getInt<uint32_t>();
+ - ]
1110 : : }
1111 [ + + ]: 57 : if (psbt_version != 2 && psbt_version != 0) {
1112 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "The PSBT version can only be 2 or 0");
1113 : : }
1114 : 111 : }
1115 : :
1116 : : // Make sure the results are valid at least up to the most recent block
1117 : : // the user could have gotten from another RPC command prior to now
1118 [ + - ]: 147 : pwallet->BlockUntilSyncedToCurrentChain();
1119 : :
1120 [ + - ]: 147 : LOCK(pwallet->cs_wallet);
1121 : :
1122 [ + + ]: 147 : EnsureWalletIsUnlocked(*pwallet);
1123 : :
1124 : :
1125 : 146 : std::vector<bilingual_str> errors;
1126 : 146 : CAmount old_fee;
1127 : 146 : CAmount new_fee;
1128 [ + - ]: 146 : CMutableTransaction mtx;
1129 : : // Targeting feerate bump.
1130 : 292 : [&](){
1131 [ - - + + : 146 : switch (feebumper::CreateRateBumpTransaction(*pwallet, hash, coin_control, errors, old_fee, new_fee, mtx, /*require_mine=*/ !want_psbt, outputs, original_change_index)) {
+ - + ]
1132 : 113 : case feebumper::Result::OK:
1133 : 113 : return;
1134 : 0 : case feebumper::Result::INVALID_ADDRESS_OR_KEY:
1135 [ # # ]: 0 : throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errors[0].original);
1136 : 0 : case feebumper::Result::INVALID_REQUEST:
1137 [ # # ]: 0 : throw JSONRPCError(RPC_INVALID_REQUEST, errors[0].original);
1138 : 16 : case feebumper::Result::INVALID_PARAMETER:
1139 [ + - ]: 16 : throw JSONRPCError(RPC_INVALID_PARAMETER, errors[0].original);
1140 : 16 : case feebumper::Result::WALLET_ERROR:
1141 [ + - ]: 16 : throw JSONRPCError(RPC_WALLET_ERROR, errors[0].original);
1142 : 1 : case feebumper::Result::MISC_ERROR:
1143 [ + - ]: 1 : throw JSONRPCError(RPC_MISC_ERROR, errors[0].original);
1144 : : } // no default case, so the compiler can warn about missing cases
1145 : 0 : NONFATAL_UNREACHABLE();
1146 [ + + ]: 146 : }();
1147 : :
1148 : 113 : UniValue result(UniValue::VOBJ);
1149 : :
1150 : : // For bumpfee, return the new transaction id.
1151 : : // For psbtbumpfee, return the base64-encoded unsigned PSBT of the new transaction.
1152 [ + + ]: 113 : if (!want_psbt) {
1153 [ + - - + ]: 104 : if (!feebumper::SignTransaction(*pwallet, mtx)) {
1154 [ # # # # ]: 0 : if (pwallet->IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
1155 [ # # # # ]: 0 : throw JSONRPCError(RPC_WALLET_ERROR, "Transaction incomplete. Try psbtbumpfee instead.");
1156 : : }
1157 [ # # # # ]: 0 : throw JSONRPCError(RPC_WALLET_ERROR, "Can't sign transaction.");
1158 : : }
1159 : :
1160 [ + - ]: 104 : Txid txid;
1161 [ + - - + ]: 104 : if (feebumper::CommitTransaction(*pwallet, hash, std::move(mtx), errors, txid) != feebumper::Result::OK) {
1162 [ # # ]: 0 : throw JSONRPCError(RPC_WALLET_ERROR, errors[0].original);
1163 : : }
1164 : :
1165 [ + - + - : 208 : result.pushKV("txid", txid.GetHex());
+ - + - ]
1166 : : } else {
1167 [ + - ]: 9 : PartiallySignedTransaction psbtx{mtx, psbt_version};
1168 : 9 : bool complete = false;
1169 [ + - ]: 9 : const auto err{pwallet->FillPSBT(psbtx, {.sign = false, .bip32_derivs = true}, complete)};
1170 [ + - ]: 9 : CHECK_NONFATAL(!err);
1171 [ + - ]: 9 : CHECK_NONFATAL(!complete);
1172 : 9 : DataStream ssTx{};
1173 [ + - ]: 9 : ssTx << psbtx;
1174 [ + - + - : 27 : result.pushKV("psbt", EncodeBase64(ssTx.str()));
+ - + - +
- ]
1175 : 9 : }
1176 : :
1177 [ + - + - : 226 : result.pushKV("origfee", ValueFromAmount(old_fee));
+ - ]
1178 [ + - + - : 226 : result.pushKV("fee", ValueFromAmount(new_fee));
+ - ]
1179 : 113 : UniValue result_errors(UniValue::VARR);
1180 [ - + ]: 113 : for (const bilingual_str& error : errors) {
1181 [ # # # # ]: 0 : result_errors.push_back(error.original);
1182 : : }
1183 [ + - + - ]: 226 : result.pushKV("errors", std::move(result_errors));
1184 : :
1185 : 113 : return result;
1186 [ + - + - : 706 : },
+ - + - +
- + - + -
+ - + - +
- - + ]
1187 [ + + + - : 13979 : };
+ - + + -
- ]
1188 [ + - + - : 57756 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + + + +
+ + - - -
- - - - -
- - - - ]
1189 : :
1190 [ + - ]: 2154 : RPCMethod bumpfee() { return bumpfee_helper("bumpfee"); }
1191 [ + - ]: 1840 : RPCMethod psbtbumpfee() { return bumpfee_helper("psbtbumpfee"); }
1192 : :
1193 : 1146 : RPCMethod send()
1194 : : {
1195 : 1146 : return RPCMethod{
1196 : 1146 : "send",
1197 [ + - ]: 2292 : "Send a transaction.\n",
1198 : : {
1199 [ + - + - ]: 2292 : {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n"
1200 : : "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"
1201 : : "At least one output of either type must be specified.\n"
1202 : : "For convenience, a dictionary, which holds the key-value pairs directly, is also accepted.",
1203 [ + - ]: 2292 : OutputsDoc(),
1204 [ + - ]: 2292 : RPCArgOptions{.skip_type_check = true}},
1205 [ + - + - : 3438 : {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
+ - ]
1206 [ + - + - ]: 2292 : {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
1207 [ + - + - : 2292 : + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
+ - ]
1208 [ + - + - : 3438 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
+ - ]
1209 [ + - + - ]: 2292 : {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
1210 [ + - + - : 34380 : Cat<std::vector<RPCArg>>(
+ - + - +
- + + + +
+ + + + -
- - - - -
- - ]
1211 : : {
1212 [ + - + - : 3438 : {"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"},
+ - ]
1213 [ + - + - : 3438 : {"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"
+ - ]
1214 : : "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
1215 : : "If that happens, you will need to fund the transaction with different inputs and republish it."},
1216 [ + - + - : 3438 : {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."},
+ - ]
1217 [ + - + - ]: 2292 : {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."},
1218 [ + - + - : 3438 : {"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"},
+ - ]
1219 [ + - + - : 3438 : {"change_address", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
+ - ]
1220 [ + - + - : 3438 : {"change_position", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
+ - ]
1221 [ + - + - : 3438 : {"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 " + FormatAllOutputTypes() + "."},
+ - + - ]
1222 [ + - + - : 4584 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB.", RPCArgOptions{.also_positional = true}},
+ - + - ]
1223 [ + - + - : 3438 : {"include_watching", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
+ - ]
1224 [ + - + - ]: 2292 : {"inputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Specify inputs instead of adding them automatically.",
1225 : : {
1226 [ + - + - ]: 2292 : {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", {
1227 [ + - + - ]: 2292 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1228 [ + - + - ]: 2292 : {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1229 [ + - + - : 3438 : {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
+ - ]
1230 [ + - + - : 3438 : {"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, "
+ - ]
1231 : : "including the weight of the outpoint and sequence number. "
1232 : : "Note that signature sizes are not guaranteed to be consistent, "
1233 : : "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
1234 : : "Remember to convert serialized sizes to weight units when necessary."},
1235 : : }},
1236 : : },
1237 : : },
1238 [ + - + - : 3438 : {"locktime", RPCArg::Type::NUM, RPCArg::DefaultHint{"locktime close to block height to prevent fee sniping"}, "Raw locktime. Non-0 value also locktime-activates inputs"},
+ - ]
1239 [ + - + - : 3438 : {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
+ - ]
1240 [ + - + - : 3438 : {"psbt", RPCArg::Type::BOOL, RPCArg::DefaultHint{"automatic"}, "Always return a PSBT, implies add_to_wallet=false."},
+ - ]
1241 [ + - + - ]: 2292 : {"subtract_fee_from_outputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Outputs to subtract the fee from, specified as integer indices.\n"
1242 : : "The fee will be equally deducted from the amount of each specified output.\n"
1243 : : "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
1244 : : "If no outputs are specified here, the sender pays the fee.",
1245 : : {
1246 [ + - + - ]: 2292 : {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
1247 : : },
1248 : : },
1249 [ + - + - : 3438 : {"max_tx_weight", RPCArg::Type::NUM, RPCArg::Default{MAX_STANDARD_TX_WEIGHT}, "The maximum acceptable transaction weight.\n"
+ - ]
1250 : : "Transaction building will fail if this can not be satisfied."},
1251 : : },
1252 [ + - ]: 2292 : FundTxDoc()),
1253 [ + - ]: 2292 : RPCArgOptions{.oneline_description="options"}},
1254 [ + - + - : 3438 : {"version", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_WALLET_TX_VERSION}, "Transaction version"},
+ - ]
1255 : : },
1256 [ + - ]: 2292 : RPCResult{
1257 [ + - + - ]: 2292 : RPCResult::Type::OBJ, "", "",
1258 : : {
1259 [ + - + - ]: 2292 : {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1260 [ + - + - ]: 2292 : {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."},
1261 [ + - + - ]: 2292 : {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
1262 [ + - + - ]: 2292 : {RPCResult::Type::STR, "psbt", /*optional=*/true, "If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"}
1263 : : }
1264 [ + - + - : 11460 : },
+ + - - ]
1265 : 1146 : RPCExamples{""
1266 : : "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode\n"
1267 [ + - + - : 3438 : + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.1}' 6 economical\n") +
+ - + - ]
1268 [ + - ]: 2292 : "Send 0.2 BTC with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB using positional arguments\n"
1269 [ + - + - : 5730 : + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.2}' null \"unset\" 1.1\n") +
+ - + - ]
1270 [ + - ]: 2292 : "Send 0.2 BTC with a fee rate of 1 " + CURRENCY_ATOM + "/vB using the options argument\n"
1271 [ + - + - : 5730 : + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.2}' null \"unset\" null '{\"fee_rate\": 1}'\n") +
+ - + - ]
1272 [ + - ]: 2292 : "Send 0.3 BTC with a fee rate of 25 " + CURRENCY_ATOM + "/vB using named arguments\n"
1273 [ + - + - : 5730 : + HelpExampleCli("-named send", "outputs='{\"" + EXAMPLE_ADDRESS[0] + "\": 0.3}' fee_rate=25\n") +
+ - + - ]
1274 : 1146 : "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"
1275 [ + - + - : 5730 : + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.1}' 1 economical null '{\"add_to_wallet\": false, \"inputs\": [{\"txid\":\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\", \"vout\":1}]}'")
+ - + - ]
1276 [ + - ]: 1146 : },
1277 : 1146 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1278 : : {
1279 : 237 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
1280 [ - + ]: 237 : if (!pwallet) return UniValue::VNULL;
1281 : :
1282 [ + - + + : 237 : UniValue options{request.params[4].isNull() ? UniValue::VOBJ : request.params[4]};
+ - + - ]
1283 [ + - + - : 237 : InterpretFeeEstimationInstructions(/*conf_target=*/request.params[1], /*estimate_mode=*/request.params[2], /*fee_rate=*/request.params[3], options);
+ - + + ]
1284 [ + + ]: 233 : PreventOutdatedOptions(options);
1285 : :
1286 : :
1287 [ + - - + : 464 : bool rbf{options.exists("replaceable") ? options["replaceable"].get_bool() : pwallet->m_signal_rbf};
- - - - -
- ]
1288 : 232 : UniValue outputs(UniValue::VOBJ);
1289 [ + - + - ]: 232 : outputs = NormalizeOutputs(request.params[0]);
1290 : 232 : std::vector<CRecipient> recipients = CreateRecipients(
1291 [ + + ]: 463 : ParseOutputs(outputs),
1292 [ + - + - : 465 : InterpretSubtractFeeFromOutputInstructions(&options["subtract_fee_from_outputs"], outputs.getKeys())
+ - + - ]
1293 [ + - ]: 231 : );
1294 [ + - ]: 231 : CCoinControl coin_control;
1295 [ + - ]: 231 : coin_control.m_version = self.Arg<uint32_t>("version");
1296 [ + - + - : 462 : CMutableTransaction rawTx = ConstructTransaction(options["inputs"], request.params[0], options["locktime"], rbf, coin_control.m_version);
+ - + - +
- + - ]
1297 : : // Automatically select coins, unless at least one is manually selected. Can
1298 : : // be overridden by options.add_inputs.
1299 [ - + ]: 231 : coin_control.m_allow_other_inputs = rawTx.vin.size() == 0;
1300 [ + - - + ]: 462 : if (options.exists("max_tx_weight")) {
1301 [ # # # # : 0 : coin_control.m_max_tx_weight = options["max_tx_weight"].getInt<int>();
# # ]
1302 : : }
1303 : :
1304 [ + - + - : 232 : SetOptionsInputWeights(options["inputs"], options);
+ + ]
1305 : : // Clear tx.vout since it is not meant to be used now that we are passing outputs directly.
1306 : : // This sets us up for a future PR to completely remove tx from the function signature in favor of passing inputs directly
1307 : 230 : rawTx.vout.clear();
1308 [ + + ]: 230 : auto txr = FundTransaction(*pwallet, rawTx, recipients, options, coin_control, /*override_min_fee=*/false);
1309 : :
1310 [ + - ]: 147 : CMutableTransaction tx = CMutableTransaction(*txr.tx);
1311 [ + - + + ]: 441 : return FinishTransaction(pwallet, options, tx);
1312 [ + - ]: 933 : }
1313 [ + - + - : 11460 : };
+ + - - ]
1314 [ + - + - : 69906 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - - - -
- - - ]
1315 : :
1316 : 1129 : RPCMethod sendall()
1317 : : {
1318 : 1129 : return RPCMethod{"sendall",
1319 [ + - ]: 2258 : "Spend the value of all (or specific) confirmed UTXOs and unconfirmed change in the wallet to one or more recipients.\n"
1320 : : "Unconfirmed inbound UTXOs and locked UTXOs will not be spent. Sendall will respect the avoid_reuse wallet flag.\n"
1321 : : "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",
1322 : : {
1323 [ + - + - ]: 2258 : {"recipients", RPCArg::Type::ARR, RPCArg::Optional::NO, "The sendall destinations. Each address may only appear once.\n"
1324 : : "Optionally some recipients can be specified with an amount to perform payments, but at least one address must appear without a specified amount.\n",
1325 : : {
1326 [ + - + - ]: 2258 : {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "A bitcoin address which receives an equal share of the unspecified amount."},
1327 [ + - + - ]: 2258 : {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
1328 : : {
1329 [ + - + - ]: 2258 : {"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 + ""},
1330 : : },
1331 : : },
1332 : : },
1333 : : },
1334 [ + - + - : 3387 : {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
+ - ]
1335 [ + - + - ]: 2258 : {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
1336 [ + - + - : 2258 : + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
+ - ]
1337 [ + - + - : 3387 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
+ - ]
1338 : : {
1339 [ + - + - ]: 2258 : "options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
1340 [ + - + - : 23709 : Cat<std::vector<RPCArg>>(
+ - + - +
+ + + + +
- - - - -
- ]
1341 : : {
1342 [ + - + - : 3387 : {"add_to_wallet", RPCArg::Type::BOOL, RPCArg::Default{true}, "When false, returns the serialized transaction without broadcasting or adding it to the wallet"},
+ - ]
1343 [ + - + - : 4516 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB.", RPCArgOptions{.also_positional = true}},
+ - + - ]
1344 [ + - + - : 3387 : {"include_watching", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
+ - ]
1345 [ + - + - ]: 2258 : {"inputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Use exactly the specified inputs to build the transaction. Specifying inputs is incompatible with the send_max, minconf, and maxconf options.",
1346 : : {
1347 [ + - + - ]: 2258 : {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
1348 : : {
1349 [ + - + - ]: 2258 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1350 [ + - + - ]: 2258 : {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1351 [ + - + - : 3387 : {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
+ - ]
1352 : : },
1353 : : },
1354 : : },
1355 : : },
1356 [ + - + - : 3387 : {"locktime", RPCArg::Type::NUM, RPCArg::DefaultHint{"locktime close to block height to prevent fee sniping"}, "Raw locktime. Non-0 value also locktime-activates inputs"},
+ - ]
1357 [ + - + - : 3387 : {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
+ - ]
1358 [ + - + - : 3387 : {"psbt", RPCArg::Type::BOOL, RPCArg::DefaultHint{"automatic"}, "Always return a PSBT, implies add_to_wallet=false."},
+ - ]
1359 [ + - + - : 3387 : {"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."},
+ - ]
1360 [ + - + - : 3387 : {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "Require inputs with at least this many confirmations."},
+ - ]
1361 [ + - + - ]: 2258 : {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Require inputs with at most this many confirmations."},
1362 [ + - + - : 3387 : {"version", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_WALLET_TX_VERSION}, "Transaction version"},
+ - ]
1363 : : },
1364 [ + - ]: 2258 : FundTxDoc()
1365 : : ),
1366 [ + - ]: 2258 : RPCArgOptions{.oneline_description="options"}
1367 : : },
1368 : : },
1369 [ + - ]: 2258 : RPCResult{
1370 [ + - + - ]: 2258 : RPCResult::Type::OBJ, "", "",
1371 : : {
1372 [ + - + - ]: 2258 : {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1373 [ + - + - ]: 2258 : {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id for the send. Only 1 transaction is created regardless of the number of addresses."},
1374 [ + - + - ]: 2258 : {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
1375 [ + - + - ]: 2258 : {RPCResult::Type::STR, "psbt", /*optional=*/true, "If more signatures are needed, or if add_to_wallet is false, the base64-encoded (partially) signed transaction"}
1376 : : }
1377 [ + - + - : 11290 : },
+ + - - ]
1378 : 1129 : RPCExamples{""
1379 [ + - ]: 2258 : "\nSpend all UTXOs from the wallet with a fee rate of 1Â " + CURRENCY_ATOM + "/vB using named arguments\n"
1380 [ + - + - : 5645 : + HelpExampleCli("-named sendall", "recipients='[\"" + EXAMPLE_ADDRESS[0] + "\"]' fee_rate=1\n") +
+ - + - ]
1381 [ + - ]: 2258 : "Spend all UTXOs with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB using positional arguments\n"
1382 [ + - + - : 5645 : + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\"]' null \"unset\" 1.1\n") +
+ - + - ]
1383 [ + - ]: 2258 : "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"
1384 [ + - + - : 6774 : + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\", \"" + EXAMPLE_ADDRESS[1] + "\"]' null \"unset\" null '{\"fee_rate\": 1.5}'\n") +
+ - + - +
- ]
1385 [ + - ]: 2258 : "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"
1386 [ + - + - : 5645 : + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\"]' null \"unset\" null '{\"fee_rate\": 10, \"send_max\": true}'\n") +
+ - + - ]
1387 [ + - + - ]: 3387 : "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"
1388 [ + - + - : 6774 : + HelpExampleCli("-named sendall", "recipients='[{\"" + EXAMPLE_ADDRESS[1] + "\": 0.25}, \""+ EXAMPLE_ADDRESS[0] + "\"]' fee_rate=1.3\n")
+ - + - +
- ]
1389 [ + - ]: 1129 : },
1390 : 1129 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1391 : : {
1392 : 220 : std::shared_ptr<CWallet> const pwallet{GetWalletForJSONRPCRequest(request)};
1393 [ - + ]: 220 : if (!pwallet) return UniValue::VNULL;
1394 : : // Make sure the results are valid at least up to the most recent block
1395 : : // the user could have gotten from another RPC command prior to now
1396 [ + - ]: 220 : pwallet->BlockUntilSyncedToCurrentChain();
1397 : :
1398 [ + - + + : 220 : UniValue options{request.params[4].isNull() ? UniValue::VOBJ : request.params[4]};
+ - + - ]
1399 [ + + + + : 3742 : RPCTypeCheckObj(options,
+ + ]
1400 : : {
1401 [ + - ]: 220 : {"add_to_wallet", UniValueType(UniValue::VBOOL)},
1402 [ + - ]: 220 : {"fee_rate", UniValueType()},
1403 [ + - ]: 220 : {"include_watching", UniValueType(UniValue::VBOOL)},
1404 [ + - ]: 220 : {"inputs", UniValueType(UniValue::VARR)},
1405 [ + - ]: 220 : {"locktime", UniValueType(UniValue::VNUM)},
1406 [ + - ]: 220 : {"lock_unspents", UniValueType(UniValue::VBOOL)},
1407 [ + - ]: 220 : {"psbt", UniValueType(UniValue::VBOOL)},
1408 [ + - ]: 220 : {"send_max", UniValueType(UniValue::VBOOL)},
1409 [ + - ]: 220 : {"minconf", UniValueType(UniValue::VNUM)},
1410 [ + - ]: 220 : {"maxconf", UniValueType(UniValue::VNUM)},
1411 [ + - ]: 220 : {"version", UniValueType(UniValue::VNUM)},
1412 [ + - ]: 220 : {"conf_target", UniValueType(UniValue::VNUM)},
1413 [ + - ]: 220 : {"estimate_mode", UniValueType(UniValue::VSTR)},
1414 [ + - ]: 220 : {"replaceable", UniValueType(UniValue::VBOOL)},
1415 [ + - ]: 220 : {"solving_data", UniValueType(UniValue::VOBJ)},
1416 : : },
1417 : : /*fAllowNull=*/true, /*fStrict=*/true);
1418 [ + - + - : 218 : InterpretFeeEstimationInstructions(/*conf_target=*/request.params[1], /*estimate_mode=*/request.params[2], /*fee_rate=*/request.params[3], options);
+ - + - ]
1419 : :
1420 : :
1421 : 218 : std::set<CTxDestination> addresses_without_amount;
1422 : 218 : UniValue recipient_key_value_pairs(UniValue::VARR);
1423 [ + - ]: 218 : const UniValue& recipients{request.params[0]};
1424 [ - + + + ]: 1145 : for (unsigned int i = 0; i < recipients.size(); ++i) {
1425 [ + - ]: 927 : const UniValue& recipient{recipients[i]};
1426 [ + + ]: 927 : if (recipient.isStr()) {
1427 : 918 : UniValue rkvp(UniValue::VOBJ);
1428 [ + - + - : 2754 : rkvp.pushKV(recipient.get_str(), 0);
- + + - ]
1429 [ + - ]: 918 : recipient_key_value_pairs.push_back(std::move(rkvp));
1430 : : // Store the decoded destination, so it matches the outputs below
1431 : : // also when the address was given in another case (e.g. uppercase bech32)
1432 [ + - + - : 918 : addresses_without_amount.insert(DecodeDestination(recipient.get_str()));
+ - ]
1433 : 918 : } else {
1434 [ + - + - ]: 9 : recipient_key_value_pairs.push_back(recipient);
1435 : : }
1436 : : }
1437 : :
1438 [ + + ]: 218 : if (addresses_without_amount.size() == 0) {
1439 [ + - + - ]: 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Must provide at least one address without a specified amount");
1440 : : }
1441 : :
1442 [ + - ]: 216 : CCoinControl coin_control;
1443 : :
1444 [ + - + - : 432 : SetFeeEstimateMode(*pwallet, coin_control, options["conf_target"], options["estimate_mode"], options["fee_rate"], /*override_min_fee=*/false);
+ - + - +
- + - +
- ]
1445 : :
1446 [ + - + + ]: 432 : if (options.exists("minconf")) {
1447 [ + - + - : 7 : if (options["minconf"].getInt<int>() < 0)
+ - + + ]
1448 : : {
1449 [ + - + - : 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid minconf (minconf cannot be negative): %s", options["minconf"].getInt<int>()));
+ - + - +
- ]
1450 : : }
1451 : :
1452 [ + - + - : 6 : coin_control.m_min_depth = options["minconf"].getInt<int>();
+ - ]
1453 : : }
1454 : :
1455 [ + - + + ]: 430 : if (options.exists("maxconf")) {
1456 [ + - + - : 2 : coin_control.m_max_depth = options["maxconf"].getInt<int>();
+ - ]
1457 : :
1458 [ - + ]: 2 : if (coin_control.m_max_depth < coin_control.m_min_depth) {
1459 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("maxconf can't be lower than minconf: %d < %d", coin_control.m_max_depth, coin_control.m_min_depth));
1460 : : }
1461 : : }
1462 : :
1463 [ + - + + ]: 430 : if (options.exists("version")) {
1464 [ + - + - : 9 : coin_control.m_version = options["version"].getInt<decltype(coin_control.m_version)>();
+ - ]
1465 : : }
1466 : :
1467 [ + + ]: 215 : if (coin_control.m_version == TRUC_VERSION) {
1468 [ - + ]: 7 : coin_control.m_max_tx_weight = TRUC_MAX_WEIGHT;
1469 : : } else {
1470 : 208 : coin_control.m_max_tx_weight = MAX_STANDARD_TX_WEIGHT;
1471 : : }
1472 : :
1473 [ + - + + : 430 : const bool rbf{options.exists("replaceable") ? options["replaceable"].get_bool() : pwallet->m_signal_rbf};
+ - + - +
- ]
1474 : :
1475 [ + - ]: 215 : auto [fee_rate, fee_reason, returned_target] = GetMinimumFeeRate(*pwallet, coin_control);
1476 : : // Do not, ever, assume that it's fine to change the fee rate if the user has explicitly
1477 : : // provided one
1478 [ + + + + ]: 215 : if (coin_control.m_feerate && fee_rate > *coin_control.m_feerate) {
1479 : 1 : const auto feerate_format = FeeRateFormat::SAT_VB;
1480 : 1 : auto msg{strprintf("Fee rate (%s) is lower than the minimum fee rate setting (%s).",
1481 [ + - ]: 2 : coin_control.m_feerate->ToString(feerate_format),
1482 [ + - + - ]: 2 : fee_rate.ToString(feerate_format))};
1483 [ + - ]: 1 : if (fee_reason == FeeReason::REQUIRED) {
1484 [ + - ]: 3 : msg += strprintf("\nConsider modifying -mintxfee (%s) or -minrelaytxfee (%s).",
1485 [ + - ]: 2 : pwallet->m_min_fee.ToString(feerate_format),
1486 [ + - + - ]: 3 : pwallet->chain().relayMinFee().ToString(feerate_format));
1487 : : }
1488 [ + - ]: 1 : throw JSONRPCError(RPC_INVALID_PARAMETER, msg);
1489 : 1 : }
1490 [ + + + - ]: 214 : if (fee_reason == FeeReason::FALLBACK && !pwallet->m_allow_fallback_fee) {
1491 : : // eventually allow a fallback fee
1492 [ # # # # ]: 0 : throw JSONRPCError(RPC_WALLET_ERROR, "Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -fallbackfee.");
1493 : : }
1494 : :
1495 [ + - + - : 429 : CMutableTransaction rawTx{ConstructTransaction(options["inputs"], recipient_key_value_pairs, options["locktime"], rbf, coin_control.m_version)};
+ - + - +
+ ]
1496 [ + - ]: 213 : LOCK(pwallet->cs_wallet);
1497 : :
1498 : 213 : CAmount total_input_value(0);
1499 [ + - + + : 428 : bool send_max{options.exists("send_max") ? options["send_max"].get_bool() : false};
+ - + - +
- ]
1500 [ + - + - : 456 : if (options.exists("inputs") && options.exists("send_max")) {
+ + + - +
- + + + +
- - ]
1501 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot combine send_max with specific inputs.");
1502 [ + - + - : 481 : } else if (options.exists("inputs") && (options.exists("minconf") || options.exists("maxconf"))) {
+ + + - +
- + + + -
+ - - + +
+ + + - -
- - ]
1503 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot combine minconf or maxconf with specific inputs.");
1504 [ + - + + ]: 422 : } else if (options.exists("inputs")) {
1505 [ + - ]: 28 : std::unordered_set<COutPoint, SaltedOutpointHasher> seen_inputs;
1506 [ - + + - ]: 28 : seen_inputs.reserve(rawTx.vin.size());
1507 [ + + ]: 53 : for (const CTxIn& input : rawTx.vin) {
1508 [ + - + + ]: 30 : if (!seen_inputs.insert(input.prevout).second) {
1509 [ + - + - : 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated input: %s:%d", input.prevout.hash.ToString(), input.prevout.n));
+ - ]
1510 : : }
1511 [ + - + + ]: 29 : if (pwallet->IsSpent(input.prevout)) {
1512 [ + - + - : 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input not available. UTXO (%s:%d) was already spent.", input.prevout.hash.ToString(), input.prevout.n));
+ - ]
1513 : : }
1514 [ + - ]: 27 : const CWalletTx* tx{pwallet->GetWalletTx(input.prevout.hash)};
1515 [ + + + - : 78 : if (!tx || input.prevout.n >= tx->GetTx()->vout.size() || !pwallet->IsMine(tx->GetTx()->vout[input.prevout.n])) {
- + + + +
- + - + -
+ + + + -
- - - ]
1516 [ + - + - : 4 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input not found. UTXO (%s:%d) is not part of wallet.", input.prevout.hash.ToString(), input.prevout.n));
+ - ]
1517 : : }
1518 [ + - + + ]: 25 : if (pwallet->GetTxDepthInMainChain(*tx) == 0) {
1519 [ + - - + : 32 : if (tx->GetTx()->version == TRUC_VERSION && coin_control.m_version != TRUC_VERSION) {
- - - + ]
1520 [ # # # # ]: 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Can't spend unconfirmed version 3 pre-selected input with a version %d tx", coin_control.m_version));
1521 [ - + - - : 16 : } else if (coin_control.m_version == TRUC_VERSION && tx->GetTx()->version != TRUC_VERSION) {
- - - + ]
1522 [ # # # # : 0 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Can't spend unconfirmed version %d pre-selected input with a version 3 tx", tx->GetTx()->version));
# # # # ]
1523 : : }
1524 : : }
1525 [ + - + - ]: 50 : total_input_value += tx->GetTx()->vout[input.prevout.n].nValue;
1526 : : }
1527 : 28 : } else {
1528 : 183 : CoinFilterParams coins_params;
1529 : 183 : coins_params.min_amount = 0;
1530 [ + - + - : 3024 : for (const COutput& output : AvailableCoins(*pwallet, &coin_control, fee_rate, coins_params).All()) {
+ + ]
1531 [ + + + - : 2841 : if (send_max && fee_rate.GetFee(output.input_bytes) > output.txout.nValue) {
+ + ]
1532 : 2 : continue;
1533 : : }
1534 : : // we are spending an unconfirmed TRUC transaction, so lower max weight
1535 [ + + + + ]: 2839 : if (output.depth == 0 && coin_control.m_version == TRUC_VERSION) {
1536 [ + - ]: 4 : coin_control.m_max_tx_weight = TRUC_CHILD_MAX_WEIGHT;
1537 : : }
1538 [ + + + - ]: 2842 : CTxIn input(output.outpoint.hash, output.outpoint.n, CScript(), rbf ? MAX_BIP125_RBF_SEQUENCE : CTxIn::MAX_SEQUENCE_NONFINAL);
1539 [ + - ]: 2839 : rawTx.vin.push_back(input);
1540 : 2839 : total_input_value += output.txout.nValue;
1541 : 3022 : }
1542 : : }
1543 : :
1544 : 206 : std::vector<COutPoint> outpoints_spent;
1545 [ - + + - ]: 206 : outpoints_spent.reserve(rawTx.vin.size());
1546 : :
1547 [ + + ]: 3069 : for (const CTxIn& tx_in : rawTx.vin) {
1548 [ + - ]: 2863 : outpoints_spent.push_back(tx_in.prevout);
1549 : : }
1550 : :
1551 : : // estimate final size of tx
1552 [ + - + - ]: 206 : const TxSize tx_size{CalculateMaximumSignedTxSize(CTransaction(rawTx), pwallet.get())};
1553 [ + + ]: 206 : if (tx_size.vsize == -1) {
1554 [ + - + - ]: 4 : throw JSONRPCError(RPC_WALLET_ERROR, "Unable to determine the size of the transaction, the wallet contains unsolvable descriptors");
1555 : : }
1556 [ + - ]: 204 : const CAmount fee_from_size{fee_rate.GetFee(tx_size.vsize)};
1557 [ + - ]: 204 : const std::optional<CAmount> total_bump_fees{pwallet->chain().calculateCombinedBumpFee(outpoints_spent, fee_rate)};
1558 [ + - ]: 204 : const CAmount actual_fee{fee_from_size + total_bump_fees.value_or(0)};
1559 : 204 : CAmount effective_value = total_input_value - actual_fee;
1560 : :
1561 [ + + ]: 204 : if (actual_fee > pwallet->m_max_tx_fee) {
1562 [ + - + - ]: 4 : throw JSONRPCError(RPC_WALLET_ERROR, TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED).original);
1563 : : }
1564 [ + - + + ]: 202 : if (actual_fee > pwallet->m_max_tx_fee_rate.GetFee(tx_size.vsize)) {
1565 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_ERROR, TransactionErrorString(TransactionError::MAX_FEE_RATE_EXCEEDED).original);
1566 : : }
1567 : :
1568 [ + + ]: 201 : if (effective_value <= 0) {
1569 [ - + ]: 33 : if (send_max) {
1570 [ # # # # ]: 0 : throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Total value of UTXO pool too low to pay for transaction, try using lower feerate.");
1571 : : } else {
1572 [ + - + - ]: 66 : throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Total value of UTXO pool too low to pay for transaction. Try using lower feerate or excluding uneconomic UTXOs with 'send_max' option.");
1573 : : }
1574 : : }
1575 : :
1576 : : // If this transaction is too large, e.g. because the wallet has many UTXOs, it will be rejected by the node's mempool.
1577 [ + - ]: 168 : if (tx_size.weight > coin_control.m_max_tx_weight) {
1578 [ + - + - ]: 6 : throw JSONRPCError(RPC_WALLET_ERROR, "Transaction too large.");
1579 : : }
1580 : :
1581 : 165 : CAmount output_amounts_claimed{0};
1582 [ + + ]: 691 : for (const CTxOut& out : rawTx.vout) {
1583 : 526 : output_amounts_claimed += out.nValue;
1584 : : }
1585 : :
1586 [ + + ]: 165 : if (output_amounts_claimed > total_input_value) {
1587 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Assigned more value to outputs than available funds.");
1588 : : }
1589 : :
1590 : 164 : const CAmount remainder{effective_value - output_amounts_claimed};
1591 [ + + ]: 164 : if (remainder < 0) {
1592 [ + - + - ]: 2 : throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds for fees after creating specified outputs.");
1593 : : }
1594 : :
1595 : 163 : const CAmount per_output_without_amount{remainder / (long)addresses_without_amount.size()};
1596 : :
1597 : 163 : bool gave_remaining_to_first{false};
1598 [ + + ]: 681 : for (CTxOut& out : rawTx.vout) {
1599 : 521 : CTxDestination dest;
1600 [ + - ]: 521 : ExtractDestination(out.scriptPubKey, dest);
1601 [ + + ]: 521 : if (addresses_without_amount.contains(dest)) {
1602 : 515 : out.nValue = per_output_without_amount;
1603 [ + + ]: 515 : if (!gave_remaining_to_first) {
1604 : 162 : out.nValue += remainder % addresses_without_amount.size();
1605 : 162 : gave_remaining_to_first = true;
1606 : : }
1607 [ + - + - : 515 : if (IsDust(out, pwallet->chain().relayDustFee())) {
+ + ]
1608 : : // Dynamically generated output amount is dust
1609 [ + - + - ]: 4 : throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Dynamically assigned remainder results in dust output.");
1610 : : }
1611 : : } else {
1612 [ + - + - : 6 : if (IsDust(out, pwallet->chain().relayDustFee())) {
+ + ]
1613 : : // Specified output amount is dust
1614 [ + - + - : 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Specified output amount to %s is below dust threshold.", EncodeDestination(dest)));
+ - ]
1615 : : }
1616 : : }
1617 : 521 : }
1618 : :
1619 [ + - + + : 322 : const bool lock_unspents{options.exists("lock_unspents") ? options["lock_unspents"].get_bool() : false};
+ - + - +
- ]
1620 [ + + ]: 160 : if (lock_unspents) {
1621 [ + + ]: 4 : for (const CTxIn& txin : rawTx.vin) {
1622 [ + - ]: 2 : pwallet->LockCoin(txin.prevout, /*persist=*/false);
1623 : : }
1624 : : }
1625 : :
1626 [ + - + - ]: 480 : return FinishTransaction(pwallet, options, rawTx);
1627 [ + - + - : 1135 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- + ]
1628 [ + - + - : 18064 : };
+ - + - +
+ + + + +
- - - - -
- ]
1629 [ + - + - : 58708 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
- - - - -
- - - -
- ]
1630 : :
1631 : 1550 : RPCMethod walletprocesspsbt()
1632 : : {
1633 : 1550 : return RPCMethod{
1634 : 1550 : "walletprocesspsbt",
1635 : : "Update a PSBT with input information from our wallet and then sign inputs\n"
1636 : 1550 : "that we can sign for." +
1637 [ + - ]: 1550 : HELP_REQUIRING_PASSPHRASE,
1638 : : {
1639 [ + - + - ]: 3100 : {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction base64 string"},
1640 [ + - + - : 4650 : {"sign", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also sign the transaction when updating (requires wallet to be unlocked)"},
+ - ]
1641 [ + - + - : 4650 : {"sighashtype", RPCArg::Type::STR, RPCArg::DefaultHint{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type to sign with if not specified by the PSBT. Must be one of\n"
+ - ]
1642 : : " \"DEFAULT\"\n"
1643 : : " \"ALL\"\n"
1644 : : " \"NONE\"\n"
1645 : : " \"SINGLE\"\n"
1646 : : " \"ALL|ANYONECANPAY\"\n"
1647 : : " \"NONE|ANYONECANPAY\"\n"
1648 : : " \"SINGLE|ANYONECANPAY\""},
1649 [ + - + - : 4650 : {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"},
+ - ]
1650 [ + - + - : 4650 : {"finalize", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also finalize inputs if possible"},
+ - ]
1651 : : },
1652 [ + - ]: 3100 : RPCResult{
1653 [ + - + - ]: 3100 : RPCResult::Type::OBJ, "", "",
1654 : : {
1655 [ + - + - ]: 3100 : {RPCResult::Type::STR, "psbt", "The base64-encoded partially signed transaction"},
1656 [ + - + - ]: 3100 : {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1657 [ + - + - ]: 3100 : {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The hex-encoded network transaction if complete"},
1658 : : }
1659 [ + - + - : 12400 : },
+ + - - ]
1660 : 1550 : RPCExamples{
1661 [ + - + - : 3100 : HelpExampleCli("walletprocesspsbt", "\"psbt\"")
+ - ]
1662 [ + - ]: 1550 : },
1663 : 1550 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1664 : : {
1665 [ - + ]: 641 : const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request);
1666 [ - + ]: 641 : if (!pwallet) return UniValue::VNULL;
1667 : :
1668 [ + - ]: 641 : const CWallet& wallet{*pwallet};
1669 : : // Make sure the results are valid at least up to the most recent block
1670 : : // the user could have gotten from another RPC command prior to now
1671 [ + - ]: 641 : wallet.BlockUntilSyncedToCurrentChain();
1672 : :
1673 : : // Unserialize the transaction
1674 [ + - + - : 641 : util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(request.params[0].get_str());
+ - ]
1675 [ + + ]: 641 : if (!psbt_res) {
1676 [ + - + - : 6 : throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));
+ - ]
1677 : : }
1678 [ + - ]: 639 : PartiallySignedTransaction psbtx = *psbt_res;
1679 : :
1680 : : // Get the sighash type
1681 [ + - + + ]: 639 : std::optional<int> nHashType = ParseSighashString(request.params[2]);
1682 : :
1683 : : // Fill transaction with our data and also sign
1684 [ + - ]: 638 : const bool sign{self.Arg<bool>("sign")};
1685 [ + - ]: 638 : const bool bip32derivs{self.Arg<bool>("bip32derivs")};
1686 [ + - ]: 638 : const bool finalize{self.Arg<bool>("finalize")};
1687 : 638 : bool complete = true;
1688 : :
1689 [ + + + + ]: 638 : if (sign) EnsureWalletIsUnlocked(*pwallet);
1690 : :
1691 [ + - ]: 637 : const auto err{wallet.FillPSBT(psbtx, {.sign = sign, .sighash_type = nHashType, .finalize = finalize, .bip32_derivs = bip32derivs}, complete)};
1692 [ + + ]: 637 : if (err) {
1693 [ + - ]: 7 : throw JSONRPCPSBTError(*err);
1694 : : }
1695 : :
1696 : 630 : UniValue result(UniValue::VOBJ);
1697 : 630 : DataStream ssTx{};
1698 [ + - ]: 630 : ssTx << psbtx;
1699 [ + - + - : 1890 : result.pushKV("psbt", EncodeBase64(ssTx.str()));
+ - + - +
- ]
1700 [ + - + - : 1260 : result.pushKV("complete", complete);
+ - ]
1701 [ + + ]: 630 : if (complete) {
1702 [ + - ]: 42 : CMutableTransaction mtx;
1703 : : // Returns true if complete, which we already think it is.
1704 [ + - + - ]: 42 : CHECK_NONFATAL(FinalizeAndExtractPSBT(psbtx, mtx));
1705 : 42 : DataStream ssTx_final;
1706 [ + - ]: 42 : ssTx_final << TX_WITH_WITNESS(mtx);
1707 [ - + + - : 84 : result.pushKV("hex", HexStr(ssTx_final));
+ - + - +
- ]
1708 : 84 : }
1709 : :
1710 : 630 : return result;
1711 : 1280 : },
1712 [ + - + - : 13950 : };
+ + - - ]
1713 [ + - + - : 24800 : }
+ - + - +
- + - + -
+ - - - -
- ]
1714 : :
1715 : 1145 : RPCMethod walletcreatefundedpsbt()
1716 : : {
1717 : 1145 : return RPCMethod{
1718 : 1145 : "walletcreatefundedpsbt",
1719 [ + - ]: 2290 : "Creates and funds a transaction in the Partially Signed Transaction format.\n"
1720 : : "Implements the Creator and Updater roles.\n"
1721 : : "All existing inputs must either have their previous output transaction be in the wallet\n"
1722 : : "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n",
1723 : : {
1724 [ + - + - ]: 2290 : {"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Leave empty to add inputs automatically. See add_inputs option.",
1725 : : {
1726 [ + - + - ]: 2290 : {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
1727 : : {
1728 [ + - + - ]: 2290 : {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1729 [ + - + - ]: 2290 : {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1730 [ + - + - : 3435 : {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'locktime' and 'options.replaceable' arguments"}, "The sequence number"},
+ - ]
1731 [ + - + - : 3435 : {"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, "
+ - ]
1732 : : "including the weight of the outpoint and sequence number. "
1733 : : "Note that signature sizes are not guaranteed to be consistent, "
1734 : : "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
1735 : : "Remember to convert serialized sizes to weight units when necessary."},
1736 : : },
1737 : : },
1738 : : },
1739 : : },
1740 [ + - + - ]: 2290 : {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n"
1741 : : "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"
1742 : : "At least one output of either type must be specified.\n"
1743 : : "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
1744 : : "accepted as second parameter.",
1745 [ + - ]: 2290 : OutputsDoc(),
1746 [ + - ]: 2290 : RPCArgOptions{.skip_type_check = true}},
1747 [ + - + - : 3435 : {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
+ - ]
1748 [ + - + - ]: 2290 : {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
1749 [ + - + - : 20610 : Cat<std::vector<RPCArg>>(
+ - + + +
+ - - -
- ]
1750 : : {
1751 [ + - + - : 3435 : {"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"},
+ - ]
1752 [ + - + - : 3435 : {"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"
+ - ]
1753 : : "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
1754 : : "If that happens, you will need to fund the transaction with different inputs and republish it."},
1755 [ + - + - : 3435 : {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."},
+ - ]
1756 [ + - + - ]: 2290 : {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."},
1757 [ + - + - : 3435 : {"change_address|changeAddress", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
+ - ]
1758 [ + - + - : 3435 : {"change_position|changePosition", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
+ - ]
1759 [ + - + - : 3435 : {"change_type", RPCArg::Type::STR, RPCArg::DefaultHint{"set by -changetype"}, "The output type to use. Only valid if changeAddress is not specified. Options are " + FormatAllOutputTypes() + "."},
+ - + - ]
1760 [ + - + - : 3435 : {"includeWatching", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
+ - ]
1761 [ + - + - : 3435 : {"lock_unspents|lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
+ - ]
1762 [ + - + - : 3435 : {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
+ - ]
1763 [ + - + - : 3435 : {"feeRate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_UNIT + "/kvB."},
+ - ]
1764 [ + - + - ]: 2290 : {"subtract_fee_from_outputs|subtractFeeFromOutputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The outputs to subtract the fee from.\n"
1765 : : "The fee will be equally deducted from the amount of each specified output.\n"
1766 : : "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
1767 : : "If no outputs are specified here, the sender pays the fee.",
1768 : : {
1769 [ + - + - ]: 2290 : {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
1770 : : },
1771 : : },
1772 [ + - + - : 3435 : {"max_tx_weight", RPCArg::Type::NUM, RPCArg::Default{MAX_STANDARD_TX_WEIGHT}, "The maximum acceptable transaction weight.\n"
+ - ]
1773 : : "Transaction building will fail if this can not be satisfied."},
1774 : : },
1775 [ + - ]: 2290 : FundTxDoc()),
1776 [ + - ]: 2290 : RPCArgOptions{.oneline_description="options"}},
1777 [ + - + - : 3435 : {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"},
+ - ]
1778 [ + - + - : 3435 : {"version", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_WALLET_TX_VERSION}, "Transaction version"},
+ - ]
1779 [ + - + - : 3435 : {"psbt_version", RPCArg::Type::NUM, RPCArg::Default(2), "The PSBT version number to use."},
+ - ]
1780 : : },
1781 [ + - ]: 2290 : RPCResult{
1782 [ + - + - ]: 2290 : RPCResult::Type::OBJ, "", "",
1783 : : {
1784 [ + - + - ]: 2290 : {RPCResult::Type::STR, "psbt", "The resulting raw transaction (base64-encoded string)"},
1785 [ + - + - ]: 2290 : {RPCResult::Type::STR_AMOUNT, "fee", "Fee in " + CURRENCY_UNIT + " the resulting transaction pays"},
1786 [ + - + - ]: 2290 : {RPCResult::Type::NUM, "changepos", "The position of the added change output, or -1"},
1787 : : }
1788 [ + - + - : 9160 : },
+ + - - ]
1789 : 1145 : RPCExamples{
1790 : : "\nCreate a PSBT with automatically picked inputs that sends 0.5 BTC to an address and has a fee rate of 2 sat/vB:\n"
1791 [ + - + - : 3435 : + HelpExampleCli("walletcreatefundedpsbt", "\"[]\" \"[{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.5}]\" 0 \"{\\\"add_inputs\\\":true,\\\"fee_rate\\\":2}\"")
+ - + - ]
1792 : 1145 : + "\nCreate the same PSBT as the above one instead using named arguments:\n"
1793 [ + - + - : 5725 : + HelpExampleCli("-named walletcreatefundedpsbt", "outputs=\"[{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.5}]\" add_inputs=true fee_rate=2")
+ - + - ]
1794 [ + - ]: 1145 : },
1795 : 1145 : [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1796 : : {
1797 : 236 : std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
1798 [ - + ]: 236 : if (!pwallet) return UniValue::VNULL;
1799 : :
1800 [ + - ]: 236 : CWallet& wallet{*pwallet};
1801 : : // Make sure the results are valid at least up to the most recent block
1802 : : // the user could have gotten from another RPC command prior to now
1803 [ + - ]: 236 : wallet.BlockUntilSyncedToCurrentChain();
1804 : :
1805 [ + - + + : 236 : UniValue options{request.params[3].isNull() ? UniValue::VOBJ : request.params[3]};
+ - + - ]
1806 : :
1807 [ + - ]: 236 : CCoinControl coin_control;
1808 [ + - ]: 236 : coin_control.m_version = self.Arg<uint32_t>("version");
1809 : :
1810 [ + - + - ]: 236 : const UniValue &replaceable_arg = options["replaceable"];
1811 [ + + + - ]: 236 : const bool rbf{replaceable_arg.isNull() ? wallet.m_signal_rbf : replaceable_arg.get_bool()};
1812 [ + - + - : 236 : CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf, coin_control.m_version);
+ - + - ]
1813 : 236 : UniValue outputs(UniValue::VOBJ);
1814 [ + - + - ]: 236 : outputs = NormalizeOutputs(request.params[1]);
1815 : 236 : std::vector<CRecipient> recipients = CreateRecipients(
1816 [ + - ]: 472 : ParseOutputs(outputs),
1817 [ + - + - : 708 : InterpretSubtractFeeFromOutputInstructions(
+ - ]
1818 [ + - + - ]: 472 : GetOptionWithAlias(options, "subtract_fee_from_outputs", "subtractFeeFromOutputs"), outputs.getKeys())
1819 [ + - ]: 236 : );
1820 : : // Automatically select coins, unless at least one is manually selected. Can
1821 : : // be overridden by options.add_inputs.
1822 [ - + ]: 236 : coin_control.m_allow_other_inputs = rawTx.vin.size() == 0;
1823 [ + - + + ]: 236 : SetOptionsInputWeights(request.params[0], options);
1824 : : // Clear tx.vout since it is not meant to be used now that we are passing outputs directly.
1825 : : // This sets us up for a future PR to completely remove tx from the function signature in favor of passing inputs directly
1826 : 235 : rawTx.vout.clear();
1827 [ + + ]: 235 : auto txr = FundTransaction(wallet, rawTx, recipients, options, coin_control, /*override_min_fee=*/true);
1828 : :
1829 : : // Make a blank psbt
1830 [ + - ]: 167 : const uint32_t psbt_version{self.Arg<uint32_t>("psbt_version")};
1831 [ + + ]: 167 : if (psbt_version != 2 && psbt_version != 0) {
1832 [ + - + - ]: 2 : throw JSONRPCError(RPC_INVALID_PARAMETER, "The PSBT version can only be 2 or 0");
1833 : : }
1834 : :
1835 [ + - + - ]: 166 : PartiallySignedTransaction psbtx(CMutableTransaction(*txr.tx), psbt_version);
1836 : :
1837 : : // Fill transaction with our data but don't sign
1838 [ + - ]: 166 : const bool bip32derivs{self.Arg<bool>("bip32derivs")};
1839 : 166 : bool complete = true;
1840 [ + - ]: 166 : const auto err{wallet.FillPSBT(psbtx, {.sign = false, .bip32_derivs = bip32derivs}, complete)};
1841 [ - + ]: 166 : if (err) {
1842 [ # # ]: 0 : throw JSONRPCPSBTError(*err);
1843 : : }
1844 : :
1845 : : // Serialize the PSBT
1846 : 166 : DataStream ssTx{};
1847 [ + - ]: 166 : ssTx << psbtx;
1848 : :
1849 : 166 : UniValue result(UniValue::VOBJ);
1850 [ + - + - : 498 : result.pushKV("psbt", EncodeBase64(ssTx.str()));
+ - + - +
- ]
1851 [ + - + - : 332 : result.pushKV("fee", ValueFromAmount(txr.fee));
+ - ]
1852 [ + + + - : 332 : result.pushKV("changepos", txr.change_pos ? (int)*txr.change_pos : -1);
+ - + - ]
1853 : 166 : return result;
1854 [ + - ]: 944 : },
1855 [ + - + - : 22900 : };
+ - + - +
+ + + + +
- - - - -
- ]
1856 [ + - + - : 64120 : }
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - -
- - - - -
- - ]
1857 : : } // namespace wallet
|