Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/wallet/rpc/spend.cpp
Line
Count
Source
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
std::vector<CRecipient> CreateRecipients(const std::vector<std::pair<CTxDestination, CAmount>>& outputs, const std::set<int>& subtract_fee_outputs)
40
2.05k
{
41
2.05k
    std::vector<CRecipient> recipients;
42
23.1k
    for (size_t i = 0; i < outputs.size(); ++i) {
43
21.1k
        const auto& [destination, amount] = outputs.at(i);
44
21.1k
        CRecipient recipient{destination, amount, subtract_fee_outputs.contains(i)};
45
21.1k
        recipients.push_back(recipient);
46
21.1k
    }
47
2.05k
    return recipients;
48
2.05k
}
49
50
static void InterpretFeeEstimationInstructions(const UniValue& conf_target, const UniValue& estimate_mode, const UniValue& fee_rate, UniValue& options)
51
455
{
52
455
    if (options.exists("conf_target") || options.exists("estimate_mode")) {
53
24
        if (!conf_target.isNull() || !estimate_mode.isNull()) {
54
3
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass conf_target and estimate_mode either as arguments or in the options object, but not both");
55
3
        }
56
431
    } else {
57
431
        options.pushKV("conf_target", conf_target);
58
431
        options.pushKV("estimate_mode", estimate_mode);
59
431
    }
60
452
    if (options.exists("fee_rate")) {
61
28
        if (!fee_rate.isNull()) {
62
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Pass the fee_rate either as an argument, or in the options object, but not both");
63
1
        }
64
424
    } else {
65
424
        options.pushKV("fee_rate", fee_rate);
66
424
    }
67
451
    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
0
    }
70
451
}
71
72
std::set<int> InterpretSubtractFeeFromOutputInstructions(const UniValue* sffo_instructions, const std::vector<std::string>& destinations)
73
772
{
74
772
    std::set<int> sffo_set;
75
772
    if (!sffo_instructions || sffo_instructions->isNull()) return sffo_set;
76
77
105
    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
9
            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
95
        } else {
86
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', invalid value type: %s", uvTypeName(sffo.type())));
87
1
        }
88
89
103
        if (sffo_set.contains(pos))
90
2
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', duplicated position: %d", pos));
91
101
        if (pos < 0)
92
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', negative position: %d", pos));
93
100
        if (pos >= int(destinations.size()))
94
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter 'subtract fee from output', position too large: %d", pos));
95
99
        sffo_set.insert(pos);
96
99
    }
97
95
    return sffo_set;
98
101
}
99
100
static UniValue FinishTransaction(const std::shared_ptr<CWallet> pwallet, const UniValue& options, CMutableTransaction& rawTx)
101
307
{
102
307
    bool can_anti_fee_snipe = !options.exists("locktime");
103
104
1.46k
    for (const CTxIn& tx_in : rawTx.vin) {
105
        // Checks sequence values consistent with DiscourageFeeSniping
106
1.46k
        can_anti_fee_snipe = can_anti_fee_snipe && (tx_in.nSequence == CTxIn::MAX_SEQUENCE_NONFINAL || tx_in.nSequence == MAX_BIP125_RBF_SEQUENCE);
107
1.46k
    }
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
301
    }
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
1
    }
126
127
306
    CMutableTransaction mtx;
128
306
    complete = FinalizeAndExtractPSBT(psbtx, mtx);
129
130
306
    UniValue result(UniValue::VOBJ);
131
132
306
    const bool psbt_opt_in{options.exists("psbt") && options["psbt"].get_bool()};
133
306
    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
60
        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
278
        result.pushKV("txid", tx->GetHash().GetHex());
145
278
        if (add_to_wallet && !psbt_opt_in) {
146
246
            pwallet->CommitTransaction(tx);
147
246
        } else {
148
32
            result.pushKV("hex", hex);
149
32
        }
150
278
    }
151
306
    result.pushKV("complete", complete);
152
153
306
    return result;
154
307
}
155
156
static void PreventOutdatedOptions(const UniValue& options)
157
233
{
158
233
    if (options.exists("feeRate")) {
159
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Use fee_rate (" + CURRENCY_ATOM + "/vB) instead of feeRate");
160
1
    }
161
232
    if (options.exists("changeAddress")) {
162
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_address instead of changeAddress");
163
0
    }
164
232
    if (options.exists("changePosition")) {
165
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Use change_position instead of changePosition");
166
0
    }
167
232
    if (options.exists("lockUnspents")) {
168
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Use lock_unspents instead of lockUnspents");
169
0
    }
170
232
    if (options.exists("subtractFeeFromOutputs")) {
171
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Use subtract_fee_from_outputs instead of subtractFeeFromOutputs");
172
0
    }
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
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
1.34k
{
182
1.34k
    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
1.34k
    if (wallet.IsWalletFlagSet(WALLET_FLAG_EXTERNAL_SIGNER)) {
188
2
        throw JSONRPCError(RPC_WALLET_ERROR, "Error: sendtoaddress and sendmany are not supported for wallets with external signers; use send instead");
189
2
    }
190
1.33k
    if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) {
191
1
        throw JSONRPCError(RPC_WALLET_ERROR, "Error: Private keys are disabled for this wallet");
192
1
    }
193
194
    // Shuffle recipient list
195
1.33k
    std::shuffle(recipients.begin(), recipients.end(), FastRandomContext());
196
197
    // Send
198
1.33k
    auto res = CreateTransaction(wallet, recipients, /*change_pos=*/std::nullopt, coin_control, true);
199
1.33k
    if (!res) {
200
19
        throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, util::ErrorString(res).original);
201
19
    }
202
1.31k
    const CTransactionRef& tx = res->tx;
203
1.31k
    wallet.CommitTransaction(tx, /*replaces_txid=*/std::nullopt, comment, comment_to);
204
1.31k
    if (verbose) {
205
8
        UniValue entry(UniValue::VOBJ);
206
8
        entry.pushKV("txid", tx->GetHash().GetHex());
207
8
        entry.pushKV("fee_reason", StringForFeeReason(res->fee_reason));
208
8
        return entry;
209
8
    }
210
1.31k
    return tx->GetHash().GetHex();
211
1.31k
}
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
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
2.29k
{
229
2.29k
    if (!fee_rate.isNull()) {
230
614
        if (!conf_target.isNull()) {
231
3
            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
3
        }
233
611
        if (!estimate_mode.isNull() && estimate_mode.get_str() != "unset") {
234
3
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and fee_rate");
235
3
        }
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
608
        if (override_min_fee) cc.fOverrideFeeRate = true;
239
        // Default RBF to true for explicit fee_rate, if unset.
240
608
        if (!cc.m_signal_bip125_rbf) cc.m_signal_bip125_rbf = true;
241
608
        return;
242
611
    }
243
1.67k
    if (!estimate_mode.isNull() && !FeeModeFromString(estimate_mode.get_str(), cc.m_fee_mode)) {
244
27
        throw JSONRPCError(RPC_INVALID_PARAMETER, InvalidEstimateModeErrorMessage());
245
27
    }
246
1.65k
    if (!conf_target.isNull()) {
247
32
        cc.m_confirm_target = ParseConfirmTarget(conf_target, wallet.chain().maximumFeeEstimationTargetBlocks());
248
32
    }
249
1.65k
}
250
251
RPCMethod sendtoaddress()
252
2.17k
{
253
2.17k
    return RPCMethod{
254
2.17k
        "sendtoaddress",
255
2.17k
        "Send an amount to a given address." +
256
2.17k
        HELP_REQUIRING_PASSPHRASE,
257
2.17k
                {
258
2.17k
                    {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address to send to."},
259
2.17k
                    {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "The amount in " + CURRENCY_UNIT + " to send. eg 0.1"},
260
2.17k
                    {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment used to store what the transaction is for.\n"
261
2.17k
                                         "This is not part of the transaction, just kept in your wallet."},
262
2.17k
                    {"comment_to", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment to store the name of the person or organization\n"
263
2.17k
                                         "to which you're sending the transaction. This is not part of the \n"
264
2.17k
                                         "transaction, just kept in your wallet."},
265
2.17k
                    {"subtractfeefromamount", RPCArg::Type::BOOL, RPCArg::Default{false}, "The fee will be deducted from the amount being sent.\n"
266
2.17k
                                         "The recipient will receive less bitcoins than you enter in the amount field."},
267
2.17k
                    {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Signal that this transaction can be replaced by a transaction (BIP 125)"},
268
2.17k
                    {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
269
2.17k
                    {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
270
2.17k
                      + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
271
2.17k
                    {"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
2.17k
                                         "dirty if they have previously been used in a transaction. If true, this also activates avoidpartialspends, grouping outputs by their addresses."},
273
2.17k
                    {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
274
2.17k
                    {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, return extra information about the transaction."},
275
2.17k
                },
276
2.17k
                {
277
2.17k
                    RPCResult{"if verbose is not set or set to false",
278
2.17k
                        RPCResult::Type::STR_HEX, "txid", "The transaction id."
279
2.17k
                    },
280
2.17k
                    RPCResult{"if verbose is set to true",
281
2.17k
                        RPCResult::Type::OBJ, "", "",
282
2.17k
                        {
283
2.17k
                            {RPCResult::Type::STR_HEX, "txid", "The transaction id."},
284
2.17k
                            {RPCResult::Type::STR, "fee_reason", "The reason the wallet selected this fee rate (\"" + FeeReasons("\", \"") + "\")."}
285
2.17k
                        },
286
2.17k
                    },
287
2.17k
                },
288
2.17k
                RPCExamples{
289
2.17k
                    "\nSend 0.1 BTC\n"
290
2.17k
                    + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1") +
291
2.17k
                    "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode using positional arguments\n"
292
2.17k
                    + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1 \"donation\" \"sean's outpost\" false true 6 economical") +
293
2.17k
                    "\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
2.17k
                    + HelpExampleCli("sendtoaddress", "\"" + EXAMPLE_ADDRESS[0] + "\" 0.1 \"drinks\" \"room77\" true true null \"unset\" null 1.1") +
295
2.17k
                    "\nSend 0.2 BTC with a confirmation target of 6 blocks in economical fee estimate mode using named arguments\n"
296
2.17k
                    + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.2 conf_target=6 estimate_mode=\"economical\"") +
297
2.17k
                    "\nSend 0.5 BTC with a fee rate of 25 " + CURRENCY_ATOM + "/vB using named arguments\n"
298
2.17k
                    + HelpExampleCli("-named sendtoaddress", "address=\"" + EXAMPLE_ADDRESS[0] + "\" amount=0.5 fee_rate=25")
299
2.17k
                    + 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
2.17k
                },
301
2.17k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
302
2.17k
{
303
1.29k
    std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request);
304
1.29k
    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
1.29k
    pwallet->BlockUntilSyncedToCurrentChain();
309
310
1.29k
    LOCK(pwallet->cs_wallet);
311
312
    // Wallet comments
313
1.29k
    std::optional<std::string> comment;
314
1.29k
    std::optional<std::string> comment_to;
315
1.29k
    if (!request.params[2].isNull() && !request.params[2].get_str().empty())
316
7
        comment = request.params[2].get_str();
317
1.29k
    if (!request.params[3].isNull() && !request.params[3].get_str().empty())
318
1
        comment_to = request.params[3].get_str();
319
320
1.29k
    CCoinControl coin_control;
321
1.29k
    if (!request.params[5].isNull()) {
322
2
        coin_control.m_signal_bip125_rbf = request.params[5].get_bool();
323
2
    }
324
325
1.29k
    coin_control.m_avoid_address_reuse = GetAvoidReuseFlag(*pwallet, request.params[8]);
326
    // We also enable partial spend avoidance if reuse avoidance is set.
327
1.29k
    coin_control.m_avoid_partial_spends |= coin_control.m_avoid_address_reuse;
328
329
1.29k
    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
1.29k
    EnsureWalletIsUnlocked(*pwallet);
332
333
1.29k
    UniValue address_amounts(UniValue::VOBJ);
334
1.29k
    const std::string address = request.params[0].get_str();
335
1.29k
    address_amounts.pushKV(address, request.params[1]);
336
337
1.29k
    std::set<int> sffo_set;
338
1.29k
    if (self.Arg<bool>("subtractfeefromamount")) {
339
216
        sffo_set.insert(0);
340
216
    }
341
342
1.29k
    std::vector<CRecipient> recipients{CreateRecipients(ParseOutputs(address_amounts), sffo_set)};
343
1.29k
    const bool verbose{self.Arg<bool>("verbose")};
344
345
1.29k
    return SendMoney(*pwallet, coin_control, recipients, comment, comment_to, verbose);
346
1.29k
},
347
2.17k
    };
348
2.17k
}
349
350
RPCMethod sendmany()
351
969
{
352
969
    return RPCMethod{"sendmany",
353
969
        "Send multiple times. Amounts are double-precision floating point numbers." +
354
969
        HELP_REQUIRING_PASSPHRASE,
355
969
                {
356
969
                    {"dummy", RPCArg::Type::STR, RPCArg::Default{"\"\""}, "Must be set to \"\" for backwards compatibility.",
357
969
                     RPCArgOptions{
358
969
                         .oneline_description = "\"\"",
359
969
                         .placeholder = true,
360
969
                     }},
361
969
                    {"amounts", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::NO, "The addresses and amounts",
362
969
                        {
363
969
                            {"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
969
                        },
365
969
                    },
366
969
                    {"minconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Ignored dummy value",
367
969
                        RPCArgOptions{.placeholder = true}},
368
969
                    {"comment", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A comment"},
369
969
                    {"subtractfeefrom", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The addresses.\n"
370
969
                                       "The fee will be equally deducted from the amount of each selected address.\n"
371
969
                                       "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
372
969
                                       "If no addresses are specified here, the sender pays the fee.",
373
969
                        {
374
969
                            {"address", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Subtract fee from this address"},
375
969
                        },
376
969
                    },
377
969
                    {"replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Signal that this transaction can be replaced by a transaction (BIP 125)"},
378
969
                    {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
379
969
                    {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
380
969
                      + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
381
969
                    {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
382
969
                    {"verbose", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, return extra information about the transaction."},
383
969
                },
384
969
                {
385
969
                    RPCResult{"if verbose is not set or set to false",
386
969
                        RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n"
387
969
                "the number of addresses."
388
969
                    },
389
969
                    RPCResult{"if verbose is set to true",
390
969
                        RPCResult::Type::OBJ, "", "",
391
969
                        {
392
969
                            {RPCResult::Type::STR_HEX, "txid", "The transaction id for the send. Only 1 transaction is created regardless of\n"
393
969
                "the number of addresses."},
394
969
                            {RPCResult::Type::STR, "fee_reason", "The reason the wallet selected this fee rate (\"" + FeeReasons("\", \"") + "\")."}
395
969
                        },
396
969
                    },
397
969
                },
398
969
                RPCExamples{
399
969
            "\nSend two amounts to two different addresses:\n"
400
969
            + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\"") +
401
969
            "\nSend two amounts to two different addresses setting the confirmation and comment:\n"
402
969
            + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\" 6 \"testing\"") +
403
969
            "\nSend two amounts to two different addresses, subtract fee from amount:\n"
404
969
            + HelpExampleCli("sendmany", "\"\" \"{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.01,\\\"" + EXAMPLE_ADDRESS[1] + "\\\":0.02}\" 1 \"\" \"[\\\"" + EXAMPLE_ADDRESS[0] + "\\\",\\\"" + EXAMPLE_ADDRESS[1] + "\\\"]\"") +
405
969
            "\nAs a JSON-RPC call\n"
406
969
            + HelpExampleRpc("sendmany", "\"\", {\"" + EXAMPLE_ADDRESS[0] + "\":0.01,\"" + EXAMPLE_ADDRESS[1] + "\":0.02}, 6, \"testing\"")
407
969
                },
408
969
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
409
969
{
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
0
    }
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
0
    }
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
84
    std::vector<CRecipient> recipients = CreateRecipients(
436
84
            ParseOutputs(sendTo),
437
84
            InterpretSubtractFeeFromOutputInstructions(&request.params[4], sendTo.getKeys())
438
84
    );
439
84
    const bool verbose{self.Arg<bool>("verbose")};
440
441
84
    return SendMoney(*pwallet, coin_control, recipients, comment, /*comment_to=*/std::nullopt, verbose);
442
84
},
443
969
    };
444
969
}
445
446
// Only includes key documentation where the key is snake_case in all RPC methods. MixedCase keys can be added later.
447
static std::vector<RPCArg> FundTxDoc(bool solving_data = true)
448
4.47k
{
449
4.47k
    std::vector<RPCArg> args = {
450
4.47k
        {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks", RPCArgOptions{.also_positional = true}},
451
4.47k
        {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
452
4.47k
          + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used")), RPCArgOptions{.also_positional = true}},
453
4.47k
        {
454
4.47k
            "replaceable", RPCArg::Type::BOOL, RPCArg::DefaultHint{"wallet default"}, "Marks this transaction as BIP125-replaceable.\n"
455
4.47k
            "Allows this transaction to be replaced by a transaction with higher fees"
456
4.47k
        },
457
4.47k
    };
458
4.47k
    if (solving_data) {
459
4.47k
        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
4.47k
        "Used for fee estimation during coin selection.",
461
4.47k
            {
462
4.47k
                {
463
4.47k
                    "pubkeys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Public keys involved in this transaction.",
464
4.47k
                    {
465
4.47k
                        {"pubkey", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A public key"},
466
4.47k
                    }
467
4.47k
                },
468
4.47k
                {
469
4.47k
                    "scripts", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Scripts involved in this transaction.",
470
4.47k
                    {
471
4.47k
                        {"script", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A script"},
472
4.47k
                    }
473
4.47k
                },
474
4.47k
                {
475
4.47k
                    "descriptors", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Descriptors that provide solving data for this transaction.",
476
4.47k
                    {
477
4.47k
                        {"descriptor", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A descriptor"},
478
4.47k
                    }
479
4.47k
                },
480
4.47k
            }
481
4.47k
        });
482
4.47k
    }
483
4.47k
    return args;
484
4.47k
}
485
486
CreatedTransactionResult FundTransaction(CWallet& wallet, const CMutableTransaction& tx, const std::vector<CRecipient>& recipients, const UniValue& options, CCoinControl& coinControl, bool override_min_fee)
487
709
{
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
673
        RPCTypeCheckObj(options,
499
673
                {
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
673
                },
528
673
                true, true);
529
530
673
        if (options.exists("add_inputs")) {
531
174
            coinControl.m_allow_other_inputs = options["add_inputs"].get_bool();
532
174
        }
533
534
673
        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
2
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Change address must be a valid bitcoin address");
539
2
            }
540
541
11
            coinControl.destChange = dest;
542
11
        }
543
544
671
        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
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "changePosition out of bounds");
548
1
            }
549
60
            change_position = (unsigned int)pos;
550
60
        }
551
552
670
        if (options.exists("change_type")) {
553
100
            if (options.exists("changeAddress") || options.exists("change_address")) {
554
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both change address and address type options");
555
1
            }
556
99
            if (std::optional<OutputType> parsed = ParseOutputType(options["change_type"].get_str())) {
557
97
                coinControl.m_change_type.emplace(parsed.value());
558
97
            } else {
559
2
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("Unknown change type '%s'", options["change_type"].get_str()));
560
2
            }
561
99
        }
562
563
667
        if (const UniValue* lock_unspents = GetOptionWithAlias(options, "lock_unspents", "lockUnspents")) {
564
4
            lockUnspents = lock_unspents->get_bool();
565
4
        }
566
567
667
        if (options.exists("include_unsafe")) {
568
46
            coinControl.m_include_unsafe_inputs = options["include_unsafe"].get_bool();
569
46
        }
570
571
667
        if (options.exists("feeRate")) {
572
58
            if (options.exists("fee_rate")) {
573
2
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both fee_rate (" + CURRENCY_ATOM + "/vB) and feeRate (" + CURRENCY_UNIT + "/kvB)");
574
2
            }
575
56
            if (options.exists("conf_target")) {
576
2
                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
2
            }
578
54
            if (options.exists("estimate_mode")) {
579
2
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot specify both estimate_mode and feeRate");
580
2
            }
581
52
            coinControl.m_feerate = CFeeRate(AmountFromValue(options["feeRate"]));
582
52
            coinControl.fOverrideFeeRate = true;
583
52
        }
584
585
661
        if (options.exists("replaceable")) {
586
5
            coinControl.m_signal_bip125_rbf = options["replaceable"].get_bool();
587
5
        }
588
589
661
        if (options.exists("minconf")) {
590
9
            coinControl.m_min_depth = options["minconf"].getInt<int>();
591
592
9
            if (coinControl.m_min_depth < 0) {
593
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Negative minconf");
594
1
            }
595
9
        }
596
597
660
        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
0
            }
603
4
        }
604
660
        SetFeeEstimateMode(wallet, coinControl, options["conf_target"], options["estimate_mode"], options["fee_rate"], override_min_fee);
605
660
    }
606
607
696
    if (options.exists("solving_data")) {
608
14
        const UniValue solving_data = options["solving_data"].get_obj();
609
14
        if (solving_data.exists("pubkeys")) {
610
5
            for (const UniValue& pk_univ : solving_data["pubkeys"].get_array().getValues()) {
611
5
                const CPubKey pubkey = HexToPubKey(pk_univ.get_str());
612
5
                coinControl.m_external_provider.pubkeys.emplace(pubkey.GetID(), pubkey);
613
                // Add witness script for pubkeys
614
5
                const CScript wit_script = GetScriptForDestination(WitnessV0KeyHash(pubkey));
615
5
                coinControl.m_external_provider.scripts.emplace(CScriptID(wit_script), wit_script);
616
5
            }
617
5
        }
618
619
14
        if (solving_data.exists("scripts")) {
620
6
            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
1
                    throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, strprintf("'%s' is not hex", script_str));
624
1
                }
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
4
        }
630
631
13
        if (solving_data.exists("descriptors")) {
632
8
            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
1
                    throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Unable to parse descriptor '%s': %s", desc_str, error));
640
1
                }
641
7
                for (auto& desc : descs) {
642
7
                    desc->Expand(0, desc_out, scripts_temp, desc_out);
643
7
                }
644
7
                coinControl.m_external_provider.Merge(std::move(desc_out));
645
7
            }
646
8
        }
647
13
    }
648
649
694
    if (options.exists("input_weights")) {
650
2.49k
        for (const UniValue& input : options["input_weights"].get_array().getValues()) {
651
2.49k
            Txid txid = Txid::FromUint256(ParseHashO(input, "txid"));
652
653
2.49k
            const UniValue& vout_v = input.find_value("vout");
654
2.49k
            if (!vout_v.isNum()) {
655
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
656
1
            }
657
2.49k
            int vout = vout_v.getInt<int>();
658
2.49k
            if (vout < 0) {
659
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
660
1
            }
661
662
2.48k
            const UniValue& weight_v = input.find_value("weight");
663
2.48k
            if (!weight_v.isNum()) {
664
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing weight key");
665
1
            }
666
2.48k
            int64_t weight = weight_v.getInt<int64_t>();
667
2.48k
            const int64_t min_input_weight = GetTransactionInputWeight(CTxIn());
668
2.48k
            CHECK_NONFATAL(min_input_weight == 165);
669
2.48k
            if (weight < min_input_weight) {
670
2
                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
2
            }
672
2.48k
            if (weight > MAX_STANDARD_TX_WEIGHT) {
673
1
                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
1
            }
675
676
2.48k
            coinControl.SetInputWeight(COutPoint(txid, vout), weight);
677
2.48k
        }
678
161
    }
679
680
688
    if (options.exists("max_tx_weight")) {
681
10
        coinControl.m_max_tx_weight = options["max_tx_weight"].getInt<int>();
682
10
    }
683
684
688
    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
34
        }
688
36
    }
689
690
688
    if (recipients.empty())
691
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "TX must have at least one output");
692
693
688
    auto txr = FundTransaction(wallet, tx, recipients, change_position, lockUnspents, coinControl);
694
688
    if (!txr) {
695
91
        throw JSONRPCError(RPC_WALLET_ERROR, ErrorString(txr).original);
696
91
    }
697
597
    return *txr;
698
688
}
699
700
static void SetOptionsInputWeights(const UniValue& inputs, UniValue& options)
701
467
{
702
467
    if (options.exists("input_weights")) {
703
2
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Input weights should be specified in inputs rather than in options.");
704
2
    }
705
465
    if (inputs.size() == 0) {
706
274
        return;
707
274
    }
708
191
    UniValue weights(UniValue::VARR);
709
2.81k
    for (const UniValue& input : inputs.getValues()) {
710
2.81k
        if (input.exists("weight")) {
711
6
            weights.push_back(input);
712
6
        }
713
2.81k
    }
714
191
    options.pushKV("input_weights", std::move(weights));
715
191
}
716
717
RPCMethod fundrawtransaction()
718
1.13k
{
719
1.13k
    return RPCMethod{
720
1.13k
        "fundrawtransaction",
721
1.13k
        "If the transaction has no inputs, they will be automatically selected to meet its out value.\n"
722
1.13k
                "It will add at most one change output to the outputs.\n"
723
1.13k
                "No existing outputs will be modified unless \"subtract_fee_from_outputs\" is specified.\n"
724
1.13k
                "Note that inputs which were signed may need to be resigned after completion since in/outputs have been added.\n"
725
1.13k
                "The inputs added will not be signed, use signrawtransactionwithkey\n"
726
1.13k
                "or signrawtransactionwithwallet for that.\n"
727
1.13k
                "All existing inputs must either have their previous output transaction be in the wallet\n"
728
1.13k
                "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n"
729
1.13k
                "Note that all inputs selected must be of standard form and P2SH scripts must be\n"
730
1.13k
                "in the wallet using importdescriptors (to calculate fees).\n"
731
1.13k
                "You can see whether this is the case by checking the \"solvable\" field in the listunspent output.\n"
732
1.13k
                "Note that if specifying an exact fee rate, the resulting transaction may have a higher fee rate\n"
733
1.13k
                "if the transaction has unconfirmed inputs. This is because the wallet will attempt to make the\n"
734
1.13k
                "entire package have the given fee rate, not the resulting transaction.\n",
735
1.13k
                {
736
1.13k
                    {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of the raw transaction"},
737
1.13k
                    {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
738
1.13k
                        Cat<std::vector<RPCArg>>(
739
1.13k
                        {
740
1.13k
                            {"add_inputs", RPCArg::Type::BOOL, RPCArg::Default{true}, "For a transaction with existing inputs, automatically include more if they are not enough."},
741
1.13k
                            {"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
1.13k
                                                          "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
743
1.13k
                                                          "If that happens, you will need to fund the transaction with different inputs and republish it."},
744
1.13k
                            {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."},
745
1.13k
                            {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."},
746
1.13k
                            {"change_address|changeAddress", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
747
1.13k
                            {"change_position|changePosition", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
748
1.13k
                            {"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
1.13k
                            {"includeWatching", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
750
1.13k
                            {"lock_unspents|lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
751
1.13k
                            {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
752
1.13k
                            {"feeRate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_UNIT + "/kvB."},
753
1.13k
                            {"subtract_fee_from_outputs|subtractFeeFromOutputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The output indices to subtract the fee from.\n"
754
1.13k
                                                          "The fee will be equally deducted from the amount of each specified output.\n"
755
1.13k
                                                          "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
756
1.13k
                                                          "If no outputs are specified here, the sender pays the fee.",
757
1.13k
                                {
758
1.13k
                                    {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
759
1.13k
                                },
760
1.13k
                            },
761
1.13k
                            {"input_weights", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Inputs and their corresponding weights",
762
1.13k
                                {
763
1.13k
                                    {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
764
1.13k
                                        {
765
1.13k
                                            {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
766
1.13k
                                            {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output index"},
767
1.13k
                                            {"weight", RPCArg::Type::NUM, RPCArg::Optional::NO, "The maximum weight for this input, "
768
1.13k
                                                "including the weight of the outpoint and sequence number. "
769
1.13k
                                                "Note that serialized signature sizes are not guaranteed to be consistent, "
770
1.13k
                                                "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
771
1.13k
                                                "Remember to convert serialized sizes to weight units when necessary."},
772
1.13k
                                        },
773
1.13k
                                    },
774
1.13k
                                },
775
1.13k
                             },
776
1.13k
                            {"max_tx_weight", RPCArg::Type::NUM, RPCArg::Default{MAX_STANDARD_TX_WEIGHT}, "The maximum acceptable transaction weight.\n"
777
1.13k
                                                          "Transaction building will fail if this can not be satisfied."},
778
1.13k
                        },
779
1.13k
                        FundTxDoc()),
780
1.13k
                        RPCArgOptions{
781
1.13k
                            .oneline_description = "options",
782
1.13k
                        }},
783
1.13k
                    {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
784
1.13k
                        "If iswitness is not present, heuristic tests will be used in decoding.\n"
785
1.13k
                        "If true, only witness deserialization will be tried.\n"
786
1.13k
                        "If false, only non-witness deserialization will be tried.\n"
787
1.13k
                        "This boolean should reflect whether the transaction has inputs\n"
788
1.13k
                        "(e.g. fully valid, or on-chain transactions), if known by the caller."
789
1.13k
                    },
790
1.13k
                },
791
1.13k
                RPCResult{
792
1.13k
                    RPCResult::Type::OBJ, "", "",
793
1.13k
                    {
794
1.13k
                        {RPCResult::Type::STR_HEX, "hex", "The resulting raw transaction (hex-encoded string)"},
795
1.13k
                        {RPCResult::Type::STR_AMOUNT, "fee", "Fee in " + CURRENCY_UNIT + " the resulting transaction pays"},
796
1.13k
                        {RPCResult::Type::NUM, "changepos", "The position of the added change output, or -1"},
797
1.13k
                    }
798
1.13k
                                },
799
1.13k
                                RPCExamples{
800
1.13k
                            "\nCreate a transaction with no inputs\n"
801
1.13k
                            + HelpExampleCli("createrawtransaction", "\"[]\" \"{\\\"myaddress\\\":0.01}\"") +
802
1.13k
                            "\nAdd sufficient unsigned inputs to meet the output value\n"
803
1.13k
                            + HelpExampleCli("fundrawtransaction", "\"rawtransactionhex\"") +
804
1.13k
                            "\nSign the transaction\n"
805
1.13k
                            + HelpExampleCli("signrawtransactionwithwallet", "\"fundedtransactionhex\"") +
806
1.13k
                            "\nSend the transaction\n"
807
1.13k
                            + HelpExampleCli("sendrawtransaction", "\"signedtransactionhex\"")
808
1.13k
                                },
809
1.13k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
810
1.13k
{
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
0
    }
821
245
    UniValue options = request.params[1];
822
245
    std::vector<std::pair<CTxDestination, CAmount>> destinations;
823
11.4k
    for (const auto& tx_out : tx.vout) {
824
11.4k
        CTxDestination dest;
825
11.4k
        ExtractDestination(tx_out.scriptPubKey, dest);
826
11.4k
        destinations.emplace_back(dest, tx_out.nValue);
827
11.4k
    }
828
245
    std::vector<std::string> dummy(destinations.size(), "dummy");
829
245
    std::vector<CRecipient> recipients = CreateRecipients(
830
245
            destinations,
831
245
            InterpretSubtractFeeFromOutputInstructions(
832
245
                GetOptionWithAlias(options, "subtract_fee_from_outputs", "subtractFeeFromOutputs"), dummy)
833
245
    );
834
245
    CCoinControl coin_control;
835
    // Automatically select (additional) coins. Can be overridden by options.add_inputs.
836
245
    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
245
    tx.vout.clear();
840
245
    auto txr = FundTransaction(*pwallet, tx, recipients, options, coin_control, /*override_min_fee=*/true);
841
842
245
    UniValue result(UniValue::VOBJ);
843
245
    result.pushKV("hex", EncodeHexTx(*txr.tx));
844
245
    result.pushKV("fee", ValueFromAmount(txr.fee));
845
245
    result.pushKV("changepos", txr.change_pos ? (int)*txr.change_pos : -1);
846
847
245
    return result;
848
245
},
849
1.13k
    };
850
1.13k
}
851
852
RPCMethod signrawtransactionwithwallet()
853
1.20k
{
854
1.20k
    return RPCMethod{
855
1.20k
        "signrawtransactionwithwallet",
856
1.20k
        "Sign inputs for raw transaction (serialized, hex-encoded).\n"
857
1.20k
                "The second optional argument (may be null) is an array of previous transaction outputs that\n"
858
1.20k
                "this transaction depends on but may not yet be in the block chain." +
859
1.20k
        HELP_REQUIRING_PASSPHRASE,
860
1.20k
                {
861
1.20k
                    {"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"},
862
1.20k
                    {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The previous dependent transaction outputs",
863
1.20k
                        {
864
1.20k
                            {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
865
1.20k
                                {
866
1.20k
                                    {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
867
1.20k
                                    {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
868
1.20k
                                    {"scriptPubKey", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The output script"},
869
1.20k
                                    {"redeemScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2SH) redeem script"},
870
1.20k
                                    {"witnessScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2WSH or P2SH-P2WSH) witness script"},
871
1.20k
                                    {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "(required for Segwit inputs) the amount spent"},
872
1.20k
                                },
873
1.20k
                            },
874
1.20k
                        },
875
1.20k
                    },
876
1.20k
                    {"sighashtype", RPCArg::Type::STR, RPCArg::DefaultHint{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type. Must be one of\n"
877
1.20k
            "       \"DEFAULT\"\n"
878
1.20k
            "       \"ALL\"\n"
879
1.20k
            "       \"NONE\"\n"
880
1.20k
            "       \"SINGLE\"\n"
881
1.20k
            "       \"ALL|ANYONECANPAY\"\n"
882
1.20k
            "       \"NONE|ANYONECANPAY\"\n"
883
1.20k
            "       \"SINGLE|ANYONECANPAY\""},
884
1.20k
                },
885
1.20k
                RPCResult{
886
1.20k
                    RPCResult::Type::OBJ, "", "",
887
1.20k
                    {
888
1.20k
                        {RPCResult::Type::STR_HEX, "hex", "The hex-encoded raw transaction with signature(s)"},
889
1.20k
                        {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
890
1.20k
                        {RPCResult::Type::ARR, "errors", /*optional=*/true, "Script verification errors (if there are any)",
891
1.20k
                        {
892
1.20k
                            {RPCResult::Type::OBJ, "", "",
893
1.20k
                            {
894
1.20k
                                {RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"},
895
1.20k
                                {RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"},
896
1.20k
                                {RPCResult::Type::ARR, "witness", "",
897
1.20k
                                {
898
1.20k
                                    {RPCResult::Type::STR_HEX, "witness", ""},
899
1.20k
                                }},
900
1.20k
                                {RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"},
901
1.20k
                                {RPCResult::Type::NUM, "sequence", "Script sequence number"},
902
1.20k
                                {RPCResult::Type::STR, "error", "Verification or signing error related to the input"},
903
1.20k
                            }},
904
1.20k
                        }},
905
1.20k
                    }
906
1.20k
                },
907
1.20k
                RPCExamples{
908
1.20k
                    HelpExampleCli("signrawtransactionwithwallet", "\"myhex\"")
909
1.20k
            + HelpExampleRpc("signrawtransactionwithwallet", "\"myhex\"")
910
1.20k
                },
911
1.20k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
912
1.20k
{
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
0
    }
920
921
    // Sign the transaction
922
323
    LOCK(pwallet->cs_wallet);
923
323
    EnsureWalletIsUnlocked(*pwallet);
924
925
    // Fetch previous transactions (inputs):
926
323
    std::map<COutPoint, Coin> coins;
927
409
    for (const CTxIn& txin : mtx.vin) {
928
409
        coins[txin.prevout]; // Create empty map entry keyed by prevout.
929
409
    }
930
323
    pwallet->chain().findCoins(coins);
931
932
    // Parse the prevtxs array
933
323
    ParsePrevouts(request.params[1], nullptr, coins);
934
935
323
    std::optional<int> nHashType = ParseSighashString(request.params[2]);
936
323
    if (!nHashType) {
937
303
        nHashType = SIGHASH_DEFAULT;
938
303
    }
939
940
    // Script verification errors
941
323
    std::map<int, bilingual_str> input_errors;
942
943
323
    bool complete = pwallet->SignTransaction(mtx, coins, *nHashType, input_errors);
944
323
    UniValue result(UniValue::VOBJ);
945
323
    SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
946
323
    return result;
947
323
},
948
1.20k
    };
949
1.20k
}
950
951
// Definition of allowed formats of specifying transaction outputs in
952
// `bumpfee`, `psbtbumpfee`, `send` and `walletcreatefundedpsbt` RPCs.
953
static std::vector<RPCArg> OutputsDoc()
954
4.19k
{
955
4.19k
    return
956
4.19k
    {
957
4.19k
        {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
958
4.19k
            {
959
4.19k
                {"address", RPCArg::Type::AMOUNT, RPCArg::Optional::NO, "A key-value pair. The key (string) is the bitcoin address,\n"
960
4.19k
                         "the value (float or string) is the amount in " + CURRENCY_UNIT + ""},
961
4.19k
            },
962
4.19k
        },
963
4.19k
        {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
964
4.19k
            {
965
4.19k
                {"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
4.19k
            },
967
4.19k
        },
968
4.19k
    };
969
4.19k
}
970
971
static RPCMethod bumpfee_helper(std::string method_name)
972
1.94k
{
973
1.94k
    const bool want_psbt = method_name == "psbtbumpfee";
974
1.94k
    const std::string incremental_fee{CFeeRate(DEFAULT_INCREMENTAL_RELAY_FEE).ToString(FeeRateFormat::SAT_VB)};
975
976
1.94k
    return RPCMethod{method_name,
977
1.94k
        "Bumps the fee of a transaction T, replacing it with a new transaction B.\n"
978
1.94k
        + std::string(want_psbt ? "Returns a PSBT instead of creating and signing a new transaction.\n" : "") +
979
1.94k
        "A transaction with the given txid must be in the wallet.\n"
980
1.94k
        "The command will pay the additional fee by reducing change outputs or adding inputs when necessary.\n"
981
1.94k
        "It may add a new change output if one does not already exist.\n"
982
1.94k
        "All inputs in the original transaction will be included in the replacement transaction.\n"
983
1.94k
        "The command will fail if the wallet or mempool contains a transaction that spends one of T's outputs.\n"
984
1.94k
        "By default, the new fee will be calculated automatically using the estimatesmartfee RPC.\n"
985
1.94k
        "The user can specify a confirmation target for estimatesmartfee.\n"
986
1.94k
        "Alternatively, the user can specify a fee rate in " + CURRENCY_ATOM + "/vB for the new transaction.\n"
987
1.94k
        "At a minimum, the new fee rate must be high enough to pay an additional new relay fee (incrementalfee\n"
988
1.94k
        "returned by getnetworkinfo) to enter the node's mempool.\n"
989
1.94k
        "* 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
1.94k
        {
991
1.94k
            {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The txid to be bumped"},
992
1.94k
            {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
993
1.94k
                Cat(
994
1.94k
                {
995
1.94k
                    {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks\n"},
996
1.94k
                    {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"},
997
1.94k
                             "\nSpecify a fee rate in " + CURRENCY_ATOM + "/vB instead of relying on the built-in fee estimator.\n"
998
1.94k
                             "Must be at least " + incremental_fee + " higher than the current transaction fee rate.\n"
999
1.94k
                             "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
1.94k
                    {"replaceable", RPCArg::Type::BOOL, RPCArg::Default{true},
1001
1.94k
                             "Whether the new transaction should be\n"
1002
1.94k
                             "marked bip-125 replaceable. If true, the sequence numbers in the transaction will\n"
1003
1.94k
                             "be set to 0xfffffffd. If false, any input sequence numbers in the\n"
1004
1.94k
                             "transaction will be set to 0xfffffffe\n"
1005
1.94k
                             "so the new transaction will not be explicitly bip-125 replaceable (though it may\n"
1006
1.94k
                             "still be replaceable in practice, for example if it has unconfirmed ancestors which\n"
1007
1.94k
                             "are replaceable).\n"},
1008
1.94k
                    {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
1009
1.94k
                              + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
1010
1.94k
                    {"outputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The outputs specified as key-value pairs.\n"
1011
1.94k
                             "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"
1012
1.94k
                             "At least one output of either type must be specified.\n"
1013
1.94k
                             "Cannot be provided if 'original_change_index' is specified.",
1014
1.94k
                        OutputsDoc(),
1015
1.94k
                        RPCArgOptions{.skip_type_check = true}},
1016
1.94k
                    {"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
1.94k
                                                                                                                            "The indicated output will be recycled into the new change output on the bumped transaction. "
1018
1.94k
                                                                                                                            "The remainder after paying the recipients and fees will be sent to the output script of the "
1019
1.94k
                                                                                                                            "original change output. The change output’s amount can increase if bumping the transaction "
1020
1.94k
                                                                                                                            "adds new inputs, otherwise it will decrease. Cannot be used in combination with the 'outputs' option."},
1021
1.94k
                },
1022
1.94k
                want_psbt ? std::vector<RPCArg>{{"psbt_version", RPCArg::Type::NUM, RPCArg::Default(2), "The PSBT version number to use."}} : std::vector<RPCArg>()
1023
1.94k
                ),
1024
1.94k
                RPCArgOptions{.oneline_description="options"}},
1025
1.94k
        },
1026
1.94k
        RPCResult{
1027
1.94k
            RPCResult::Type::OBJ, "", "", Cat(
1028
1.94k
                want_psbt ?
1029
896
                std::vector<RPCResult>{{RPCResult::Type::STR, "psbt", "The base64-encoded unsigned PSBT of the new transaction."}} :
1030
1.94k
                std::vector<RPCResult>{{RPCResult::Type::STR_HEX, "txid", "The id of the new transaction."}},
1031
1.94k
            {
1032
1.94k
                {RPCResult::Type::STR_AMOUNT, "origfee", "The fee of the replaced transaction."},
1033
1.94k
                {RPCResult::Type::STR_AMOUNT, "fee", "The fee of the new transaction."},
1034
1.94k
                {RPCResult::Type::ARR, "errors", "Errors encountered during processing (may be empty).",
1035
1.94k
                {
1036
1.94k
                    {RPCResult::Type::STR, "", ""},
1037
1.94k
                }},
1038
1.94k
            })
1039
1.94k
        },
1040
1.94k
        RPCExamples{
1041
1.94k
    "\nBump the fee, get the new transaction\'s " + std::string(want_psbt ? "psbt" : "txid") + "\n" +
1042
1.94k
            HelpExampleCli(method_name, "<txid>")
1043
1.94k
        },
1044
1.94k
        [want_psbt](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1045
1.94k
{
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
1
        throw JSONRPCError(RPC_WALLET_ERROR, "bumpfee is not available with wallets that have private keys disabled. Use psbtbumpfee instead.");
1051
1
    }
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
87
        RPCTypeCheckObj(options,
1067
87
            {
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
87
            },
1077
87
            true, true);
1078
1079
87
        if (options.exists("confTarget") && !pwallet->chain().rpcEnableDeprecated("confTarget")) {
1080
2
            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
2
        }
1082
1083
85
        if (options.exists("confTarget") && options.exists("conf_target")) {
1084
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "confTarget and conf_target options should not both be set. Use conf_target (confTarget is deprecated).");
1085
1
        }
1086
1087
84
        auto conf_target = options.exists("confTarget") ? options["confTarget"] : options["conf_target"];
1088
1089
84
        if (options.exists("replaceable")) {
1090
1
            coin_control.m_signal_bip125_rbf = options["replaceable"].get_bool();
1091
1
        }
1092
84
        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
84
        if (!options["outputs"].isNull()) {
1096
11
            if (options["outputs"].isArray() && options["outputs"].empty()) {
1097
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output argument cannot be an empty array");
1098
1
            }
1099
10
            CMutableTransaction tempTx;
1100
10
            AddOutputs(tempTx, options["outputs"]);
1101
10
            outputs = tempTx.vout;
1102
10
        }
1103
1104
83
        if (options.exists("original_change_index")) {
1105
6
            original_change_index = options["original_change_index"].getInt<uint32_t>();
1106
6
        }
1107
1108
83
        if (options.exists("psbt_version")) {
1109
3
            psbt_version = options["psbt_version"].getInt<uint32_t>();
1110
3
        }
1111
83
        if (psbt_version != 2 && psbt_version != 0) {
1112
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "The PSBT version can only be 2 or 0");
1113
1
        }
1114
83
    }
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
173
    pwallet->BlockUntilSyncedToCurrentChain();
1119
1120
173
    LOCK(pwallet->cs_wallet);
1121
1122
173
    EnsureWalletIsUnlocked(*pwallet);
1123
1124
1125
173
    std::vector<bilingual_str> errors;
1126
173
    CAmount old_fee;
1127
173
    CAmount new_fee;
1128
173
    CMutableTransaction mtx;
1129
    // Targeting feerate bump.
1130
173
    [&](){
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
146
        } // no default case, so the compiler can warn about missing cases
1145
0
        NONFATAL_UNREACHABLE();
1146
0
    }();
1147
1148
173
    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
173
    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
0
            }
1157
0
            throw JSONRPCError(RPC_WALLET_ERROR, "Can't sign transaction.");
1158
0
        }
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
0
        }
1164
1165
104
        result.pushKV("txid", txid.GetHex());
1166
104
    } else {
1167
69
        PartiallySignedTransaction psbtx{mtx, psbt_version};
1168
69
        bool complete = false;
1169
69
        const auto err{pwallet->FillPSBT(psbtx, {.sign = false, .bip32_derivs = true}, complete)};
1170
69
        CHECK_NONFATAL(!err);
1171
69
        CHECK_NONFATAL(!complete);
1172
69
        DataStream ssTx{};
1173
69
        ssTx << psbtx;
1174
69
        result.pushKV("psbt", EncodeBase64(ssTx.str()));
1175
69
    }
1176
1177
173
    result.pushKV("origfee", ValueFromAmount(old_fee));
1178
173
    result.pushKV("fee", ValueFromAmount(new_fee));
1179
173
    UniValue result_errors(UniValue::VARR);
1180
173
    for (const bilingual_str& error : errors) {
1181
0
        result_errors.push_back(error.original);
1182
0
    }
1183
173
    result.pushKV("errors", std::move(result_errors));
1184
1185
173
    return result;
1186
173
},
1187
1.94k
    };
1188
1.94k
}
1189
1190
1.05k
RPCMethod bumpfee() { return bumpfee_helper("bumpfee"); }
1191
896
RPCMethod psbtbumpfee() { return bumpfee_helper("psbtbumpfee"); }
1192
1193
RPCMethod send()
1194
1.12k
{
1195
1.12k
    return RPCMethod{
1196
1.12k
        "send",
1197
1.12k
        "Send a transaction.\n",
1198
1.12k
        {
1199
1.12k
            {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n"
1200
1.12k
                    "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"
1201
1.12k
                    "At least one output of either type must be specified.\n"
1202
1.12k
                    "For convenience, a dictionary, which holds the key-value pairs directly, is also accepted.",
1203
1.12k
                OutputsDoc(),
1204
1.12k
                RPCArgOptions{.skip_type_check = true}},
1205
1.12k
            {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
1206
1.12k
            {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
1207
1.12k
              + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
1208
1.12k
            {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
1209
1.12k
            {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
1210
1.12k
                Cat<std::vector<RPCArg>>(
1211
1.12k
                {
1212
1.12k
                    {"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
1.12k
                    {"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
1.12k
                                                          "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
1215
1.12k
                                                          "If that happens, you will need to fund the transaction with different inputs and republish it."},
1216
1.12k
                    {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."},
1217
1.12k
                    {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."},
1218
1.12k
                    {"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
1.12k
                    {"change_address", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
1220
1.12k
                    {"change_position", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
1221
1.12k
                    {"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
1.12k
                    {"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
1.12k
                    {"include_watching", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
1224
1.12k
                    {"inputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Specify inputs instead of adding them automatically.",
1225
1.12k
                        {
1226
1.12k
                          {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", {
1227
1.12k
                            {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1228
1.12k
                            {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1229
1.12k
                            {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
1230
1.12k
                            {"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, "
1231
1.12k
                                        "including the weight of the outpoint and sequence number. "
1232
1.12k
                                        "Note that signature sizes are not guaranteed to be consistent, "
1233
1.12k
                                        "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
1234
1.12k
                                        "Remember to convert serialized sizes to weight units when necessary."},
1235
1.12k
                          }},
1236
1.12k
                        },
1237
1.12k
                    },
1238
1.12k
                    {"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
1.12k
                    {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
1240
1.12k
                    {"psbt", RPCArg::Type::BOOL,  RPCArg::DefaultHint{"automatic"}, "Always return a PSBT, implies add_to_wallet=false."},
1241
1.12k
                    {"subtract_fee_from_outputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Outputs to subtract the fee from, specified as integer indices.\n"
1242
1.12k
                    "The fee will be equally deducted from the amount of each specified output.\n"
1243
1.12k
                    "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
1244
1.12k
                    "If no outputs are specified here, the sender pays the fee.",
1245
1.12k
                        {
1246
1.12k
                            {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
1247
1.12k
                        },
1248
1.12k
                    },
1249
1.12k
                    {"max_tx_weight", RPCArg::Type::NUM, RPCArg::Default{MAX_STANDARD_TX_WEIGHT}, "The maximum acceptable transaction weight.\n"
1250
1.12k
                                                  "Transaction building will fail if this can not be satisfied."},
1251
1.12k
                },
1252
1.12k
                FundTxDoc()),
1253
1.12k
                RPCArgOptions{.oneline_description="options"}},
1254
1.12k
                {"version", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_WALLET_TX_VERSION}, "Transaction version"},
1255
1.12k
        },
1256
1.12k
        RPCResult{
1257
1.12k
            RPCResult::Type::OBJ, "", "",
1258
1.12k
                {
1259
1.12k
                    {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1260
1.12k
                    {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
1.12k
                    {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
1262
1.12k
                    {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
1.12k
                }
1264
1.12k
        },
1265
1.12k
        RPCExamples{""
1266
1.12k
        "\nSend 0.1 BTC with a confirmation target of 6 blocks in economical fee estimate mode\n"
1267
1.12k
        + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.1}' 6 economical\n") +
1268
1.12k
        "Send 0.2 BTC with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB using positional arguments\n"
1269
1.12k
        + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.2}' null \"unset\" 1.1\n") +
1270
1.12k
        "Send 0.2 BTC with a fee rate of 1 " + CURRENCY_ATOM + "/vB using the options argument\n"
1271
1.12k
        + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.2}' null \"unset\" null '{\"fee_rate\": 1}'\n") +
1272
1.12k
        "Send 0.3 BTC with a fee rate of 25 " + CURRENCY_ATOM + "/vB using named arguments\n"
1273
1.12k
        + HelpExampleCli("-named send", "outputs='{\"" + EXAMPLE_ADDRESS[0] + "\": 0.3}' fee_rate=25\n") +
1274
1.12k
        "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
1.12k
        + HelpExampleCli("send", "'{\"" + EXAMPLE_ADDRESS[0] + "\": 0.1}' 1 economical null '{\"add_to_wallet\": false, \"inputs\": [{\"txid\":\"a08e6907dbbd3d809776dbfc5d82e371b764ed838b5655e72f463568df1aadf0\", \"vout\":1}]}'")
1276
1.12k
        },
1277
1.12k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1278
1.12k
        {
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
237
            PreventOutdatedOptions(options);
1285
1286
1287
237
            bool rbf{options.exists("replaceable") ? options["replaceable"].get_bool() : pwallet->m_signal_rbf};
1288
237
            UniValue outputs(UniValue::VOBJ);
1289
237
            outputs = NormalizeOutputs(request.params[0]);
1290
237
            std::vector<CRecipient> recipients = CreateRecipients(
1291
237
                    ParseOutputs(outputs),
1292
237
                    InterpretSubtractFeeFromOutputInstructions(&options["subtract_fee_from_outputs"], outputs.getKeys())
1293
237
            );
1294
237
            CCoinControl coin_control;
1295
237
            coin_control.m_version = self.Arg<uint32_t>("version");
1296
237
            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
237
            coin_control.m_allow_other_inputs = rawTx.vin.size() == 0;
1300
237
            if (options.exists("max_tx_weight")) {
1301
0
                coin_control.m_max_tx_weight = options["max_tx_weight"].getInt<int>();
1302
0
            }
1303
1304
237
            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
237
            rawTx.vout.clear();
1308
237
            auto txr = FundTransaction(*pwallet, rawTx, recipients, options, coin_control, /*override_min_fee=*/false);
1309
1310
237
            CMutableTransaction tx = CMutableTransaction(*txr.tx);
1311
237
            return FinishTransaction(pwallet, options, tx);
1312
237
        }
1313
1.12k
    };
1314
1.12k
}
1315
1316
RPCMethod sendall()
1317
1.10k
{
1318
1.10k
    return RPCMethod{"sendall",
1319
1.10k
        "Spend the value of all (or specific) confirmed UTXOs and unconfirmed change in the wallet to one or more recipients.\n"
1320
1.10k
        "Unconfirmed inbound UTXOs and locked UTXOs will not be spent. Sendall will respect the avoid_reuse wallet flag.\n"
1321
1.10k
        "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
1.10k
        {
1323
1.10k
            {"recipients", RPCArg::Type::ARR, RPCArg::Optional::NO, "The sendall destinations. Each address may only appear once.\n"
1324
1.10k
                "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
1.10k
                {
1326
1.10k
                    {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "A bitcoin address which receives an equal share of the unspecified amount."},
1327
1.10k
                    {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
1328
1.10k
                        {
1329
1.10k
                            {"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
1.10k
                        },
1331
1.10k
                    },
1332
1.10k
                },
1333
1.10k
            },
1334
1.10k
            {"conf_target", RPCArg::Type::NUM, RPCArg::DefaultHint{"wallet -txconfirmtarget"}, "Confirmation target in blocks"},
1335
1.10k
            {"estimate_mode", RPCArg::Type::STR, RPCArg::Default{"unset"}, "The fee estimate mode, must be one of (case insensitive):\n"
1336
1.10k
              + FeeModesDetail(std::string("economical mode is used if the transaction is replaceable;\notherwise, conservative mode is used"))},
1337
1.10k
            {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
1338
1.10k
            {
1339
1.10k
                "options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
1340
1.10k
                Cat<std::vector<RPCArg>>(
1341
1.10k
                    {
1342
1.10k
                        {"add_to_wallet", RPCArg::Type::BOOL, RPCArg::Default{true}, "When false, returns the serialized transaction without broadcasting or adding it to the wallet"},
1343
1.10k
                        {"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
1.10k
                        {"include_watching", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
1345
1.10k
                        {"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
1.10k
                            {
1347
1.10k
                                {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
1348
1.10k
                                    {
1349
1.10k
                                        {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1350
1.10k
                                        {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1351
1.10k
                                        {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
1352
1.10k
                                    },
1353
1.10k
                                },
1354
1.10k
                            },
1355
1.10k
                        },
1356
1.10k
                        {"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
1.10k
                        {"lock_unspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
1358
1.10k
                        {"psbt", RPCArg::Type::BOOL,  RPCArg::DefaultHint{"automatic"}, "Always return a PSBT, implies add_to_wallet=false."},
1359
1.10k
                        {"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
1.10k
                        {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "Require inputs with at least this many confirmations."},
1361
1.10k
                        {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "Require inputs with at most this many confirmations."},
1362
1.10k
                        {"version", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_WALLET_TX_VERSION}, "Transaction version"},
1363
1.10k
                    },
1364
1.10k
                    FundTxDoc()
1365
1.10k
                ),
1366
1.10k
                RPCArgOptions{.oneline_description="options"}
1367
1.10k
            },
1368
1.10k
        },
1369
1.10k
        RPCResult{
1370
1.10k
            RPCResult::Type::OBJ, "", "",
1371
1.10k
                {
1372
1.10k
                    {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1373
1.10k
                    {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
1.10k
                    {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "If add_to_wallet is false, the hex-encoded raw transaction with signature(s)"},
1375
1.10k
                    {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
1.10k
                }
1377
1.10k
        },
1378
1.10k
        RPCExamples{""
1379
1.10k
        "\nSpend all UTXOs from the wallet with a fee rate of 1 " + CURRENCY_ATOM + "/vB using named arguments\n"
1380
1.10k
        + HelpExampleCli("-named sendall", "recipients='[\"" + EXAMPLE_ADDRESS[0] + "\"]' fee_rate=1\n") +
1381
1.10k
        "Spend all UTXOs with a fee rate of 1.1 " + CURRENCY_ATOM + "/vB using positional arguments\n"
1382
1.10k
        + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\"]' null \"unset\" 1.1\n") +
1383
1.10k
        "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
1.10k
        + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\", \"" + EXAMPLE_ADDRESS[1] + "\"]' null \"unset\" null '{\"fee_rate\": 1.5}'\n") +
1385
1.10k
        "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
1.10k
        + HelpExampleCli("sendall", "'[\"" + EXAMPLE_ADDRESS[0] + "\"]' null \"unset\" null '{\"fee_rate\": 10, \"send_max\": true}'\n") +
1387
1.10k
        "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
1.10k
        + HelpExampleCli("-named sendall", "recipients='[{\"" + EXAMPLE_ADDRESS[1] + "\": 0.25}, \""+ EXAMPLE_ADDRESS[0] + "\"]' fee_rate=1.3\n")
1389
1.10k
        },
1390
1.10k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1391
1.10k
        {
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
220
            RPCTypeCheckObj(options,
1400
220
                {
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
220
                },
1417
220
                /*fAllowNull=*/true, /*fStrict=*/true);
1418
220
            InterpretFeeEstimationInstructions(/*conf_target=*/request.params[1], /*estimate_mode=*/request.params[2], /*fee_rate=*/request.params[3], options);
1419
1420
1421
220
            std::set<CTxDestination> addresses_without_amount;
1422
220
            UniValue recipient_key_value_pairs(UniValue::VARR);
1423
220
            const UniValue& recipients{request.params[0]};
1424
1.14k
            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
918
                    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
9
                }
1436
927
            }
1437
1438
220
            if (addresses_without_amount.size() == 0) {
1439
2
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Must provide at least one address without a specified amount");
1440
2
            }
1441
1442
218
            CCoinControl coin_control;
1443
1444
218
            SetFeeEstimateMode(*pwallet, coin_control, options["conf_target"], options["estimate_mode"], options["fee_rate"], /*override_min_fee=*/false);
1445
1446
218
            if (options.exists("minconf")) {
1447
7
                if (options["minconf"].getInt<int>() < 0)
1448
1
                {
1449
1
                    throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid minconf (minconf cannot be negative): %s", options["minconf"].getInt<int>()));
1450
1
                }
1451
1452
6
                coin_control.m_min_depth = options["minconf"].getInt<int>();
1453
6
            }
1454
1455
217
            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
0
                }
1461
2
            }
1462
1463
217
            if (options.exists("version")) {
1464
9
                coin_control.m_version = options["version"].getInt<decltype(coin_control.m_version)>();
1465
9
            }
1466
1467
217
            if (coin_control.m_version == TRUC_VERSION) {
1468
7
                coin_control.m_max_tx_weight = TRUC_MAX_WEIGHT;
1469
210
            } else {
1470
210
                coin_control.m_max_tx_weight = MAX_STANDARD_TX_WEIGHT;
1471
210
            }
1472
1473
217
            const bool rbf{options.exists("replaceable") ? options["replaceable"].get_bool() : pwallet->m_signal_rbf};
1474
1475
217
            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
217
            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
1
                    coin_control.m_feerate->ToString(feerate_format),
1482
1
                    fee_rate.ToString(feerate_format))};
1483
1
                if (fee_reason == FeeReason::REQUIRED) {
1484
1
                    msg += strprintf("\nConsider modifying -mintxfee (%s) or -minrelaytxfee (%s).",
1485
1
                        pwallet->m_min_fee.ToString(feerate_format),
1486
1
                        pwallet->chain().relayMinFee().ToString(feerate_format));
1487
1
                }
1488
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, msg);
1489
1
            }
1490
216
            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
0
            }
1494
1495
216
            CMutableTransaction rawTx{ConstructTransaction(options["inputs"], recipient_key_value_pairs, options["locktime"], rbf, coin_control.m_version)};
1496
216
            LOCK(pwallet->cs_wallet);
1497
1498
216
            CAmount total_input_value(0);
1499
216
            bool send_max{options.exists("send_max") ? options["send_max"].get_bool() : false};
1500
216
            if (options.exists("inputs") && options.exists("send_max")) {
1501
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot combine send_max with specific inputs.");
1502
215
            } else if (options.exists("inputs") && (options.exists("minconf") || options.exists("maxconf"))) {
1503
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot combine minconf or maxconf with specific inputs.");
1504
214
            } else if (options.exists("inputs")) {
1505
28
                std::unordered_set<COutPoint, SaltedOutpointHasher> seen_inputs;
1506
28
                seen_inputs.reserve(rawTx.vin.size());
1507
30
                for (const CTxIn& input : rawTx.vin) {
1508
30
                    if (!seen_inputs.insert(input.prevout).second) {
1509
1
                        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, duplicated input: %s:%d", input.prevout.hash.ToString(), input.prevout.n));
1510
1
                    }
1511
29
                    if (pwallet->IsSpent(input.prevout)) {
1512
2
                        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input not available. UTXO (%s:%d) was already spent.", input.prevout.hash.ToString(), input.prevout.n));
1513
2
                    }
1514
27
                    const CWalletTx* tx{pwallet->GetWalletTx(input.prevout.hash)};
1515
27
                    if (!tx || input.prevout.n >= tx->GetTx()->vout.size() || !pwallet->IsMine(tx->GetTx()->vout[input.prevout.n])) {
1516
2
                        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
2
                    }
1518
25
                    if (pwallet->GetTxDepthInMainChain(*tx) == 0) {
1519
16
                        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
0
                        }
1524
16
                    }
1525
25
                    total_input_value += tx->GetTx()->vout[input.prevout.n].nValue;
1526
25
                }
1527
186
            } else {
1528
186
                CoinFilterParams coins_params;
1529
186
                coins_params.min_amount = 0;
1530
2.84k
                for (const COutput& output : AvailableCoins(*pwallet, &coin_control, fee_rate, coins_params).All()) {
1531
2.84k
                    if (send_max && fee_rate.GetFee(output.input_bytes) > output.txout.nValue) {
1532
2
                        continue;
1533
2
                    }
1534
                    // we are spending an unconfirmed TRUC transaction, so lower max weight
1535
2.84k
                    if (output.depth == 0 && coin_control.m_version == TRUC_VERSION) {
1536
4
                        coin_control.m_max_tx_weight = TRUC_CHILD_MAX_WEIGHT;
1537
4
                    }
1538
2.84k
                    CTxIn input(output.outpoint.hash, output.outpoint.n, CScript(), rbf ? MAX_BIP125_RBF_SEQUENCE : CTxIn::MAX_SEQUENCE_NONFINAL);
1539
2.84k
                    rawTx.vin.push_back(input);
1540
2.84k
                    total_input_value += output.txout.nValue;
1541
2.84k
                }
1542
186
            }
1543
1544
209
            std::vector<COutPoint> outpoints_spent;
1545
209
            outpoints_spent.reserve(rawTx.vin.size());
1546
1547
2.87k
            for (const CTxIn& tx_in : rawTx.vin) {
1548
2.87k
                outpoints_spent.push_back(tx_in.prevout);
1549
2.87k
            }
1550
1551
            // estimate final size of tx
1552
209
            const TxSize tx_size{CalculateMaximumSignedTxSize(CTransaction(rawTx), pwallet.get())};
1553
209
            if (tx_size.vsize == -1) {
1554
2
                throw JSONRPCError(RPC_WALLET_ERROR, "Unable to determine the size of the transaction, the wallet contains unsolvable descriptors");
1555
2
            }
1556
207
            const CAmount fee_from_size{fee_rate.GetFee(tx_size.vsize)};
1557
207
            const std::optional<CAmount> total_bump_fees{pwallet->chain().calculateCombinedBumpFee(outpoints_spent, fee_rate)};
1558
207
            const CAmount actual_fee{fee_from_size + total_bump_fees.value_or(0)};
1559
207
            CAmount effective_value = total_input_value - actual_fee;
1560
1561
207
            if (actual_fee > pwallet->m_max_tx_fee) {
1562
2
                throw JSONRPCError(RPC_WALLET_ERROR, TransactionErrorString(TransactionError::MAX_FEE_EXCEEDED).original);
1563
2
            }
1564
205
            if (actual_fee > pwallet->m_max_tx_fee_rate.GetFee(tx_size.vsize)) {
1565
1
                throw JSONRPCError(RPC_WALLET_ERROR, TransactionErrorString(TransactionError::MAX_FEE_RATE_EXCEEDED).original);
1566
1
            }
1567
1568
204
            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
33
                } else {
1572
33
                    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
33
                }
1574
33
            }
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
171
            if (tx_size.weight > coin_control.m_max_tx_weight) {
1578
3
                throw JSONRPCError(RPC_WALLET_ERROR, "Transaction too large.");
1579
3
            }
1580
1581
168
            CAmount output_amounts_claimed{0};
1582
526
            for (const CTxOut& out : rawTx.vout) {
1583
526
                output_amounts_claimed += out.nValue;
1584
526
            }
1585
1586
168
            if (output_amounts_claimed > total_input_value) {
1587
1
                throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Assigned more value to outputs than available funds.");
1588
1
            }
1589
1590
167
            const CAmount remainder{effective_value - output_amounts_claimed};
1591
167
            if (remainder < 0) {
1592
1
                throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds for fees after creating specified outputs.");
1593
1
            }
1594
1595
166
            const CAmount per_output_without_amount{remainder / (long)addresses_without_amount.size()};
1596
1597
166
            bool gave_remaining_to_first{false};
1598
521
            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
162
                    }
1607
515
                    if (IsDust(out, pwallet->chain().relayDustFee())) {
1608
                        // Dynamically generated output amount is dust
1609
2
                        throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Dynamically assigned remainder results in dust output.");
1610
2
                    }
1611
515
                } else {
1612
6
                    if (IsDust(out, pwallet->chain().relayDustFee())) {
1613
                        // Specified output amount is dust
1614
1
                        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Specified output amount to %s is below dust threshold.", EncodeDestination(dest)));
1615
1
                    }
1616
6
                }
1617
521
            }
1618
1619
163
            const bool lock_unspents{options.exists("lock_unspents") ? options["lock_unspents"].get_bool() : false};
1620
163
            if (lock_unspents) {
1621
2
                for (const CTxIn& txin : rawTx.vin) {
1622
2
                    pwallet->LockCoin(txin.prevout, /*persist=*/false);
1623
2
                }
1624
2
            }
1625
1626
163
            return FinishTransaction(pwallet, options, rawTx);
1627
166
        }
1628
1.10k
    };
1629
1.10k
}
1630
1631
RPCMethod walletprocesspsbt()
1632
1.52k
{
1633
1.52k
    return RPCMethod{
1634
1.52k
        "walletprocesspsbt",
1635
1.52k
        "Update a PSBT with input information from our wallet and then sign inputs\n"
1636
1.52k
                "that we can sign for." +
1637
1.52k
        HELP_REQUIRING_PASSPHRASE,
1638
1.52k
                {
1639
1.52k
                    {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction base64 string"},
1640
1.52k
                    {"sign", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also sign the transaction when updating (requires wallet to be unlocked)"},
1641
1.52k
                    {"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
1.52k
            "       \"DEFAULT\"\n"
1643
1.52k
            "       \"ALL\"\n"
1644
1.52k
            "       \"NONE\"\n"
1645
1.52k
            "       \"SINGLE\"\n"
1646
1.52k
            "       \"ALL|ANYONECANPAY\"\n"
1647
1.52k
            "       \"NONE|ANYONECANPAY\"\n"
1648
1.52k
            "       \"SINGLE|ANYONECANPAY\""},
1649
1.52k
                    {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"},
1650
1.52k
                    {"finalize", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also finalize inputs if possible"},
1651
1.52k
                },
1652
1.52k
                RPCResult{
1653
1.52k
                    RPCResult::Type::OBJ, "", "",
1654
1.52k
                    {
1655
1.52k
                        {RPCResult::Type::STR, "psbt", "The base64-encoded partially signed transaction"},
1656
1.52k
                        {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1657
1.52k
                        {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The hex-encoded network transaction if complete"},
1658
1.52k
                    }
1659
1.52k
                },
1660
1.52k
                RPCExamples{
1661
1.52k
                    HelpExampleCli("walletprocesspsbt", "\"psbt\"")
1662
1.52k
                },
1663
1.52k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1664
1.52k
{
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
2
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));
1677
2
    }
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
639
    const bool sign{self.Arg<bool>("sign")};
1685
639
    const bool bip32derivs{self.Arg<bool>("bip32derivs")};
1686
639
    const bool finalize{self.Arg<bool>("finalize")};
1687
639
    bool complete = true;
1688
1689
639
    if (sign) EnsureWalletIsUnlocked(*pwallet);
1690
1691
639
    const auto err{wallet.FillPSBT(psbtx, {.sign = sign, .sighash_type = nHashType, .finalize = finalize, .bip32_derivs = bip32derivs}, complete)};
1692
639
    if (err) {
1693
7
        throw JSONRPCPSBTError(*err);
1694
7
    }
1695
1696
632
    UniValue result(UniValue::VOBJ);
1697
632
    DataStream ssTx{};
1698
632
    ssTx << psbtx;
1699
632
    result.pushKV("psbt", EncodeBase64(ssTx.str()));
1700
632
    result.pushKV("complete", complete);
1701
632
    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
42
        result.pushKV("hex", HexStr(ssTx_final));
1708
42
    }
1709
1710
632
    return result;
1711
639
},
1712
1.52k
    };
1713
1.52k
}
1714
1715
RPCMethod walletcreatefundedpsbt()
1716
1.12k
{
1717
1.12k
    return RPCMethod{
1718
1.12k
        "walletcreatefundedpsbt",
1719
1.12k
        "Creates and funds a transaction in the Partially Signed Transaction format.\n"
1720
1.12k
                "Implements the Creator and Updater roles.\n"
1721
1.12k
                "All existing inputs must either have their previous output transaction be in the wallet\n"
1722
1.12k
                "or be in the UTXO set. Solving data must be provided for non-wallet inputs.\n",
1723
1.12k
                {
1724
1.12k
                    {"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "Leave empty to add inputs automatically. See add_inputs option.",
1725
1.12k
                        {
1726
1.12k
                            {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
1727
1.12k
                                {
1728
1.12k
                                    {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
1729
1.12k
                                    {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
1730
1.12k
                                    {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'locktime' and 'options.replaceable' arguments"}, "The sequence number"},
1731
1.12k
                                    {"weight", RPCArg::Type::NUM, RPCArg::DefaultHint{"Calculated from wallet and solving data"}, "The maximum weight for this input, "
1732
1.12k
                                        "including the weight of the outpoint and sequence number. "
1733
1.12k
                                        "Note that signature sizes are not guaranteed to be consistent, "
1734
1.12k
                                        "so the maximum DER signatures size of 73 bytes should be used when considering ECDSA signatures."
1735
1.12k
                                        "Remember to convert serialized sizes to weight units when necessary."},
1736
1.12k
                                },
1737
1.12k
                            },
1738
1.12k
                        },
1739
1.12k
                        },
1740
1.12k
                    {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n"
1741
1.12k
                            "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"
1742
1.12k
                            "At least one output of either type must be specified.\n"
1743
1.12k
                            "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
1744
1.12k
                            "accepted as second parameter.",
1745
1.12k
                        OutputsDoc(),
1746
1.12k
                        RPCArgOptions{.skip_type_check = true}},
1747
1.12k
                    {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
1748
1.12k
                    {"options", RPCArg::Type::OBJ_NAMED_PARAMS, RPCArg::Optional::OMITTED, "",
1749
1.12k
                        Cat<std::vector<RPCArg>>(
1750
1.12k
                        {
1751
1.12k
                            {"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
1.12k
                            {"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
1.12k
                                                          "Warning: the resulting transaction may become invalid if one of the unsafe inputs disappears.\n"
1754
1.12k
                                                          "If that happens, you will need to fund the transaction with different inputs and republish it."},
1755
1.12k
                            {"minconf", RPCArg::Type::NUM, RPCArg::Default{0}, "If add_inputs is specified, require inputs with at least this many confirmations."},
1756
1.12k
                            {"maxconf", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If add_inputs is specified, require inputs with at most this many confirmations."},
1757
1.12k
                            {"change_address|changeAddress", RPCArg::Type::STR, RPCArg::DefaultHint{"automatic"}, "The bitcoin address to receive the change"},
1758
1.12k
                            {"change_position|changePosition", RPCArg::Type::NUM, RPCArg::DefaultHint{"random"}, "The index of the change output"},
1759
1.12k
                            {"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
1.12k
                            {"includeWatching", RPCArg::Type::BOOL, RPCArg::Default{false}, "(DEPRECATED) No longer used"},
1761
1.12k
                            {"lock_unspents|lockUnspents", RPCArg::Type::BOOL, RPCArg::Default{false}, "Lock selected unspent outputs"},
1762
1.12k
                            {"fee_rate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_ATOM + "/vB."},
1763
1.12k
                            {"feeRate", RPCArg::Type::AMOUNT, RPCArg::DefaultHint{"not set, fall back to wallet fee estimation"}, "Specify a fee rate in " + CURRENCY_UNIT + "/kvB."},
1764
1.12k
                            {"subtract_fee_from_outputs|subtractFeeFromOutputs", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "The outputs to subtract the fee from.\n"
1765
1.12k
                                                          "The fee will be equally deducted from the amount of each specified output.\n"
1766
1.12k
                                                          "Those recipients will receive less bitcoins than you enter in their corresponding amount field.\n"
1767
1.12k
                                                          "If no outputs are specified here, the sender pays the fee.",
1768
1.12k
                                {
1769
1.12k
                                    {"vout_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "The zero-based output index, before a change output is added."},
1770
1.12k
                                },
1771
1.12k
                            },
1772
1.12k
                            {"max_tx_weight", RPCArg::Type::NUM, RPCArg::Default{MAX_STANDARD_TX_WEIGHT}, "The maximum acceptable transaction weight.\n"
1773
1.12k
                                                          "Transaction building will fail if this can not be satisfied."},
1774
1.12k
                        },
1775
1.12k
                        FundTxDoc()),
1776
1.12k
                        RPCArgOptions{.oneline_description="options"}},
1777
1.12k
                    {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"},
1778
1.12k
                    {"version", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_WALLET_TX_VERSION}, "Transaction version"},
1779
1.12k
                    {"psbt_version", RPCArg::Type::NUM, RPCArg::Default(2), "The PSBT version number to use."},
1780
1.12k
                },
1781
1.12k
                RPCResult{
1782
1.12k
                    RPCResult::Type::OBJ, "", "",
1783
1.12k
                    {
1784
1.12k
                        {RPCResult::Type::STR, "psbt", "The resulting raw transaction (base64-encoded string)"},
1785
1.12k
                        {RPCResult::Type::STR_AMOUNT, "fee", "Fee in " + CURRENCY_UNIT + " the resulting transaction pays"},
1786
1.12k
                        {RPCResult::Type::NUM, "changepos", "The position of the added change output, or -1"},
1787
1.12k
                    }
1788
1.12k
                                },
1789
1.12k
                                RPCExamples{
1790
1.12k
                            "\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
1.12k
                            + HelpExampleCli("walletcreatefundedpsbt", "\"[]\" \"[{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.5}]\" 0 \"{\\\"add_inputs\\\":true,\\\"fee_rate\\\":2}\"")
1792
1.12k
                            + "\nCreate the same PSBT as the above one instead using named arguments:\n"
1793
1.12k
                            + HelpExampleCli("-named walletcreatefundedpsbt", "outputs=\"[{\\\"" + EXAMPLE_ADDRESS[0] + "\\\":0.5}]\" add_inputs=true fee_rate=2")
1794
1.12k
                                },
1795
1.12k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1796
1.12k
{
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
236
            ParseOutputs(outputs),
1817
236
            InterpretSubtractFeeFromOutputInstructions(
1818
236
                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
236
    rawTx.vout.clear();
1827
236
    auto txr = FundTransaction(wallet, rawTx, recipients, options, coin_control, /*override_min_fee=*/true);
1828
1829
    // Make a blank psbt
1830
236
    const uint32_t psbt_version{self.Arg<uint32_t>("psbt_version")};
1831
236
    if (psbt_version != 2 && psbt_version != 0) {
1832
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, "The PSBT version can only be 2 or 0");
1833
1
    }
1834
1835
235
    PartiallySignedTransaction psbtx(CMutableTransaction(*txr.tx), psbt_version);
1836
1837
    // Fill transaction with our data but don't sign
1838
235
    const bool bip32derivs{self.Arg<bool>("bip32derivs")};
1839
235
    bool complete = true;
1840
235
    const auto err{wallet.FillPSBT(psbtx, {.sign = false, .bip32_derivs = bip32derivs}, complete)};
1841
235
    if (err) {
1842
0
        throw JSONRPCPSBTError(*err);
1843
0
    }
1844
1845
    // Serialize the PSBT
1846
235
    DataStream ssTx{};
1847
235
    ssTx << psbtx;
1848
1849
235
    UniValue result(UniValue::VOBJ);
1850
235
    result.pushKV("psbt", EncodeBase64(ssTx.str()));
1851
235
    result.pushKV("fee", ValueFromAmount(txr.fee));
1852
235
    result.pushKV("changepos", txr.change_pos ? (int)*txr.change_pos : -1);
1853
235
    return result;
1854
235
},
1855
1.12k
    };
1856
1.12k
}
1857
} // namespace wallet