Coverage Report

Created: 2026-11-13 17:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/rpc/rawtransaction.cpp
Line
Count
Source
1
// Copyright (c) 2010 Satoshi Nakamoto
2
// Copyright (c) 2009-present The Bitcoin Core developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <addresstype.h>
7
#include <base58.h>
8
#include <chain.h>
9
#include <coins.h>
10
#include <common/types.h>
11
#include <consensus/amount.h>
12
#include <core_io.h>
13
#include <crypto/common.h>
14
#include <crypto/hex_base.h>
15
#include <hash.h>
16
#include <index/txindex.h>
17
#include <kernel/chainparams.h>
18
#include <key.h>
19
#include <key_io.h>
20
#include <node/blockstorage.h>
21
#include <node/coin.h>
22
#include <node/context.h>
23
#include <node/psbt.h>
24
#include <node/transaction.h>
25
#include <policy/feerate.h>
26
#include <primitives/block.h>
27
#include <primitives/transaction.h>
28
#include <psbt.h>
29
#include <pubkey.h>
30
#include <random.h>
31
#include <rpc/blockchain.h>
32
#include <rpc/protocol.h>
33
#include <rpc/rawtransaction_util.h>
34
#include <rpc/register.h> // IWYU pragma: associated
35
#include <rpc/request.h>
36
#include <rpc/server.h>
37
#include <rpc/server_util.h>
38
#include <rpc/util.h>
39
#include <script/interpreter.h>
40
#include <script/keyorigin.h>
41
#include <script/script.h>
42
#include <script/sign.h>
43
#include <script/signingprovider.h>
44
#include <script/solver.h>
45
#include <serialize.h>
46
#include <streams.h>
47
#include <sync.h>
48
#include <tinyformat.h>
49
#include <txmempool.h>
50
#include <uint256.h>
51
#include <undo.h>
52
#include <univalue.h>
53
#include <util/bip32.h>
54
#include <util/check.h>
55
#include <util/expected.h>
56
#include <util/result.h>
57
#include <util/strencodings.h>
58
#include <util/translation.h>
59
#include <util/vector.h>
60
#include <validation.h>
61
62
#include <algorithm>
63
#include <any>
64
#include <bitset>
65
#include <cstddef>
66
#include <cstdint>
67
#include <map>
68
#include <memory>
69
#include <optional>
70
#include <set>
71
#include <span>
72
#include <stdexcept>
73
#include <tuple>
74
#include <utility>
75
#include <vector>
76
77
using node::AnalyzePSBT;
78
using node::FindCoins;
79
using node::GetTransaction;
80
using node::NodeContext;
81
using node::PSBTAnalysis;
82
83
static constexpr decltype(CTransaction::version) DEFAULT_RAWTX_VERSION{CTransaction::CURRENT_VERSION};
84
85
static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry,
86
                     Chainstate& active_chainstate, const CTxUndo* txundo = nullptr,
87
                     TxVerbosity verbosity = TxVerbosity::SHOW_DETAILS)
88
3.49k
{
89
3.49k
    CHECK_NONFATAL(verbosity >= TxVerbosity::SHOW_DETAILS);
90
    // Call into TxToUniv() in bitcoin-common to decode the transaction hex.
91
    //
92
    // Blockchain contextual information (confirmations and blocktime) is not
93
    // available to code in bitcoin-common, so we query them here and push the
94
    // data into the returned UniValue.
95
3.49k
    TxToUniv(tx, /*block_hash=*/uint256(), entry, /*include_hex=*/true, txundo, verbosity);
96
97
3.49k
    if (!hashBlock.IsNull()) {
98
54
        LOCK(cs_main);
99
100
54
        entry.pushKV("blockhash", hashBlock.GetHex());
101
54
        const CBlockIndex* pindex = active_chainstate.m_blockman.LookupBlockIndex(hashBlock);
102
54
        if (pindex) {
103
54
            if (active_chainstate.m_chain.Contains(*pindex)) {
104
50
                entry.pushKV("confirmations", 1 + active_chainstate.m_chain.Height() - pindex->nHeight);
105
50
                entry.pushKV("time", pindex->GetBlockTime());
106
50
                entry.pushKV("blocktime", pindex->GetBlockTime());
107
50
            }
108
4
            else
109
4
                entry.pushKV("confirmations", 0);
110
54
        }
111
54
    }
112
3.49k
}
113
114
static std::vector<RPCArg> CreateTxDoc()
115
5.73k
{
116
5.73k
    return {
117
5.73k
        {"inputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The inputs",
118
5.73k
            {
119
5.73k
                {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
120
5.73k
                    {
121
5.73k
                        {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
122
5.73k
                        {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
123
5.73k
                        {"sequence", RPCArg::Type::NUM, RPCArg::DefaultHint{"depends on the value of the 'replaceable' and 'locktime' arguments"}, "The sequence number"},
124
5.73k
                    },
125
5.73k
                },
126
5.73k
            },
127
5.73k
        },
128
5.73k
        {"outputs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The outputs specified as key-value pairs.\n"
129
5.73k
                "Each key may only appear once, i.e. there can only be one 'data' output, and no address may be duplicated.\n"
130
5.73k
                "At least one output of either type must be specified.\n"
131
5.73k
                "For compatibility reasons, a dictionary, which holds the key-value pairs directly, is also\n"
132
5.73k
                "                             accepted as second parameter.",
133
5.73k
            {
134
5.73k
                {"", RPCArg::Type::OBJ_USER_KEYS, RPCArg::Optional::OMITTED, "",
135
5.73k
                    {
136
5.73k
                        {"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},
137
5.73k
                    },
138
5.73k
                },
139
5.73k
                {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
140
5.73k
                    {
141
5.73k
                        {"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"},
142
5.73k
                    },
143
5.73k
                },
144
5.73k
            },
145
5.73k
         RPCArgOptions{.skip_type_check = true}},
146
5.73k
        {"locktime", RPCArg::Type::NUM, RPCArg::Default{0}, "Raw locktime. Non-0 value also locktime-activates inputs"},
147
5.73k
        {"replaceable", RPCArg::Type::BOOL, RPCArg::Default{true}, "Marks this transaction as BIP125-replaceable.\n"
148
5.73k
                "Allows this transaction to be replaced by a transaction with higher fees. If provided, it is an error if explicit sequence numbers are incompatible."},
149
5.73k
        {"version", RPCArg::Type::NUM, RPCArg::Default{DEFAULT_RAWTX_VERSION}, "Transaction version"},
150
5.73k
    };
151
5.73k
}
152
153
// Update PSBT with information from the mempool, the UTXO set, the txindex, and the provided descriptors.
154
// Optionally, sign the inputs that we can using information from the descriptors.
155
PartiallySignedTransaction ProcessPSBT(const std::string& psbt_string, const std::any& context, const HidingSigningProvider& provider, std::optional<int> sighash_type, bool finalize)
156
26
{
157
    // Unserialize the transactions
158
26
    util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(psbt_string);
159
26
    if (!psbt_res) {
160
0
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));
161
0
    }
162
26
    PartiallySignedTransaction psbtx = *psbt_res;
163
164
26
    if (g_txindex) g_txindex->BlockUntilSyncedToCurrentChain();
165
26
    const NodeContext& node = EnsureAnyNodeContext(context);
166
167
    // If we can't find the corresponding full transaction for all of our inputs,
168
    // this will be used to find just the utxos for the segwit inputs for which
169
    // the full transaction isn't found
170
26
    std::map<COutPoint, Coin> coins;
171
172
    // Fetch previous transactions:
173
    // First, look in the txindex and the mempool
174
39
    for (PSBTInput& psbt_input : psbtx.inputs) {
175
        // The `non_witness_utxo` is the whole previous transaction
176
39
        if (psbt_input.non_witness_utxo) continue;
177
178
25
        uint256 block_hash;
179
25
        CTransactionRef tx{GetTransaction(/*block_index=*/nullptr, node.mempool.get(), psbt_input.prev_txid, node.chainman->m_blockman, block_hash)};
180
25
        if (tx) {
181
10
            psbt_input.non_witness_utxo = tx;
182
15
        } else {
183
15
            coins[psbt_input.GetOutPoint()]; // Create empty map entry keyed by prevout
184
15
        }
185
25
    }
186
187
    // If we still haven't found all of the inputs, look for the missing ones in the utxo set
188
26
    if (!coins.empty()) {
189
5
        FindCoins(node, coins);
190
14
        for (PSBTInput& input : psbtx.inputs) {
191
            // If there are still missing utxos, add them if they were found in the utxo set
192
14
            if (!input.non_witness_utxo) {
193
14
                const Coin& coin = coins.at(input.GetOutPoint());
194
14
                if (!coin.out.IsNull() && IsSegWitOutput(provider, coin.out.scriptPubKey)) {
195
12
                    input.witness_utxo = coin.out;
196
12
                }
197
14
            }
198
14
        }
199
5
    }
200
201
26
    std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbtx);
202
26
    if (!txdata_res) {
203
0
        throw JSONRPCPSBTError(common::PSBTError::INVALID_TX);
204
0
    }
205
26
    const PrecomputedTransactionData& txdata = *txdata_res;
206
207
57
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
208
38
        if (PSBTInputSigned(psbtx.inputs.at(i))) {
209
5
            continue;
210
5
        }
211
212
        // Update script/keypath information using descriptor data.
213
        // Note that SignPSBTInput does a lot more than just constructing ECDSA signatures.
214
        // We only actually care about those if our signing provider doesn't hide private
215
        // information, as is the case with `descriptorprocesspsbt`
216
        // Only error for mismatching sighash types as it is critical that the sighash to sign with matches the PSBT's
217
33
        const auto sign_result = SignPSBTInput(provider, psbtx, /*index=*/i, &txdata, {.sighash_type = sighash_type, .finalize = finalize}, /*out_sigdata=*/nullptr);
218
33
        if (!sign_result.has_value() && sign_result.error() == common::PSBTError::SIGHASH_MISMATCH) {
219
7
            throw JSONRPCPSBTError(common::PSBTError::SIGHASH_MISMATCH);
220
7
        }
221
33
    }
222
223
    // Update script/keypath information using descriptor data.
224
48
    for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
225
29
        UpdatePSBTOutput(provider, psbtx, i);
226
29
    }
227
228
19
    RemoveUnnecessaryTransactions(psbtx);
229
230
19
    return psbtx;
231
26
}
232
233
static RPCMethod getrawtransaction()
234
6.18k
{
235
6.18k
    const std::vector<RPCResult> verbosity_1_block{
236
6.18k
        {RPCResult::Type::BOOL, "in_active_chain", /*optional=*/true, "Whether specified block is in the active chain or not (only present with explicit \"blockhash\" argument)"},
237
6.18k
        {RPCResult::Type::STR_HEX, "blockhash", /*optional=*/true, "the block hash"},
238
6.18k
        {RPCResult::Type::NUM, "vsize_adjusted", /*optional=*/true, "Sigop-adjusted virtual size in bytes, present for mempool transactions."},
239
6.18k
        {RPCResult::Type::NUM, "confirmations", /*optional=*/true, "The confirmations"},
240
6.18k
        {RPCResult::Type::NUM_TIME, "blocktime", /*optional=*/true, "The block time expressed in " + UNIX_EPOCH_TIME},
241
6.18k
        {RPCResult::Type::NUM, "time", /*optional=*/true, "Same as \"blocktime\""},
242
6.18k
        {RPCResult::Type::STR_HEX, "hex", "The serialized, hex-encoded data for 'txid'"},
243
6.18k
    };
244
6.18k
    const auto v2_extras = Cat<std::vector<RPCResult>>(
245
6.18k
        std::vector<RPCResult>{{
246
6.18k
            RPCResult::Type::NUM, "fee", /*optional=*/true,
247
6.18k
            "transaction fee in " + CURRENCY_UNIT + ", omitted if block undo data is not available"
248
6.18k
        }},
249
6.18k
        TxDoc({.elision_mode = ElisionMode::Silent,
250
6.18k
               .prevout = true,
251
6.18k
               .prevout_optional = true,
252
6.18k
               .vin_inner_elision = "Same vin fields as verbosity = 1"}));
253
6.18k
    return RPCMethod{
254
6.18k
                "getrawtransaction",
255
256
6.18k
                "By default, this call only returns a transaction if it is in the mempool. If -txindex is enabled\n"
257
6.18k
                "and no blockhash argument is passed, it will return the transaction if it is in the mempool or any block.\n"
258
6.18k
                "If a blockhash argument is passed, it will return the transaction if\n"
259
6.18k
                "the specified block is available and the transaction is in that block.\n\n"
260
6.18k
                "Hint: Use gettransaction for wallet transactions.\n\n"
261
262
6.18k
                "If verbosity is 0 or omitted, returns the serialized transaction as a hex-encoded string.\n"
263
6.18k
                "If verbosity is 1, returns a JSON Object with information about the transaction.\n"
264
6.18k
                "If verbosity is 2, returns a JSON Object with information about the transaction, including fee and prevout information.",
265
6.18k
                {
266
6.18k
                    {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
267
6.18k
                    {"verbosity|verbose", RPCArg::Type::NUM, RPCArg::Default{0}, "0 for hex-encoded data, 1 for a JSON object, and 2 for JSON object with fee and prevout",
268
6.18k
                     RPCArgOptions{.skip_type_check = true}},
269
6.18k
                    {"blockhash", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "The block in which to look for the transaction"},
270
6.18k
                },
271
6.18k
                {
272
6.18k
                    RPCResult{"if verbosity is not set or set to 0",
273
6.18k
                         RPCResult::Type::STR, "data", "The serialized transaction as a hex-encoded string for 'txid'"
274
6.18k
                     },
275
6.18k
                     RPCResult{"if verbosity is set to 1",
276
6.18k
                         RPCResult::Type::OBJ, "", "",
277
6.18k
                         Cat<std::vector<RPCResult>>(
278
6.18k
                         verbosity_1_block,
279
6.18k
                         TxDoc({.txid_field_doc="The transaction id (same as provided)"})),
280
6.18k
                    },
281
6.18k
                    RPCResult{"for verbosity = 2", RPCResult::Type::OBJ, "", "",
282
6.18k
                    Cat(ElideGroup(verbosity_1_block, "Same output as verbosity = 1"), v2_extras)},
283
6.18k
                },
284
6.18k
                RPCExamples{
285
6.18k
                    HelpExampleCli("getrawtransaction", "\"mytxid\"")
286
6.18k
            + HelpExampleCli("getrawtransaction", "\"mytxid\" 1")
287
6.18k
            + HelpExampleRpc("getrawtransaction", "\"mytxid\", 1")
288
6.18k
            + HelpExampleCli("getrawtransaction", "\"mytxid\" 0 \"myblockhash\"")
289
6.18k
            + HelpExampleCli("getrawtransaction", "\"mytxid\" 1 \"myblockhash\"")
290
6.18k
            + HelpExampleCli("getrawtransaction", "\"mytxid\" 2 \"myblockhash\"")
291
6.18k
                },
292
6.18k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
293
6.18k
{
294
3.58k
    const NodeContext& node = EnsureAnyNodeContext(request.context);
295
3.58k
    ChainstateManager& chainman = EnsureChainman(node);
296
297
3.58k
    auto txid{Txid::FromUint256(ParseHashV(request.params[0], "parameter 1"))};
298
3.58k
    const CBlockIndex* blockindex = nullptr;
299
300
3.58k
    if (txid.ToUint256() == chainman.GetParams().GenesisBlock().hashMerkleRoot) {
301
        // Special exception for the genesis block coinbase transaction
302
1
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "The genesis block coinbase is not considered an ordinary transaction and cannot be retrieved");
303
1
    }
304
305
3.58k
    int verbosity{ParseVerbosity(request.params[1], /*default_verbosity=*/0, /*allow_bool=*/true)};
306
307
3.58k
    if (!request.params[2].isNull()) {
308
44
        LOCK(cs_main);
309
310
44
        uint256 blockhash = ParseHashV(request.params[2], "parameter 3");
311
44
        blockindex = chainman.m_blockman.LookupBlockIndex(blockhash);
312
44
        if (!blockindex) {
313
2
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found");
314
2
        }
315
44
    }
316
317
3.58k
    bool f_txindex_ready = false;
318
3.58k
    if (g_txindex && !blockindex) {
319
39
        f_txindex_ready = g_txindex->BlockUntilSyncedToCurrentChain();
320
39
    }
321
322
3.58k
    uint256 hash_block;
323
3.58k
    CTransactionRef tx;
324
3.58k
    try {
325
3.58k
        tx = GetTransaction(blockindex, node.mempool.get(), txid, chainman.m_blockman, hash_block);
326
3.58k
    } catch (const std::runtime_error&) {
327
3
        if (blockindex) WITH_LOCK(::cs_main, CheckBlockDataAvailability(chainman.m_blockman, *blockindex, /*check_for_undo=*/false));
328
3
        throw;
329
3
    }
330
3.56k
    if (!tx) {
331
10
        std::string errmsg;
332
10
        if (blockindex) {
333
2
            errmsg = "No such transaction found in the provided block";
334
8
        } else if (!g_txindex) {
335
8
            errmsg = "No such mempool transaction. Use -txindex or provide a block hash to enable blockchain transaction queries";
336
8
        } else if (!f_txindex_ready) {
337
0
            errmsg = "No such mempool transaction. Blockchain transactions are still in the process of being indexed";
338
0
        } else {
339
0
            errmsg = "No such mempool or blockchain transaction";
340
0
        }
341
10
        throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, errmsg + ". Use gettransaction for wallet transactions.");
342
10
    }
343
344
3.55k
    if (verbosity <= 0) {
345
55
        return EncodeHexTx(*tx);
346
55
    }
347
348
3.49k
    UniValue result(UniValue::VOBJ);
349
3.49k
    if (blockindex) {
350
31
        LOCK(cs_main);
351
31
        result.pushKV("in_active_chain", chainman.ActiveChain().Contains(*blockindex));
352
31
    }
353
    // If request is verbosity >= 1 but no blockhash was given, then look up the blockindex
354
3.49k
    if (request.params[2].isNull()) {
355
3.46k
        LOCK(cs_main);
356
3.46k
        blockindex = chainman.m_blockman.LookupBlockIndex(hash_block); // May be nullptr for mempool transactions
357
3.46k
    }
358
359
    // Add sigop-adjusted virtual size if the transaction exists in the mempool.
360
3.49k
    if (blockindex == nullptr && hash_block.IsNull() && node.mempool) {
361
3.44k
        auto info = node.mempool->info(tx->GetHash());
362
3.44k
        if (info.tx) {
363
3.44k
            result.pushKV("vsize_adjusted", info.vsize);
364
3.44k
        }
365
3.44k
    }
366
367
3.49k
    if (verbosity == 1) {
368
3.48k
        TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate());
369
3.48k
        return result;
370
3.48k
    }
371
372
7
    CBlockUndo blockUndo;
373
7
    CBlock block;
374
375
7
    if (tx->IsCoinBase() || !blockindex || WITH_LOCK(::cs_main, return !(blockindex->nStatus & BLOCK_HAVE_MASK))) {
376
2
        TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate());
377
2
        return result;
378
2
    }
379
5
    if (!chainman.m_blockman.ReadBlockUndo(blockUndo, *blockindex)) {
380
0
        throw JSONRPCError(RPC_INTERNAL_ERROR, "Undo data expected but can't be read. This could be due to disk corruption or a conflict with a pruning event.");
381
0
    }
382
5
    if (!chainman.m_blockman.ReadBlock(block, *blockindex)) {
383
0
        throw JSONRPCError(RPC_INTERNAL_ERROR, "Block data expected but can't be read. This could be due to disk corruption or a conflict with a pruning event.");
384
0
    }
385
386
5
    CTxUndo* undoTX {nullptr};
387
10
    auto it = std::find_if(block.vtx.begin(), block.vtx.end(), [tx](CTransactionRef t){ return t->Equals(*tx); });
388
5
    if (it != block.vtx.end()) {
389
        // -1 as blockundo does not have coinbase tx
390
5
        undoTX = &blockUndo.vtxundo.at(it - block.vtx.begin() - 1);
391
5
    }
392
5
    TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate(), undoTX, TxVerbosity::SHOW_DETAILS_AND_PREVOUT);
393
5
    return result;
394
5
},
395
6.18k
    };
396
6.18k
}
397
398
static RPCMethod createrawtransaction()
399
3.06k
{
400
3.06k
    return RPCMethod{
401
3.06k
        "createrawtransaction",
402
3.06k
        "Create a transaction spending the given inputs and creating new outputs.\n"
403
3.06k
                "Outputs can be addresses or data.\n"
404
3.06k
                "Returns hex-encoded raw transaction.\n"
405
3.06k
                "Note that the transaction's inputs are not signed, and\n"
406
3.06k
                "it is not stored in the wallet or transmitted to the network.\n",
407
3.06k
                CreateTxDoc(),
408
3.06k
                RPCResult{
409
3.06k
                    RPCResult::Type::STR_HEX, "transaction", "hex string of the transaction"
410
3.06k
                },
411
3.06k
                RPCExamples{
412
3.06k
                    HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"")
413
3.06k
            + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
414
3.06k
            + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"address\\\":0.01}]\"")
415
3.06k
            + HelpExampleRpc("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\", \"[{\\\"data\\\":\\\"00010203\\\"}]\"")
416
3.06k
                },
417
3.06k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
418
3.06k
{
419
465
    std::optional<bool> rbf;
420
465
    if (!request.params[3].isNull()) {
421
10
        rbf = request.params[3].get_bool();
422
10
    }
423
465
    CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf, self.Arg<uint32_t>("version"));
424
425
465
    return EncodeHexTx(CTransaction(rawTx));
426
465
},
427
3.06k
    };
428
3.06k
}
429
430
static RPCMethod decoderawtransaction()
431
6.68k
{
432
6.68k
    return RPCMethod{"decoderawtransaction",
433
6.68k
                "Return a JSON object representing the serialized, hex-encoded transaction.",
434
6.68k
                {
435
6.68k
                    {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction hex string"},
436
6.68k
                    {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
437
6.68k
                        "If iswitness is not present, heuristic tests will be used in decoding.\n"
438
6.68k
                        "If true, only witness deserialization will be tried.\n"
439
6.68k
                        "If false, only non-witness deserialization will be tried.\n"
440
6.68k
                        "This boolean should reflect whether the transaction has inputs\n"
441
6.68k
                        "(e.g. fully valid, or on-chain transactions), if known by the caller."
442
6.68k
                    },
443
6.68k
                },
444
6.68k
                RPCResult{
445
6.68k
                    RPCResult::Type::OBJ, "", "",
446
6.68k
                    TxDoc(),
447
6.68k
                },
448
6.68k
                RPCExamples{
449
6.68k
                    HelpExampleCli("decoderawtransaction", "\"hexstring\"")
450
6.68k
            + HelpExampleRpc("decoderawtransaction", "\"hexstring\"")
451
6.68k
                },
452
6.68k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
453
6.68k
{
454
4.08k
    CMutableTransaction mtx;
455
456
4.08k
    bool try_witness = request.params[1].isNull() ? true : request.params[1].get_bool();
457
4.08k
    bool try_no_witness = request.params[1].isNull() ? true : !request.params[1].get_bool();
458
459
4.08k
    if (!DecodeHexTx(mtx, request.params[0].get_str(), try_no_witness, try_witness)) {
460
7
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
461
7
    }
462
463
4.07k
    UniValue result(UniValue::VOBJ);
464
4.07k
    TxToUniv(CTransaction(std::move(mtx)), /*block_hash=*/uint256(), /*entry=*/result, /*include_hex=*/false);
465
466
4.07k
    return result;
467
4.08k
},
468
6.68k
    };
469
6.68k
}
470
471
static RPCMethod decodescript()
472
2.62k
{
473
2.62k
    return RPCMethod{
474
2.62k
        "decodescript",
475
2.62k
        "Decode a hex-encoded script.\n",
476
2.62k
        {
477
2.62k
            {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "the hex-encoded script"},
478
2.62k
        },
479
2.62k
        RPCResult{
480
2.62k
            RPCResult::Type::OBJ, "", "",
481
2.62k
            {
482
2.62k
                {RPCResult::Type::STR, "asm", "Disassembly of the script"},
483
2.62k
                {RPCResult::Type::STR, "desc", "Inferred descriptor for the script"},
484
2.62k
                {RPCResult::Type::STR, "type", "The output type (e.g. " + GetAllOutputTypes() + ")"},
485
2.62k
                {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
486
2.62k
                {RPCResult::Type::STR, "p2sh", /*optional=*/true,
487
2.62k
                 "address of P2SH script wrapping this redeem script (not returned for types that should not be wrapped)"},
488
2.62k
                {RPCResult::Type::OBJ, "segwit", /*optional=*/true,
489
2.62k
                 "Result of a witness output script wrapping this redeem script (not returned for types that should not be wrapped)",
490
2.62k
                 {
491
2.62k
                     {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
492
2.62k
                     {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
493
2.62k
                     {RPCResult::Type::STR, "type", "The type of the output script (e.g. witness_v0_keyhash or witness_v0_scripthash)"},
494
2.62k
                     {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
495
2.62k
                     {RPCResult::Type::STR, "desc", "Inferred descriptor for the script"},
496
2.62k
                     {RPCResult::Type::STR, "p2sh-segwit", "address of the P2SH script wrapping this witness redeem script"},
497
2.62k
                 }},
498
2.62k
            },
499
2.62k
        },
500
2.62k
        RPCExamples{
501
2.62k
            HelpExampleCli("decodescript", "\"hexstring\"")
502
2.62k
          + HelpExampleRpc("decodescript", "\"hexstring\"")
503
2.62k
        },
504
2.62k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
505
2.62k
{
506
31
    UniValue r(UniValue::VOBJ);
507
31
    CScript script;
508
31
    if (request.params[0].get_str().size() > 0){
509
31
        std::vector<unsigned char> scriptData(ParseHexV(request.params[0], "argument"));
510
31
        script = CScript(scriptData.begin(), scriptData.end());
511
31
    } else {
512
        // Empty scripts are valid
513
0
    }
514
31
    ScriptToUniv(script, /*out=*/r, /*include_hex=*/false, /*include_address=*/true);
515
516
31
    std::vector<std::vector<unsigned char>> solutions_data;
517
31
    const TxoutType which_type{Solver(script, solutions_data)};
518
519
31
    const bool can_wrap{[&] {
520
31
        switch (which_type) {
521
2
        case TxoutType::MULTISIG:
522
15
        case TxoutType::NONSTANDARD:
523
17
        case TxoutType::PUBKEY:
524
18
        case TxoutType::PUBKEYHASH:
525
19
        case TxoutType::WITNESS_V0_KEYHASH:
526
21
        case TxoutType::WITNESS_V0_SCRIPTHASH:
527
            // Can be wrapped if the checks below pass
528
21
            break;
529
2
        case TxoutType::NULL_DATA:
530
4
        case TxoutType::SCRIPTHASH:
531
5
        case TxoutType::WITNESS_UNKNOWN:
532
9
        case TxoutType::WITNESS_V1_TAPROOT:
533
10
        case TxoutType::ANCHOR:
534
            // Should not be wrapped
535
10
            return false;
536
31
        } // no default case, so the compiler can warn about missing cases
537
21
        if (!script.HasValidOps() || script.IsUnspendable()) {
538
3
            return false;
539
3
        }
540
112
        for (CScript::const_iterator it{script.begin()}; it != script.end();) {
541
95
            opcodetype op;
542
95
            CHECK_NONFATAL(script.GetOp(it, op));
543
95
            if (op == OP_CHECKSIGADD || IsOpSuccess(op)) {
544
1
                return false;
545
1
            }
546
95
        }
547
17
        return true;
548
18
    }()};
549
550
31
    if (can_wrap) {
551
17
        r.pushKV("p2sh", EncodeDestination(ScriptHash(script)));
552
        // P2SH and witness programs cannot be wrapped in P2WSH, if this script
553
        // is a witness program, don't return addresses for a segwit programs.
554
17
        const bool can_wrap_P2WSH{[&] {
555
17
            switch (which_type) {
556
2
            case TxoutType::MULTISIG:
557
4
            case TxoutType::PUBKEY:
558
            // Uncompressed pubkeys cannot be used with segwit checksigs.
559
            // If the script contains an uncompressed pubkey, skip encoding of a segwit program.
560
10
                for (const auto& solution : solutions_data) {
561
10
                    if ((solution.size() != 1) && !CPubKey(solution).IsCompressed()) {
562
2
                        return false;
563
2
                    }
564
10
                }
565
2
                return true;
566
9
            case TxoutType::NONSTANDARD:
567
10
            case TxoutType::PUBKEYHASH:
568
                // Can be P2WSH wrapped
569
10
                return true;
570
0
            case TxoutType::NULL_DATA:
571
0
            case TxoutType::SCRIPTHASH:
572
0
            case TxoutType::WITNESS_UNKNOWN:
573
1
            case TxoutType::WITNESS_V0_KEYHASH:
574
3
            case TxoutType::WITNESS_V0_SCRIPTHASH:
575
3
            case TxoutType::WITNESS_V1_TAPROOT:
576
3
            case TxoutType::ANCHOR:
577
                // Should not be wrapped
578
3
                return false;
579
17
            } // no default case, so the compiler can warn about missing cases
580
0
            NONFATAL_UNREACHABLE();
581
0
        }()};
582
17
        if (can_wrap_P2WSH) {
583
12
            UniValue sr(UniValue::VOBJ);
584
12
            CScript segwitScr;
585
12
            FlatSigningProvider provider;
586
12
            if (which_type == TxoutType::PUBKEY) {
587
1
                segwitScr = GetScriptForDestination(WitnessV0KeyHash(Hash160(solutions_data[0])));
588
11
            } else if (which_type == TxoutType::PUBKEYHASH) {
589
1
                segwitScr = GetScriptForDestination(WitnessV0KeyHash(uint160{solutions_data[0]}));
590
10
            } else {
591
                // Scripts that are not fit for P2WPKH are encoded as P2WSH.
592
10
                provider.scripts[CScriptID(script)] = script;
593
10
                segwitScr = GetScriptForDestination(WitnessV0ScriptHash(script));
594
10
            }
595
12
            ScriptToUniv(segwitScr, /*out=*/sr, /*include_hex=*/true, /*include_address=*/true, /*provider=*/&provider);
596
12
            sr.pushKV("p2sh-segwit", EncodeDestination(ScriptHash(segwitScr)));
597
12
            r.pushKV("segwit", std::move(sr));
598
12
        }
599
17
    }
600
601
31
    return r;
602
31
},
603
2.62k
    };
604
2.62k
}
605
606
static RPCMethod combinerawtransaction()
607
2.64k
{
608
2.64k
    return RPCMethod{
609
2.64k
        "combinerawtransaction",
610
2.64k
        "Combine multiple partially signed transactions into one transaction.\n"
611
2.64k
                "The combined transaction may be another partially signed transaction or a \n"
612
2.64k
                "fully signed transaction.",
613
2.64k
                {
614
2.64k
                    {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The hex strings of partially signed transactions",
615
2.64k
                        {
616
2.64k
                            {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "A hex-encoded raw transaction"},
617
2.64k
                        },
618
2.64k
                        },
619
2.64k
                },
620
2.64k
                RPCResult{
621
2.64k
                    RPCResult::Type::STR, "", "The hex-encoded raw transaction with signature(s)"
622
2.64k
                },
623
2.64k
                RPCExamples{
624
2.64k
                    HelpExampleCli("combinerawtransaction", R"('["myhex1", "myhex2", "myhex3"]')")
625
2.64k
                },
626
2.64k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
627
2.64k
{
628
629
52
    UniValue txs = request.params[0].get_array();
630
631
    // Can't merge < 2 items
632
52
    if (txs.size() < 2) {
633
2
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transactions. At least two transactions required.");
634
2
    }
635
636
50
    std::vector<CMutableTransaction> txVariants(txs.size());
637
638
149
    for (unsigned int idx = 0; idx < txs.size(); idx++) {
639
100
        if (!DecodeHexTx(txVariants[idx], txs[idx].get_str())) {
640
1
            throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed for tx %d. Make sure the tx has at least one input.", idx));
641
1
        }
642
100
    }
643
644
49
    { // Test Tx relation for mergeability. Strip scriptSigs and scriptWitnesses to facilitate txId comparison
645
49
        std::vector<CMutableTransaction> tx_variants_copy(txVariants);
646
49
        Txid first_txid{};
647
141
        for (unsigned int k{0}; k < tx_variants_copy.size(); ++k) {
648
            // Remove all scriptSigs and scriptWitnesses from inputs
649
98
            for (CTxIn& input : tx_variants_copy[k].vin) {
650
98
                input.scriptSig.clear();
651
98
                input.scriptWitness.SetNull();
652
98
            }
653
98
            if (k == 0) {
654
49
                first_txid = tx_variants_copy[k].GetHash();
655
49
            } else if (first_txid != tx_variants_copy[k].GetHash()) {
656
6
                throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Transaction number %d not compatible with first transaction", k+1));
657
6
            }
658
98
        }
659
49
    }
660
661
    // mergedTx will end up with all the signatures; it
662
    // starts as a clone of the rawtx:
663
43
    CMutableTransaction mergedTx(txVariants[0]);
664
665
    // Fetch previous transactions (inputs):
666
43
    CCoinsViewCache view{&CoinsViewEmpty::Get()};
667
43
    {
668
43
        NodeContext& node = EnsureAnyNodeContext(request.context);
669
43
        const CTxMemPool& mempool = EnsureMemPool(node);
670
43
        ChainstateManager& chainman = EnsureChainman(node);
671
43
        LOCK2(cs_main, mempool.cs);
672
43
        CCoinsViewCache &viewChain = chainman.ActiveChainstate().CoinsTip();
673
43
        CCoinsViewMemPool viewMempool(&viewChain, mempool);
674
43
        view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
675
676
43
        for (const CTxIn& txin : mergedTx.vin) {
677
43
            view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
678
43
        }
679
680
43
        view.SetBackend(CoinsViewEmpty::Get()); // switch back to avoid locking mempool for too long
681
43
    }
682
683
    // Use CTransaction for the constant parts of the
684
    // transaction to avoid rehashing.
685
43
    const CTransaction txConst(mergedTx);
686
    // Sign what we can:
687
65
    for (unsigned int i = 0; i < mergedTx.vin.size(); i++) {
688
43
        CTxIn& txin = mergedTx.vin[i];
689
43
        const Coin& coin = view.AccessCoin(txin.prevout);
690
43
        if (coin.IsSpent()) {
691
21
            throw JSONRPCError(RPC_VERIFY_ERROR, "Input not found or already spent");
692
21
        }
693
22
        SignatureData sigdata;
694
695
        // ... and merge in other signatures:
696
44
        for (const CMutableTransaction& txv : txVariants) {
697
44
            if (txv.vin.size() > i) {
698
44
                sigdata.MergeSignatureData(DataFromTransaction(txv, i, coin.out));
699
44
            }
700
44
        }
701
22
        ProduceSignature(DUMMY_SIGNING_PROVIDER, MutableTransactionSignatureCreator(mergedTx, i, coin.out.nValue, {.sighash_type = SIGHASH_ALL}), coin.out.scriptPubKey, sigdata);
702
703
22
        UpdateInput(txin, sigdata);
704
22
    }
705
706
22
    return EncodeHexTx(CTransaction(mergedTx));
707
43
},
708
2.64k
    };
709
2.64k
}
710
711
static RPCMethod signrawtransactionwithkey()
712
2.79k
{
713
2.79k
    return RPCMethod{
714
2.79k
        "signrawtransactionwithkey",
715
2.79k
        "Sign inputs for raw transaction (serialized, hex-encoded).\n"
716
2.79k
                "The second argument is an array of base58-encoded private\n"
717
2.79k
                "keys that will be the only keys used to sign the transaction.\n"
718
2.79k
                "The third optional argument (may be null) is an array of previous transaction outputs that\n"
719
2.79k
                "this transaction depends on but may not yet be in the block chain.\n",
720
2.79k
                {
721
2.79k
                    {"hexstring", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction hex string"},
722
2.79k
                    {"privkeys", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base58-encoded private keys for signing",
723
2.79k
                        {
724
2.79k
                            {"privatekey", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "private key in base58-encoding"},
725
2.79k
                        },
726
2.79k
                        },
727
2.79k
                    {"prevtxs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "The previous dependent transaction outputs",
728
2.79k
                        {
729
2.79k
                            {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
730
2.79k
                                {
731
2.79k
                                    {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
732
2.79k
                                    {"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
733
2.79k
                                    {"scriptPubKey", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "output script"},
734
2.79k
                                    {"redeemScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2SH) redeem script"},
735
2.79k
                                    {"witnessScript", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED, "(required for P2WSH or P2SH-P2WSH) witness script"},
736
2.79k
                                    {"amount", RPCArg::Type::AMOUNT, RPCArg::Optional::OMITTED, "(required for Segwit inputs) the amount spent"},
737
2.79k
                                },
738
2.79k
                                },
739
2.79k
                        },
740
2.79k
                        },
741
2.79k
                    {"sighashtype", RPCArg::Type::STR, RPCArg::DefaultHint{"DEFAULT for Taproot, ALL otherwise"}, "The signature hash type. Must be one of:\n"
742
2.79k
            "       \"DEFAULT\"\n"
743
2.79k
            "       \"ALL\"\n"
744
2.79k
            "       \"NONE\"\n"
745
2.79k
            "       \"SINGLE\"\n"
746
2.79k
            "       \"ALL|ANYONECANPAY\"\n"
747
2.79k
            "       \"NONE|ANYONECANPAY\"\n"
748
2.79k
            "       \"SINGLE|ANYONECANPAY\"\n"
749
2.79k
                    },
750
2.79k
                },
751
2.79k
                RPCResult{
752
2.79k
                    RPCResult::Type::OBJ, "", "",
753
2.79k
                    {
754
2.79k
                        {RPCResult::Type::STR_HEX, "hex", "The hex-encoded raw transaction with signature(s)"},
755
2.79k
                        {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
756
2.79k
                        {RPCResult::Type::ARR, "errors", /*optional=*/true, "Script verification errors (if there are any)",
757
2.79k
                        {
758
2.79k
                            {RPCResult::Type::OBJ, "", "",
759
2.79k
                            {
760
2.79k
                                {RPCResult::Type::STR_HEX, "txid", "The hash of the referenced, previous transaction"},
761
2.79k
                                {RPCResult::Type::NUM, "vout", "The index of the output to spent and used as input"},
762
2.79k
                                {RPCResult::Type::ARR, "witness", "",
763
2.79k
                                {
764
2.79k
                                    {RPCResult::Type::STR_HEX, "witness", ""},
765
2.79k
                                }},
766
2.79k
                                {RPCResult::Type::STR_HEX, "scriptSig", "The hex-encoded signature script"},
767
2.79k
                                {RPCResult::Type::NUM, "sequence", "Script sequence number"},
768
2.79k
                                {RPCResult::Type::STR, "error", "Verification or signing error related to the input"},
769
2.79k
                            }},
770
2.79k
                        }},
771
2.79k
                    }
772
2.79k
                },
773
2.79k
                RPCExamples{
774
2.79k
                    HelpExampleCli("signrawtransactionwithkey", "\"myhex\" \"[\\\"key1\\\",\\\"key2\\\"]\"")
775
2.79k
            + HelpExampleRpc("signrawtransactionwithkey", "\"myhex\", \"[\\\"key1\\\",\\\"key2\\\"]\"")
776
2.79k
                },
777
2.79k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
778
2.79k
{
779
199
    CMutableTransaction mtx;
780
199
    if (!DecodeHexTx(mtx, request.params[0].get_str())) {
781
1
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input.");
782
1
    }
783
784
198
    FlatSigningProvider keystore;
785
198
    const UniValue& keys = request.params[1].get_array();
786
1.18k
    for (unsigned int idx = 0; idx < keys.size(); ++idx) {
787
984
        UniValue k = keys[idx];
788
984
        CKey key = DecodeSecret(k.get_str());
789
984
        if (!key.IsValid()) {
790
1
            throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
791
1
        }
792
793
983
        CPubKey pubkey = key.GetPubKey();
794
983
        CKeyID key_id = pubkey.GetID();
795
983
        keystore.pubkeys.emplace(key_id, pubkey);
796
983
        keystore.keys.emplace(key_id, key);
797
983
    }
798
799
    // Fetch previous transactions (inputs):
800
197
    std::map<COutPoint, Coin> coins;
801
599
    for (const CTxIn& txin : mtx.vin) {
802
599
        coins[txin.prevout]; // Create empty map entry keyed by prevout.
803
599
    }
804
197
    NodeContext& node = EnsureAnyNodeContext(request.context);
805
197
    FindCoins(node, coins);
806
807
    // Parse the prevtxs array
808
197
    ParsePrevouts(request.params[2], &keystore, coins);
809
810
197
    UniValue result(UniValue::VOBJ);
811
197
    SignTransaction(mtx, &keystore, coins, request.params[3], result);
812
197
    return result;
813
198
},
814
2.79k
    };
815
2.79k
}
816
817
const RPCResult& DecodePSBTInputs()
818
3.16k
{
819
3.16k
    static const RPCResult decodepsbt_inputs{
820
3.16k
        RPCResult::Type::ARR, "inputs", "",
821
3.16k
        {
822
3.16k
            {RPCResult::Type::OBJ, "", "",
823
3.16k
            {
824
3.16k
                {RPCResult::Type::OBJ, "non_witness_utxo", /*optional=*/true, "Decoded network transaction for non-witness UTXOs",
825
3.16k
                    TxDoc({.elision_mode = ElisionMode::WithSummary, .elision_summary = "The layout is the same as the output of decoderawtransaction."})
826
3.16k
                },
827
3.16k
                {RPCResult::Type::OBJ, "witness_utxo", /*optional=*/true, "Transaction output for witness UTXOs",
828
3.16k
                {
829
3.16k
                    {RPCResult::Type::NUM, "amount", "The value in " + CURRENCY_UNIT},
830
3.16k
                    {RPCResult::Type::OBJ, "scriptPubKey", "",
831
3.16k
                    {
832
3.16k
                        {RPCResult::Type::STR, "asm", "Disassembly of the output script"},
833
3.16k
                        {RPCResult::Type::STR, "desc", "Inferred descriptor for the output"},
834
3.16k
                        {RPCResult::Type::STR_HEX, "hex", "The raw output script bytes, hex-encoded"},
835
3.16k
                        {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
836
3.16k
                        {RPCResult::Type::STR, "address", /*optional=*/true, "The Bitcoin address (only if a well-defined address exists)"},
837
3.16k
                    }},
838
3.16k
                }},
839
3.16k
                {RPCResult::Type::OBJ_DYN, "partial_signatures", /*optional=*/true, "",
840
3.16k
                {
841
3.16k
                    {RPCResult::Type::STR, "pubkey", "The public key and signature that corresponds to it."},
842
3.16k
                }},
843
3.16k
                {RPCResult::Type::STR, "sighash", /*optional=*/true, "The sighash type to be used"},
844
3.16k
                {RPCResult::Type::OBJ, "redeem_script", /*optional=*/true, "",
845
3.16k
                {
846
3.16k
                    {RPCResult::Type::STR, "asm", "Disassembly of the redeem script"},
847
3.16k
                    {RPCResult::Type::STR_HEX, "hex", "The raw redeem script bytes, hex-encoded"},
848
3.16k
                    {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
849
3.16k
                }},
850
3.16k
                {RPCResult::Type::OBJ, "witness_script", /*optional=*/true, "",
851
3.16k
                {
852
3.16k
                    {RPCResult::Type::STR, "asm", "Disassembly of the witness script"},
853
3.16k
                    {RPCResult::Type::STR_HEX, "hex", "The raw witness script bytes, hex-encoded"},
854
3.16k
                    {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
855
3.16k
                }},
856
3.16k
                {RPCResult::Type::ARR, "bip32_derivs", /*optional=*/true, "",
857
3.16k
                {
858
3.16k
                    {RPCResult::Type::OBJ, "", "",
859
3.16k
                    {
860
3.16k
                        {RPCResult::Type::STR, "pubkey", "The public key with the derivation path as the value."},
861
3.16k
                        {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
862
3.16k
                        {RPCResult::Type::STR, "path", "The path"},
863
3.16k
                    }},
864
3.16k
                }},
865
3.16k
                {RPCResult::Type::OBJ, "final_scriptSig", /*optional=*/true, "",
866
3.16k
                {
867
3.16k
                    {RPCResult::Type::STR, "asm", "Disassembly of the final signature script"},
868
3.16k
                    {RPCResult::Type::STR_HEX, "hex", "The raw final signature script bytes, hex-encoded"},
869
3.16k
                }},
870
3.16k
                {RPCResult::Type::ARR, "final_scriptwitness", /*optional=*/true, "",
871
3.16k
                {
872
3.16k
                    {RPCResult::Type::STR_HEX, "", "hex-encoded witness data (if any)"},
873
3.16k
                }},
874
3.16k
                {RPCResult::Type::OBJ_DYN, "ripemd160_preimages", /*optional=*/ true, "",
875
3.16k
                {
876
3.16k
                    {RPCResult::Type::STR, "hash", "The hash and preimage that corresponds to it."},
877
3.16k
                }},
878
3.16k
                {RPCResult::Type::OBJ_DYN, "sha256_preimages", /*optional=*/ true, "",
879
3.16k
                {
880
3.16k
                    {RPCResult::Type::STR, "hash", "The hash and preimage that corresponds to it."},
881
3.16k
                }},
882
3.16k
                {RPCResult::Type::OBJ_DYN, "hash160_preimages", /*optional=*/ true, "",
883
3.16k
                {
884
3.16k
                    {RPCResult::Type::STR, "hash", "The hash and preimage that corresponds to it."},
885
3.16k
                }},
886
3.16k
                {RPCResult::Type::OBJ_DYN, "hash256_preimages", /*optional=*/ true, "",
887
3.16k
                {
888
3.16k
                    {RPCResult::Type::STR, "hash", "The hash and preimage that corresponds to it."},
889
3.16k
                }},
890
3.16k
                {RPCResult::Type::STR_HEX, "previous_txid", /*optional=*/true, "TXID of the transaction containing the output being spent by this input"},
891
3.16k
                {RPCResult::Type::NUM, "previous_vout", /*optional=*/true, "Index of the output being spent"},
892
3.16k
                {RPCResult::Type::NUM, "sequence", /*optional=*/true, "Sequence number for this input"},
893
3.16k
                {RPCResult::Type::NUM, "time_locktime", /*optional=*/true, "Time-based locktime required for this input"},
894
3.16k
                {RPCResult::Type::NUM, "height_locktime", /*optional=*/true, "Height-based locktime required for this input"},
895
3.16k
                {RPCResult::Type::STR_HEX, "taproot_key_path_sig", /*optional=*/ true, "hex-encoded signature for the Taproot key path spend"},
896
3.16k
                {RPCResult::Type::ARR, "taproot_script_path_sigs", /*optional=*/ true, "",
897
3.16k
                {
898
3.16k
                    {RPCResult::Type::OBJ, "signature", /*optional=*/ true, "The signature for the pubkey and leaf hash combination",
899
3.16k
                    {
900
3.16k
                        {RPCResult::Type::STR, "pubkey", "The x-only pubkey for this signature"},
901
3.16k
                        {RPCResult::Type::STR, "leaf_hash", "The leaf hash for this signature"},
902
3.16k
                        {RPCResult::Type::STR, "sig", "The signature itself"},
903
3.16k
                    }},
904
3.16k
                }},
905
3.16k
                {RPCResult::Type::ARR, "taproot_scripts", /*optional=*/ true, "",
906
3.16k
                {
907
3.16k
                    {RPCResult::Type::OBJ, "", "",
908
3.16k
                    {
909
3.16k
                        {RPCResult::Type::STR_HEX, "script", "A leaf script"},
910
3.16k
                        {RPCResult::Type::NUM, "leaf_ver", "The version number for the leaf script"},
911
3.16k
                        {RPCResult::Type::ARR, "control_blocks", "The control blocks for this script",
912
3.16k
                        {
913
3.16k
                            {RPCResult::Type::STR_HEX, "control_block", "A hex-encoded control block for this script"},
914
3.16k
                        }},
915
3.16k
                    }},
916
3.16k
                }},
917
3.16k
                {RPCResult::Type::ARR, "taproot_bip32_derivs", /*optional=*/ true, "",
918
3.16k
                {
919
3.16k
                    {RPCResult::Type::OBJ, "", "",
920
3.16k
                    {
921
3.16k
                        {RPCResult::Type::STR, "pubkey", "The x-only public key this path corresponds to"},
922
3.16k
                        {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
923
3.16k
                        {RPCResult::Type::STR, "path", "The path"},
924
3.16k
                        {RPCResult::Type::ARR, "leaf_hashes", "The hashes of the leaves this pubkey appears in",
925
3.16k
                        {
926
3.16k
                            {RPCResult::Type::STR_HEX, "hash", "The hash of a leaf this pubkey appears in"},
927
3.16k
                        }},
928
3.16k
                    }},
929
3.16k
                }},
930
3.16k
                {RPCResult::Type::STR_HEX, "taproot_internal_key", /*optional=*/ true, "The hex-encoded Taproot x-only internal key"},
931
3.16k
                {RPCResult::Type::STR_HEX, "taproot_merkle_root", /*optional=*/ true, "The hex-encoded Taproot merkle root"},
932
3.16k
                {RPCResult::Type::ARR, "musig2_participant_pubkeys", /*optional=*/true, "",
933
3.16k
                {
934
3.16k
                    {RPCResult::Type::OBJ, "", "",
935
3.16k
                    {
936
3.16k
                        {RPCResult::Type::STR_HEX, "aggregate_pubkey", "The compressed aggregate public key for which the participants create."},
937
3.16k
                        {RPCResult::Type::ARR, "participant_pubkeys", "",
938
3.16k
                        {
939
3.16k
                            {RPCResult::Type::STR_HEX, "pubkey", "The compressed public keys that are aggregated for aggregate_pubkey."},
940
3.16k
                        }},
941
3.16k
                    }},
942
3.16k
                }},
943
3.16k
                {RPCResult::Type::ARR, "musig2_pubnonces", /*optional=*/true, "",
944
3.16k
                {
945
3.16k
                    {RPCResult::Type::OBJ, "", "",
946
3.16k
                    {
947
3.16k
                        {RPCResult::Type::STR_HEX, "participant_pubkey", "The compressed public key of the participant that created this pubnonce."},
948
3.16k
                        {RPCResult::Type::STR_HEX, "aggregate_pubkey", "The compressed aggregate public key for which this pubnonce is for."},
949
3.16k
                        {RPCResult::Type::STR_HEX, "leaf_hash", /*optional=*/true, "The hash of the leaf script that contains the aggregate pubkey being signed for. Omitted when signing for the internal key."},
950
3.16k
                        {RPCResult::Type::STR_HEX, "pubnonce", "The public nonce itself."},
951
3.16k
                    }},
952
3.16k
                }},
953
3.16k
                {RPCResult::Type::ARR, "musig2_partial_sigs", /*optional=*/true, "",
954
3.16k
                {
955
3.16k
                    {RPCResult::Type::OBJ, "", "",
956
3.16k
                    {
957
3.16k
                        {RPCResult::Type::STR_HEX, "participant_pubkey", "The compressed public key of the participant that created this partial signature."},
958
3.16k
                        {RPCResult::Type::STR_HEX, "aggregate_pubkey", "The compressed aggregate public key for which this partial signature is for."},
959
3.16k
                        {RPCResult::Type::STR_HEX, "leaf_hash", /*optional=*/true, "The hash of the leaf script that contains the aggregate pubkey being signed for. Omitted when signing for the internal key."},
960
3.16k
                        {RPCResult::Type::STR_HEX, "partial_sig", "The partial signature itself."},
961
3.16k
                    }},
962
3.16k
                }},
963
3.16k
                {RPCResult::Type::OBJ_DYN, "unknown", /*optional=*/ true, "The unknown input fields",
964
3.16k
                {
965
3.16k
                    {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
966
3.16k
                }},
967
3.16k
                {RPCResult::Type::ARR, "proprietary", /*optional=*/true, "The input proprietary map",
968
3.16k
                {
969
3.16k
                    {RPCResult::Type::OBJ, "", "",
970
3.16k
                    {
971
3.16k
                        {RPCResult::Type::STR_HEX, "identifier", "The hex string for the proprietary identifier"},
972
3.16k
                        {RPCResult::Type::NUM, "subtype", "The number for the subtype"},
973
3.16k
                        {RPCResult::Type::STR_HEX, "key", "The hex for the key"},
974
3.16k
                        {RPCResult::Type::STR_HEX, "value", "The hex for the value"},
975
3.16k
                    }},
976
3.16k
                }},
977
3.16k
            }},
978
3.16k
        }
979
3.16k
    };
980
3.16k
    return decodepsbt_inputs;
981
3.16k
}
982
983
const RPCResult& DecodePSBTOutputs()
984
3.16k
{
985
3.16k
    static const RPCResult decodepsbt_outputs{
986
3.16k
        RPCResult::Type::ARR, "outputs", "",
987
3.16k
        {
988
3.16k
            {RPCResult::Type::OBJ, "", "",
989
3.16k
            {
990
3.16k
                {RPCResult::Type::OBJ, "redeem_script", /*optional=*/true, "",
991
3.16k
                {
992
3.16k
                    {RPCResult::Type::STR, "asm", "Disassembly of the redeem script"},
993
3.16k
                    {RPCResult::Type::STR_HEX, "hex", "The raw redeem script bytes, hex-encoded"},
994
3.16k
                    {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
995
3.16k
                }},
996
3.16k
                {RPCResult::Type::OBJ, "witness_script", /*optional=*/true, "",
997
3.16k
                {
998
3.16k
                    {RPCResult::Type::STR, "asm", "Disassembly of the witness script"},
999
3.16k
                    {RPCResult::Type::STR_HEX, "hex", "The raw witness script bytes, hex-encoded"},
1000
3.16k
                    {RPCResult::Type::STR, "type", "The type, eg 'pubkeyhash'"},
1001
3.16k
                }},
1002
3.16k
                {RPCResult::Type::ARR, "bip32_derivs", /*optional=*/true, "",
1003
3.16k
                {
1004
3.16k
                    {RPCResult::Type::OBJ, "", "",
1005
3.16k
                    {
1006
3.16k
                        {RPCResult::Type::STR, "pubkey", "The public key this path corresponds to"},
1007
3.16k
                        {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
1008
3.16k
                        {RPCResult::Type::STR, "path", "The path"},
1009
3.16k
                    }},
1010
3.16k
                }},
1011
3.16k
                {RPCResult::Type::NUM, "amount", /* optional=*/ true, "The amount (nValue) for this output"},
1012
3.16k
                {RPCResult::Type::OBJ, "script", /* optional=*/ true, "The output script (scriptPubKey) for this output",
1013
3.16k
                    ElideGroup(ScriptPubKeyDoc(), "The layout is the same as the output of scriptPubKeys in decoderawtransaction."),
1014
3.16k
                },
1015
3.16k
                {RPCResult::Type::STR_HEX, "taproot_internal_key", /*optional=*/ true, "The hex-encoded Taproot x-only internal key"},
1016
3.16k
                {RPCResult::Type::ARR, "taproot_tree", /*optional=*/ true, "The tuples that make up the Taproot tree, in depth first search order",
1017
3.16k
                {
1018
3.16k
                    {RPCResult::Type::OBJ, "tuple", /*optional=*/ true, "A single leaf script in the taproot tree",
1019
3.16k
                    {
1020
3.16k
                        {RPCResult::Type::NUM, "depth", "The depth of this element in the tree"},
1021
3.16k
                        {RPCResult::Type::NUM, "leaf_ver", "The version of this leaf"},
1022
3.16k
                        {RPCResult::Type::STR, "script", "The hex-encoded script itself"},
1023
3.16k
                    }},
1024
3.16k
                }},
1025
3.16k
                {RPCResult::Type::ARR, "taproot_bip32_derivs", /*optional=*/ true, "",
1026
3.16k
                {
1027
3.16k
                    {RPCResult::Type::OBJ, "", "",
1028
3.16k
                    {
1029
3.16k
                        {RPCResult::Type::STR, "pubkey", "The x-only public key this path corresponds to"},
1030
3.16k
                        {RPCResult::Type::STR, "master_fingerprint", "The fingerprint of the master key"},
1031
3.16k
                        {RPCResult::Type::STR, "path", "The path"},
1032
3.16k
                        {RPCResult::Type::ARR, "leaf_hashes", "The hashes of the leaves this pubkey appears in",
1033
3.16k
                        {
1034
3.16k
                            {RPCResult::Type::STR_HEX, "hash", "The hash of a leaf this pubkey appears in"},
1035
3.16k
                        }},
1036
3.16k
                    }},
1037
3.16k
                }},
1038
3.16k
                {RPCResult::Type::ARR, "musig2_participant_pubkeys", /*optional=*/true, "",
1039
3.16k
                {
1040
3.16k
                    {RPCResult::Type::OBJ, "", "",
1041
3.16k
                    {
1042
3.16k
                        {RPCResult::Type::STR_HEX, "aggregate_pubkey", "The compressed aggregate public key for which the participants create."},
1043
3.16k
                        {RPCResult::Type::ARR, "participant_pubkeys", "",
1044
3.16k
                        {
1045
3.16k
                            {RPCResult::Type::STR_HEX, "pubkey", "The compressed public keys that are aggregated for aggregate_pubkey."},
1046
3.16k
                        }},
1047
3.16k
                    }},
1048
3.16k
                }},
1049
3.16k
                {RPCResult::Type::OBJ_DYN, "unknown", /*optional=*/true, "The unknown output fields",
1050
3.16k
                {
1051
3.16k
                    {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
1052
3.16k
                }},
1053
3.16k
                {RPCResult::Type::ARR, "proprietary", /*optional=*/true, "The output proprietary map",
1054
3.16k
                {
1055
3.16k
                    {RPCResult::Type::OBJ, "", "",
1056
3.16k
                    {
1057
3.16k
                        {RPCResult::Type::STR_HEX, "identifier", "The hex string for the proprietary identifier"},
1058
3.16k
                        {RPCResult::Type::NUM, "subtype", "The number for the subtype"},
1059
3.16k
                        {RPCResult::Type::STR_HEX, "key", "The hex for the key"},
1060
3.16k
                        {RPCResult::Type::STR_HEX, "value", "The hex for the value"},
1061
3.16k
                    }},
1062
3.16k
                }},
1063
3.16k
            }},
1064
3.16k
        }
1065
3.16k
    };
1066
3.16k
    return decodepsbt_outputs;
1067
3.16k
}
1068
1069
static RPCMethod decodepsbt()
1070
3.16k
{
1071
3.16k
    return RPCMethod{
1072
3.16k
        "decodepsbt",
1073
3.16k
        "Return a JSON object representing the serialized, base64-encoded partially signed Bitcoin transaction.",
1074
3.16k
                {
1075
3.16k
                    {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The PSBT base64 string"},
1076
3.16k
                },
1077
3.16k
                RPCResult{
1078
3.16k
                    RPCResult::Type::OBJ, "", "",
1079
3.16k
                    {
1080
3.16k
                        {RPCResult::Type::OBJ, "tx", /*optional=*/true, "The decoded network-serialized unsigned transaction.",
1081
3.16k
                            TxDoc({.elision_mode = ElisionMode::WithSummary, .elision_summary = "The layout is the same as the output of decoderawtransaction."})
1082
3.16k
                        },
1083
3.16k
                        {RPCResult::Type::ARR, "global_xpubs", "",
1084
3.16k
                        {
1085
3.16k
                            {RPCResult::Type::OBJ, "", "",
1086
3.16k
                            {
1087
3.16k
                                {RPCResult::Type::STR, "xpub", "The extended public key this path corresponds to"},
1088
3.16k
                                {RPCResult::Type::STR_HEX, "master_fingerprint", "The fingerprint of the master key"},
1089
3.16k
                                {RPCResult::Type::STR, "path", "The path"},
1090
3.16k
                            }},
1091
3.16k
                        }},
1092
3.16k
                        {RPCResult::Type::NUM, "tx_version", /* optional */ true, "The version number of the unsigned transaction. Not to be confused with PSBT version"},
1093
3.16k
                        {RPCResult::Type::NUM, "fallback_locktime", /* optional */ true, "The locktime to fallback to if no inputs specify a required locktime."},
1094
3.16k
                        {RPCResult::Type::NUM, "input_count", /* optional */ true, "The number of inputs in this psbt"},
1095
3.16k
                        {RPCResult::Type::NUM, "output_count", /* optional */ true, "The number of outputs in this psbt."},
1096
3.16k
                        {RPCResult::Type::BOOL, "inputs_modifiable", /* optional */ true, "Whether inputs can be modified"},
1097
3.16k
                        {RPCResult::Type::BOOL, "outputs_modifiable", /* optional */ true, "Whether outputs can be modified"},
1098
3.16k
                        {RPCResult::Type::BOOL, "has_sighash_single", /* optional */ true, "Whether this PSBT has SIGHASH_SINGLE inputs"},
1099
3.16k
                        {RPCResult::Type::NUM, "psbt_version", /* optional */ true, "The PSBT version number. Not to be confused with the unsigned transaction version"},
1100
3.16k
                        {RPCResult::Type::ARR, "proprietary", "The global proprietary map",
1101
3.16k
                        {
1102
3.16k
                            {RPCResult::Type::OBJ, "", "",
1103
3.16k
                            {
1104
3.16k
                                {RPCResult::Type::STR_HEX, "identifier", "The hex string for the proprietary identifier"},
1105
3.16k
                                {RPCResult::Type::NUM, "subtype", "The number for the subtype"},
1106
3.16k
                                {RPCResult::Type::STR_HEX, "key", "The hex for the key"},
1107
3.16k
                                {RPCResult::Type::STR_HEX, "value", "The hex for the value"},
1108
3.16k
                            }},
1109
3.16k
                        }},
1110
3.16k
                        {RPCResult::Type::OBJ_DYN, "unknown", "The unknown global fields",
1111
3.16k
                        {
1112
3.16k
                             {RPCResult::Type::STR_HEX, "key", "(key-value pair) An unknown key-value pair"},
1113
3.16k
                        }},
1114
3.16k
                        DecodePSBTInputs(),
1115
3.16k
                        DecodePSBTOutputs(),
1116
3.16k
                        {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The transaction fee paid if all UTXOs slots in the PSBT have been filled."},
1117
3.16k
                    }
1118
3.16k
                },
1119
3.16k
                RPCExamples{
1120
3.16k
                    HelpExampleCli("decodepsbt", "\"psbt\"")
1121
3.16k
                },
1122
3.16k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1123
3.16k
{
1124
    // Unserialize the transactions
1125
569
    util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(request.params[0].get_str());
1126
569
    if (!psbt_res) {
1127
88
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));
1128
88
    }
1129
481
    PartiallySignedTransaction psbtx = *psbt_res;
1130
1131
481
    UniValue result(UniValue::VOBJ);
1132
1133
481
    if (psbtx.GetVersion() < 2) {
1134
        // Add the decoded tx
1135
59
        UniValue tx_univ(UniValue::VOBJ);
1136
59
        TxToUniv(CTransaction(*CHECK_NONFATAL(psbtx.GetUnsignedTx())), /*block_hash=*/uint256(), /*entry=*/tx_univ, /*include_hex=*/false);
1137
59
        result.pushKV("tx", std::move(tx_univ));
1138
59
    }
1139
1140
    // Add the global xpubs
1141
481
    UniValue global_xpubs(UniValue::VARR);
1142
481
    for (std::pair<KeyOriginInfo, std::set<CExtPubKey>> xpub_pair : psbtx.m_xpubs) {
1143
5
        for (auto& xpub : xpub_pair.second) {
1144
5
            std::vector<unsigned char> ser_xpub;
1145
5
            VectorWriter{ser_xpub, 0, xpub.version, xpub};
1146
1147
5
            UniValue keypath(UniValue::VOBJ);
1148
5
            keypath.pushKV("xpub", EncodeBase58Check(ser_xpub));
1149
5
            keypath.pushKV("master_fingerprint", HexStr(xpub_pair.first.fingerprint));
1150
5
            keypath.pushKV("path", WriteHDKeypath(xpub_pair.first.path));
1151
5
            global_xpubs.push_back(std::move(keypath));
1152
5
        }
1153
5
    }
1154
481
    result.pushKV("global_xpubs", std::move(global_xpubs));
1155
1156
    // Add PSBTv2 stuff
1157
481
    if (psbtx.GetVersion() >= 2) {
1158
422
        result.pushKV("tx_version", psbtx.tx_version);
1159
422
        if (psbtx.fallback_locktime.has_value()) {
1160
410
            result.pushKV("fallback_locktime", static_cast<uint64_t>(*psbtx.fallback_locktime));
1161
410
        }
1162
422
        result.pushKV("input_count", (uint64_t)psbtx.inputs.size());
1163
422
        result.pushKV("output_count", (uint64_t)psbtx.outputs.size());
1164
422
        if (psbtx.m_tx_modifiable.has_value()) {
1165
10
            result.pushKV("inputs_modifiable", psbtx.m_tx_modifiable->test(0));
1166
10
            result.pushKV("outputs_modifiable", psbtx.m_tx_modifiable->test(1));
1167
10
            result.pushKV("has_sighash_single", psbtx.m_tx_modifiable->test(2));
1168
10
        }
1169
422
    }
1170
1171
    // PSBT version
1172
481
    result.pushKV("psbt_version", psbtx.GetVersion());
1173
1174
    // Proprietary
1175
481
    UniValue proprietary(UniValue::VARR);
1176
481
    for (const auto& entry : psbtx.m_proprietary) {
1177
4
        UniValue this_prop(UniValue::VOBJ);
1178
4
        this_prop.pushKV("identifier", HexStr(entry.identifier));
1179
4
        this_prop.pushKV("subtype", entry.subtype);
1180
4
        this_prop.pushKV("key", HexStr(entry.key));
1181
4
        this_prop.pushKV("value", HexStr(entry.value));
1182
4
        proprietary.push_back(std::move(this_prop));
1183
4
    }
1184
481
    result.pushKV("proprietary", std::move(proprietary));
1185
1186
    // Unknown data
1187
481
    UniValue unknowns(UniValue::VOBJ);
1188
481
    for (auto [key, value] : psbtx.unknown) {
1189
14
        unknowns.pushKVEnd(HexStr(key), HexStr(value));
1190
14
    }
1191
481
    result.pushKV("unknown", std::move(unknowns));
1192
1193
    // inputs
1194
481
    CAmount total_in = 0;
1195
481
    bool have_all_utxos = true;
1196
481
    UniValue inputs(UniValue::VARR);
1197
1.04k
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
1198
559
        const PSBTInput& input = psbtx.inputs[i];
1199
559
        UniValue in(UniValue::VOBJ);
1200
        // UTXOs
1201
559
        bool have_a_utxo = false;
1202
559
        CTxOut txout;
1203
559
        if (!input.witness_utxo.IsNull()) {
1204
465
            txout = input.witness_utxo;
1205
1206
465
            UniValue o(UniValue::VOBJ);
1207
465
            ScriptToUniv(txout.scriptPubKey, /*out=*/o, /*include_hex=*/true, /*include_address=*/true);
1208
1209
465
            UniValue out(UniValue::VOBJ);
1210
465
            out.pushKV("amount", ValueFromAmount(txout.nValue));
1211
465
            out.pushKV("scriptPubKey", std::move(o));
1212
1213
465
            in.pushKV("witness_utxo", std::move(out));
1214
1215
465
            have_a_utxo = true;
1216
465
        }
1217
559
        if (input.non_witness_utxo) {
1218
169
            txout = input.non_witness_utxo->vout[input.prev_out];
1219
1220
169
            UniValue non_wit(UniValue::VOBJ);
1221
169
            TxToUniv(*input.non_witness_utxo, /*block_hash=*/uint256(), /*entry=*/non_wit, /*include_hex=*/false);
1222
169
            in.pushKV("non_witness_utxo", std::move(non_wit));
1223
1224
169
            have_a_utxo = true;
1225
169
        }
1226
559
        if (have_a_utxo) {
1227
506
            if (MoneyRange(txout.nValue) && MoneyRange(total_in + txout.nValue)) {
1228
506
                total_in += txout.nValue;
1229
506
            } else {
1230
                // Hack to just not show fee later
1231
0
                have_all_utxos = false;
1232
0
            }
1233
506
        } else {
1234
53
            have_all_utxos = false;
1235
53
        }
1236
1237
        // Partial sigs
1238
559
        if (!input.partial_sigs.empty()) {
1239
40
            UniValue partial_sigs(UniValue::VOBJ);
1240
57
            for (const auto& sig : input.partial_sigs) {
1241
57
                partial_sigs.pushKV(HexStr(sig.second.first), HexStr(sig.second.second));
1242
57
            }
1243
40
            in.pushKV("partial_signatures", std::move(partial_sigs));
1244
40
        }
1245
1246
        // Sighash
1247
559
        if (input.sighash_type != std::nullopt) {
1248
13
            in.pushKV("sighash", SighashToStr(*input.sighash_type));
1249
13
        }
1250
1251
        // Redeem script and witness script
1252
559
        if (!input.redeem_script.empty()) {
1253
19
            UniValue r(UniValue::VOBJ);
1254
19
            ScriptToUniv(input.redeem_script, /*out=*/r);
1255
19
            in.pushKV("redeem_script", std::move(r));
1256
19
        }
1257
559
        if (!input.witness_script.empty()) {
1258
27
            UniValue r(UniValue::VOBJ);
1259
27
            ScriptToUniv(input.witness_script, /*out=*/r);
1260
27
            in.pushKV("witness_script", std::move(r));
1261
27
        }
1262
1263
        // keypaths
1264
559
        if (!input.hd_keypaths.empty()) {
1265
108
            UniValue keypaths(UniValue::VARR);
1266
149
            for (auto entry : input.hd_keypaths) {
1267
149
                UniValue keypath(UniValue::VOBJ);
1268
149
                keypath.pushKV("pubkey", HexStr(entry.first));
1269
1270
149
                keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint.data())));
1271
149
                keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1272
149
                keypaths.push_back(std::move(keypath));
1273
149
            }
1274
108
            in.pushKV("bip32_derivs", std::move(keypaths));
1275
108
        }
1276
1277
        // Final scriptSig and scriptwitness
1278
559
        if (!input.final_script_sig.empty()) {
1279
17
            UniValue scriptsig(UniValue::VOBJ);
1280
17
            scriptsig.pushKV("asm", ScriptToAsmStr(input.final_script_sig, true));
1281
17
            scriptsig.pushKV("hex", HexStr(input.final_script_sig));
1282
17
            in.pushKV("final_scriptSig", std::move(scriptsig));
1283
17
        }
1284
559
        if (!input.final_script_witness.IsNull()) {
1285
54
            UniValue txinwitness(UniValue::VARR);
1286
117
            for (const auto& item : input.final_script_witness.stack) {
1287
117
                txinwitness.push_back(HexStr(item));
1288
117
            }
1289
54
            in.pushKV("final_scriptwitness", std::move(txinwitness));
1290
54
        }
1291
1292
        // Ripemd160 hash preimages
1293
559
        if (!input.ripemd160_preimages.empty()) {
1294
2
            UniValue ripemd160_preimages(UniValue::VOBJ);
1295
3
            for (const auto& [hash, preimage] : input.ripemd160_preimages) {
1296
3
                ripemd160_preimages.pushKVEnd(HexStr(hash), HexStr(preimage));
1297
3
            }
1298
2
            in.pushKV("ripemd160_preimages", std::move(ripemd160_preimages));
1299
2
        }
1300
1301
        // Sha256 hash preimages
1302
559
        if (!input.sha256_preimages.empty()) {
1303
3
            UniValue sha256_preimages(UniValue::VOBJ);
1304
4
            for (const auto& [hash, preimage] : input.sha256_preimages) {
1305
4
                sha256_preimages.pushKVEnd(HexStr(hash), HexStr(preimage));
1306
4
            }
1307
3
            in.pushKV("sha256_preimages", std::move(sha256_preimages));
1308
3
        }
1309
1310
        // Hash160 hash preimages
1311
559
        if (!input.hash160_preimages.empty()) {
1312
2
            UniValue hash160_preimages(UniValue::VOBJ);
1313
3
            for (const auto& [hash, preimage] : input.hash160_preimages) {
1314
3
                hash160_preimages.pushKVEnd(HexStr(hash), HexStr(preimage));
1315
3
            }
1316
2
            in.pushKV("hash160_preimages", std::move(hash160_preimages));
1317
2
        }
1318
1319
        // Hash256 hash preimages
1320
559
        if (!input.hash256_preimages.empty()) {
1321
2
            UniValue hash256_preimages(UniValue::VOBJ);
1322
3
            for (const auto& [hash, preimage] : input.hash256_preimages) {
1323
3
                hash256_preimages.pushKVEnd(HexStr(hash), HexStr(preimage));
1324
3
            }
1325
2
            in.pushKV("hash256_preimages", std::move(hash256_preimages));
1326
2
        }
1327
1328
        // PSBTv2
1329
559
        if (psbtx.GetVersion() >= 2) {
1330
487
            in.pushKV("previous_txid", input.prev_txid.GetHex());
1331
487
            in.pushKV("previous_vout", static_cast<uint64_t>(input.prev_out));
1332
487
            if (input.sequence.has_value()) {
1333
476
                in.pushKV("sequence", static_cast<uint64_t>(*input.sequence));
1334
476
            }
1335
487
            if (input.time_locktime.has_value()) {
1336
2
                in.pushKV("time_locktime", static_cast<uint64_t>(*input.time_locktime));
1337
2
            }
1338
487
            if (input.height_locktime.has_value()) {
1339
2
                in.pushKV("height_locktime", static_cast<uint64_t>(*input.height_locktime));
1340
2
            }
1341
487
        }
1342
1343
        // Taproot key path signature
1344
559
        if (!input.m_tap_key_sig.empty()) {
1345
84
            in.pushKV("taproot_key_path_sig", HexStr(input.m_tap_key_sig));
1346
84
        }
1347
1348
        // Taproot script path signatures
1349
559
        if (!input.m_tap_script_sigs.empty()) {
1350
102
            UniValue script_sigs(UniValue::VARR);
1351
163
            for (const auto& [pubkey_leaf, sig] : input.m_tap_script_sigs) {
1352
163
                const auto& [xonly, leaf_hash] = pubkey_leaf;
1353
163
                UniValue sigobj(UniValue::VOBJ);
1354
163
                sigobj.pushKV("pubkey", HexStr(xonly));
1355
163
                sigobj.pushKV("leaf_hash", HexStr(leaf_hash));
1356
163
                sigobj.pushKV("sig", HexStr(sig));
1357
163
                script_sigs.push_back(std::move(sigobj));
1358
163
            }
1359
102
            in.pushKV("taproot_script_path_sigs", std::move(script_sigs));
1360
102
        }
1361
1362
        // Taproot leaf scripts
1363
559
        if (!input.m_tap_scripts.empty()) {
1364
219
            UniValue tap_scripts(UniValue::VARR);
1365
327
            for (const auto& [leaf, control_blocks] : input.m_tap_scripts) {
1366
327
                const auto& [script, leaf_ver] = leaf;
1367
327
                UniValue script_info(UniValue::VOBJ);
1368
327
                script_info.pushKV("script", HexStr(script));
1369
327
                script_info.pushKV("leaf_ver", leaf_ver);
1370
327
                UniValue control_blocks_univ(UniValue::VARR);
1371
395
                for (const auto& control_block : control_blocks) {
1372
395
                    control_blocks_univ.push_back(HexStr(control_block));
1373
395
                }
1374
327
                script_info.pushKV("control_blocks", std::move(control_blocks_univ));
1375
327
                tap_scripts.push_back(std::move(script_info));
1376
327
            }
1377
219
            in.pushKV("taproot_scripts", std::move(tap_scripts));
1378
219
        }
1379
1380
        // Taproot bip32 keypaths
1381
559
        if (!input.m_tap_bip32_paths.empty()) {
1382
299
            UniValue keypaths(UniValue::VARR);
1383
1.07k
            for (const auto& [xonly, leaf_origin] : input.m_tap_bip32_paths) {
1384
1.07k
                const auto& [leaf_hashes, origin] = leaf_origin;
1385
1.07k
                UniValue path_obj(UniValue::VOBJ);
1386
1.07k
                path_obj.pushKV("pubkey", HexStr(xonly));
1387
1.07k
                path_obj.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(origin.fingerprint.data())));
1388
1.07k
                path_obj.pushKV("path", WriteHDKeypath(origin.path));
1389
1.07k
                UniValue leaf_hashes_arr(UniValue::VARR);
1390
1.07k
                for (const auto& leaf_hash : leaf_hashes) {
1391
731
                    leaf_hashes_arr.push_back(HexStr(leaf_hash));
1392
731
                }
1393
1.07k
                path_obj.pushKV("leaf_hashes", std::move(leaf_hashes_arr));
1394
1.07k
                keypaths.push_back(std::move(path_obj));
1395
1.07k
            }
1396
299
            in.pushKV("taproot_bip32_derivs", std::move(keypaths));
1397
299
        }
1398
1399
        // Taproot internal key
1400
559
        if (!input.m_tap_internal_key.IsNull()) {
1401
266
            in.pushKV("taproot_internal_key", HexStr(input.m_tap_internal_key));
1402
266
        }
1403
1404
        // Write taproot merkle root
1405
559
        if (!input.m_tap_merkle_root.IsNull()) {
1406
213
            in.pushKV("taproot_merkle_root", HexStr(input.m_tap_merkle_root));
1407
213
        }
1408
1409
        // Write MuSig2 fields
1410
559
        if (!input.m_musig2_participants.empty()) {
1411
122
            UniValue musig_pubkeys(UniValue::VARR);
1412
157
            for (const auto& [agg, parts] : input.m_musig2_participants) {
1413
157
                UniValue musig_part(UniValue::VOBJ);
1414
157
                musig_part.pushKV("aggregate_pubkey", HexStr(agg));
1415
157
                UniValue part_pubkeys(UniValue::VARR);
1416
434
                for (const auto& pub : parts) {
1417
434
                    part_pubkeys.push_back(HexStr(pub));
1418
434
                }
1419
157
                musig_part.pushKV("participant_pubkeys", part_pubkeys);
1420
157
                musig_pubkeys.push_back(musig_part);
1421
157
            }
1422
122
            in.pushKV("musig2_participant_pubkeys", musig_pubkeys);
1423
122
        }
1424
559
        if (!input.m_musig2_pubnonces.empty()) {
1425
97
            UniValue musig_pubnonces(UniValue::VARR);
1426
129
            for (const auto& [agg_lh, part_pubnonce] : input.m_musig2_pubnonces) {
1427
129
                const auto& [agg, lh] = agg_lh;
1428
346
                for (const auto& [part, pubnonce] : part_pubnonce) {
1429
346
                    UniValue info(UniValue::VOBJ);
1430
346
                    info.pushKV("participant_pubkey", HexStr(part));
1431
346
                    info.pushKV("aggregate_pubkey", HexStr(agg));
1432
346
                    if (!lh.IsNull()) info.pushKV("leaf_hash", HexStr(lh));
1433
346
                    info.pushKV("pubnonce", HexStr(pubnonce));
1434
346
                    musig_pubnonces.push_back(info);
1435
346
                }
1436
129
            }
1437
97
            in.pushKV("musig2_pubnonces", musig_pubnonces);
1438
97
        }
1439
559
        if (!input.m_musig2_partial_sigs.empty()) {
1440
48
            UniValue musig_partial_sigs(UniValue::VARR);
1441
60
            for (const auto& [agg_lh, part_psig] : input.m_musig2_partial_sigs) {
1442
60
                const auto& [agg, lh] = agg_lh;
1443
165
                for (const auto& [part, psig] : part_psig) {
1444
165
                    UniValue info(UniValue::VOBJ);
1445
165
                    info.pushKV("participant_pubkey", HexStr(part));
1446
165
                    info.pushKV("aggregate_pubkey", HexStr(agg));
1447
165
                    if (!lh.IsNull()) info.pushKV("leaf_hash", HexStr(lh));
1448
165
                    info.pushKV("partial_sig", HexStr(psig));
1449
165
                    musig_partial_sigs.push_back(info);
1450
165
                }
1451
60
            }
1452
48
            in.pushKV("musig2_partial_sigs", musig_partial_sigs);
1453
48
        }
1454
1455
        // Proprietary
1456
559
        if (!input.m_proprietary.empty()) {
1457
2
            UniValue proprietary(UniValue::VARR);
1458
3
            for (const auto& entry : input.m_proprietary) {
1459
3
                UniValue this_prop(UniValue::VOBJ);
1460
3
                this_prop.pushKV("identifier", HexStr(entry.identifier));
1461
3
                this_prop.pushKV("subtype", entry.subtype);
1462
3
                this_prop.pushKV("key", HexStr(entry.key));
1463
3
                this_prop.pushKV("value", HexStr(entry.value));
1464
3
                proprietary.push_back(std::move(this_prop));
1465
3
            }
1466
2
            in.pushKV("proprietary", std::move(proprietary));
1467
2
        }
1468
1469
        // Unknown data
1470
559
        if (input.unknown.size() > 0) {
1471
11
            UniValue unknowns(UniValue::VOBJ);
1472
16
            for (auto [key, value] : input.unknown) {
1473
16
                unknowns.pushKVEnd(HexStr(key), HexStr(value));
1474
16
            }
1475
11
            in.pushKV("unknown", std::move(unknowns));
1476
11
        }
1477
1478
559
        inputs.push_back(std::move(in));
1479
559
    }
1480
481
    result.pushKV("inputs", std::move(inputs));
1481
1482
    // outputs
1483
481
    CAmount output_value = 0;
1484
481
    UniValue outputs(UniValue::VARR);
1485
1.32k
    for (unsigned int i = 0; i < psbtx.outputs.size(); ++i) {
1486
846
        const PSBTOutput& output = psbtx.outputs[i];
1487
846
        UniValue out(UniValue::VOBJ);
1488
        // Redeem script and witness script
1489
846
        if (!output.redeem_script.empty()) {
1490
16
            UniValue r(UniValue::VOBJ);
1491
16
            ScriptToUniv(output.redeem_script, /*out=*/r);
1492
16
            out.pushKV("redeem_script", std::move(r));
1493
16
        }
1494
846
        if (!output.witness_script.empty()) {
1495
12
            UniValue r(UniValue::VOBJ);
1496
12
            ScriptToUniv(output.witness_script, /*out=*/r);
1497
12
            out.pushKV("witness_script", std::move(r));
1498
12
        }
1499
1500
        // keypaths
1501
846
        if (!output.hd_keypaths.empty()) {
1502
136
            UniValue keypaths(UniValue::VARR);
1503
152
            for (auto entry : output.hd_keypaths) {
1504
152
                UniValue keypath(UniValue::VOBJ);
1505
152
                keypath.pushKV("pubkey", HexStr(entry.first));
1506
152
                keypath.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(entry.second.fingerprint.data())));
1507
152
                keypath.pushKV("path", WriteHDKeypath(entry.second.path));
1508
152
                keypaths.push_back(std::move(keypath));
1509
152
            }
1510
136
            out.pushKV("bip32_derivs", std::move(keypaths));
1511
136
        }
1512
1513
        // PSBTv2 stuff
1514
846
        if (psbtx.GetVersion() >= 2) {
1515
768
            out.pushKV("amount", ValueFromAmount(output.amount));
1516
768
            UniValue spk(UniValue::VOBJ);
1517
768
            ScriptToUniv(output.script, spk, /*include_hex=*/true, /*include_address=*/true);
1518
768
            out.pushKV("script", spk);
1519
768
        }
1520
1521
        // Taproot internal key
1522
846
        if (!output.m_tap_internal_key.IsNull()) {
1523
240
            out.pushKV("taproot_internal_key", HexStr(output.m_tap_internal_key));
1524
240
        }
1525
1526
        // Taproot tree
1527
846
        if (!output.m_tap_tree.empty()) {
1528
183
            UniValue tree(UniValue::VARR);
1529
381
            for (const auto& [depth, leaf_ver, script] : output.m_tap_tree) {
1530
381
                UniValue elem(UniValue::VOBJ);
1531
381
                elem.pushKV("depth", depth);
1532
381
                elem.pushKV("leaf_ver", leaf_ver);
1533
381
                elem.pushKV("script", HexStr(script));
1534
381
                tree.push_back(std::move(elem));
1535
381
            }
1536
183
            out.pushKV("taproot_tree", std::move(tree));
1537
183
        }
1538
1539
        // Taproot bip32 keypaths
1540
846
        if (!output.m_tap_bip32_paths.empty()) {
1541
278
            UniValue keypaths(UniValue::VARR);
1542
1.01k
            for (const auto& [xonly, leaf_origin] : output.m_tap_bip32_paths) {
1543
1.01k
                const auto& [leaf_hashes, origin] = leaf_origin;
1544
1.01k
                UniValue path_obj(UniValue::VOBJ);
1545
1.01k
                path_obj.pushKV("pubkey", HexStr(xonly));
1546
1.01k
                path_obj.pushKV("master_fingerprint", strprintf("%08x", ReadBE32(origin.fingerprint.data())));
1547
1.01k
                path_obj.pushKV("path", WriteHDKeypath(origin.path));
1548
1.01k
                UniValue leaf_hashes_arr(UniValue::VARR);
1549
1.01k
                for (const auto& leaf_hash : leaf_hashes) {
1550
705
                    leaf_hashes_arr.push_back(HexStr(leaf_hash));
1551
705
                }
1552
1.01k
                path_obj.pushKV("leaf_hashes", std::move(leaf_hashes_arr));
1553
1.01k
                keypaths.push_back(std::move(path_obj));
1554
1.01k
            }
1555
278
            out.pushKV("taproot_bip32_derivs", std::move(keypaths));
1556
278
        }
1557
1558
        // Write MuSig2 fields
1559
846
        if (!output.m_musig2_participants.empty()) {
1560
133
            UniValue musig_pubkeys(UniValue::VARR);
1561
175
            for (const auto& [agg, parts] : output.m_musig2_participants) {
1562
175
                UniValue musig_part(UniValue::VOBJ);
1563
175
                musig_part.pushKV("aggregate_pubkey", HexStr(agg));
1564
175
                UniValue part_pubkeys(UniValue::VARR);
1565
488
                for (const auto& pub : parts) {
1566
488
                    part_pubkeys.push_back(HexStr(pub));
1567
488
                }
1568
175
                musig_part.pushKV("participant_pubkeys", part_pubkeys);
1569
175
                musig_pubkeys.push_back(musig_part);
1570
175
            }
1571
133
            out.pushKV("musig2_participant_pubkeys", musig_pubkeys);
1572
133
        }
1573
1574
        // Proprietary
1575
846
        if (!output.m_proprietary.empty()) {
1576
2
            UniValue proprietary(UniValue::VARR);
1577
3
            for (const auto& entry : output.m_proprietary) {
1578
3
                UniValue this_prop(UniValue::VOBJ);
1579
3
                this_prop.pushKV("identifier", HexStr(entry.identifier));
1580
3
                this_prop.pushKV("subtype", entry.subtype);
1581
3
                this_prop.pushKV("key", HexStr(entry.key));
1582
3
                this_prop.pushKV("value", HexStr(entry.value));
1583
3
                proprietary.push_back(std::move(this_prop));
1584
3
            }
1585
2
            out.pushKV("proprietary", std::move(proprietary));
1586
2
        }
1587
1588
        // Unknown data
1589
846
        if (output.unknown.size() > 0) {
1590
10
            UniValue unknowns(UniValue::VOBJ);
1591
14
            for (auto [key, value] : output.unknown) {
1592
14
                unknowns.pushKVEnd(HexStr(key), HexStr(value));
1593
14
            }
1594
10
            out.pushKV("unknown", std::move(unknowns));
1595
10
        }
1596
1597
846
        outputs.push_back(std::move(out));
1598
1599
        // Fee calculation
1600
846
        if (MoneyRange(output.amount) && MoneyRange(output_value + output.amount)) {
1601
846
            output_value += output.amount;
1602
846
        } else {
1603
            // Hack to just not show fee later
1604
0
            have_all_utxos = false;
1605
0
        }
1606
846
    }
1607
481
    result.pushKV("outputs", std::move(outputs));
1608
481
    if (have_all_utxos) {
1609
441
        result.pushKV("fee", ValueFromAmount(total_in - output_value));
1610
441
    }
1611
1612
481
    return result;
1613
569
},
1614
3.16k
    };
1615
3.16k
}
1616
1617
static RPCMethod combinepsbt()
1618
2.71k
{
1619
2.71k
    return RPCMethod{
1620
2.71k
        "combinepsbt",
1621
2.71k
        "Combine multiple partially signed Bitcoin transactions into one transaction.\n"
1622
2.71k
                "Implements the Combiner role.\n",
1623
2.71k
                {
1624
2.71k
                    {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base64 strings of partially signed transactions",
1625
2.71k
                        {
1626
2.71k
                            {"psbt", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "A base64 string of a PSBT"},
1627
2.71k
                        },
1628
2.71k
                        },
1629
2.71k
                },
1630
2.71k
                RPCResult{
1631
2.71k
                    RPCResult::Type::STR, "", "The base64-encoded partially signed transaction"
1632
2.71k
                },
1633
2.71k
                RPCExamples{
1634
2.71k
                    HelpExampleCli("combinepsbt", R"('["mybase64_1", "mybase64_2", "mybase64_3"]')")
1635
2.71k
                },
1636
2.71k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1637
2.71k
{
1638
    // Unserialize the transactions
1639
123
    std::vector<PartiallySignedTransaction> psbtxs;
1640
123
    UniValue txs = request.params[0].get_array();
1641
123
    if (txs.empty()) {
1642
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Parameter 'txs' cannot be empty");
1643
1
    }
1644
460
    for (unsigned int i = 0; i < txs.size(); ++i) {
1645
338
        util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(txs[i].get_str());
1646
338
        if (!psbt_res) {
1647
0
            throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));
1648
0
        }
1649
338
        psbtxs.push_back(*psbt_res);
1650
338
    }
1651
1652
122
    std::optional<PartiallySignedTransaction> merged_psbt = CombinePSBTs(psbtxs);
1653
122
    if (!merged_psbt) {
1654
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, "PSBTs not compatible (different transactions)");
1655
1
    }
1656
1657
121
    DataStream ssTx{};
1658
121
    ssTx << *merged_psbt;
1659
121
    return EncodeBase64(ssTx);
1660
122
},
1661
2.71k
    };
1662
2.71k
}
1663
1664
static RPCMethod finalizepsbt()
1665
2.85k
{
1666
2.85k
    return RPCMethod{"finalizepsbt",
1667
2.85k
                "Finalize the inputs of a PSBT. If the transaction is fully signed, it will produce a\n"
1668
2.85k
                "network serialized transaction which can be broadcast with sendrawtransaction. Otherwise a PSBT will be\n"
1669
2.85k
                "created which has the final_scriptSig and final_scriptwitness fields filled for inputs that are complete.\n"
1670
2.85k
                "Implements the Finalizer and Extractor roles.\n",
1671
2.85k
                {
1672
2.85k
                    {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"},
1673
2.85k
                    {"extract", RPCArg::Type::BOOL, RPCArg::Default{true}, "If true and the transaction is complete,\n"
1674
2.85k
            "                             extract and return the complete transaction in normal network serialization instead of the PSBT."},
1675
2.85k
                },
1676
2.85k
                RPCResult{
1677
2.85k
                    RPCResult::Type::OBJ, "", "",
1678
2.85k
                    {
1679
2.85k
                        {RPCResult::Type::STR, "psbt", /*optional=*/true, "The base64-encoded partially signed transaction if not extracted"},
1680
2.85k
                        {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The hex-encoded network transaction if extracted"},
1681
2.85k
                        {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
1682
2.85k
                    }
1683
2.85k
                },
1684
2.85k
                RPCExamples{
1685
2.85k
                    HelpExampleCli("finalizepsbt", "\"psbt\"")
1686
2.85k
                },
1687
2.85k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1688
2.85k
{
1689
    // Unserialize the transactions
1690
263
    util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(request.params[0].get_str());
1691
263
    if (!psbt_res) {
1692
1
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));
1693
1
    }
1694
262
    PartiallySignedTransaction psbtx = *psbt_res;
1695
1696
262
    const bool extract{self.Arg<bool>("extract")};
1697
1698
262
    CMutableTransaction mtx;
1699
262
    bool complete = FinalizeAndExtractPSBT(psbtx, mtx);
1700
1701
262
    UniValue result(UniValue::VOBJ);
1702
262
    DataStream ssTx{};
1703
262
    std::string result_str;
1704
1705
262
    if (complete && extract) {
1706
206
        ssTx << TX_WITH_WITNESS(mtx);
1707
206
        result_str = HexStr(ssTx);
1708
206
        result.pushKV("hex", result_str);
1709
206
    } else {
1710
56
        ssTx << psbtx;
1711
56
        result_str = EncodeBase64(ssTx.str());
1712
56
        result.pushKV("psbt", result_str);
1713
56
    }
1714
262
    result.pushKV("complete", complete);
1715
1716
262
    return result;
1717
263
},
1718
2.85k
    };
1719
2.85k
}
1720
1721
static RPCMethod createpsbt()
1722
2.66k
{
1723
2.66k
    return RPCMethod{
1724
2.66k
        "createpsbt",
1725
2.66k
        "Creates a transaction in the Partially Signed Transaction format.\n"
1726
2.66k
                "Implements the Creator role.\n"
1727
2.66k
                "Note that the transaction's inputs are not signed, and\n"
1728
2.66k
                "it is not stored in the wallet or transmitted to the network.\n",
1729
2.66k
                Cat<std::vector<RPCArg>>(
1730
2.66k
                    CreateTxDoc(),
1731
2.66k
                    {
1732
2.66k
                        {"psbt_version", RPCArg::Type::NUM, RPCArg::Default{2}, "The PSBT version number to use."},
1733
2.66k
                    }
1734
2.66k
                ),
1735
2.66k
                RPCResult{
1736
2.66k
                    RPCResult::Type::STR, "", "The resulting raw transaction (base64-encoded string)"
1737
2.66k
                },
1738
2.66k
                RPCExamples{
1739
2.66k
                    HelpExampleCli("createpsbt", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"address\\\":0.01}]\"")
1740
2.66k
                },
1741
2.66k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1742
2.66k
{
1743
72
    std::optional<bool> rbf;
1744
72
    if (!request.params[3].isNull()) {
1745
1
        rbf = request.params[3].get_bool();
1746
1
    }
1747
72
    CMutableTransaction rawTx = ConstructTransaction(request.params[0], request.params[1], request.params[2], rbf, self.Arg<uint32_t>("version"));
1748
1749
    // Make a blank psbt
1750
72
    const uint32_t psbt_version{self.Arg<uint32_t>("psbt_version")};
1751
72
    if (psbt_version != 2 && psbt_version != 0) {
1752
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, "The PSBT version can only be 2 or 0");
1753
1
    }
1754
71
    PartiallySignedTransaction psbtx{rawTx, psbt_version};
1755
1756
    // Serialize the PSBT
1757
71
    DataStream ssTx{};
1758
71
    ssTx << psbtx;
1759
1760
71
    return EncodeBase64(ssTx);
1761
72
},
1762
2.66k
    };
1763
2.66k
}
1764
1765
static RPCMethod converttopsbt()
1766
2.60k
{
1767
2.60k
    return RPCMethod{
1768
2.60k
        "converttopsbt",
1769
2.60k
        "Converts a network serialized transaction to a PSBT. This should be used only with createrawtransaction and fundrawtransaction\n"
1770
2.60k
                "createpsbt and walletcreatefundedpsbt should be used for new applications.\n",
1771
2.60k
                {
1772
2.60k
                    {"hexstring", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex string of a raw transaction"},
1773
2.60k
                    {"permitsigdata", RPCArg::Type::BOOL, RPCArg::Default{false}, "If true, any signatures in the input will be discarded and conversion\n"
1774
2.60k
                            "                              will continue. If false, RPC will fail if any signatures are present."},
1775
2.60k
                    {"iswitness", RPCArg::Type::BOOL, RPCArg::DefaultHint{"depends on heuristic tests"}, "Whether the transaction hex is a serialized witness transaction.\n"
1776
2.60k
                        "If iswitness is not present, heuristic tests will be used in decoding.\n"
1777
2.60k
                        "If true, only witness deserialization will be tried.\n"
1778
2.60k
                        "If false, only non-witness deserialization will be tried.\n"
1779
2.60k
                        "This boolean should reflect whether the transaction has inputs\n"
1780
2.60k
                        "(e.g. fully valid, or on-chain transactions), if known by the caller."
1781
2.60k
                    },
1782
2.60k
                    {"psbt_version", RPCArg::Type::NUM, RPCArg::Default{2}, "The PSBT version number to use."},
1783
2.60k
                },
1784
2.60k
                RPCResult{
1785
2.60k
                    RPCResult::Type::STR, "", "The resulting raw transaction (base64-encoded string)"
1786
2.60k
                },
1787
2.60k
                RPCExamples{
1788
2.60k
                            "\nCreate a transaction\n"
1789
2.60k
                            + HelpExampleCli("createrawtransaction", "\"[{\\\"txid\\\":\\\"myid\\\",\\\"vout\\\":0}]\" \"[{\\\"data\\\":\\\"00010203\\\"}]\"") +
1790
2.60k
                            "\nConvert the transaction to a PSBT\n"
1791
2.60k
                            + HelpExampleCli("converttopsbt", "\"rawtransaction\"")
1792
2.60k
                },
1793
2.60k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1794
2.60k
{
1795
    // parse hex string from parameter
1796
12
    CMutableTransaction tx;
1797
12
    const bool permitsigdata{self.Arg<bool>("permitsigdata")};
1798
12
    bool witness_specified = !request.params[2].isNull();
1799
12
    bool iswitness = witness_specified ? request.params[2].get_bool() : false;
1800
12
    const bool try_witness = witness_specified ? iswitness : true;
1801
12
    const bool try_no_witness = witness_specified ? !iswitness : true;
1802
12
    if (!DecodeHexTx(tx, request.params[0].get_str(), try_no_witness, try_witness)) {
1803
0
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
1804
0
    }
1805
1806
    // Remove all scriptSigs and scriptWitnesses from inputs
1807
15
    for (CTxIn& input : tx.vin) {
1808
15
        if ((!input.scriptSig.empty() || !input.scriptWitness.IsNull()) && !permitsigdata) {
1809
3
            throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Inputs must not have scriptSigs and scriptWitnesses");
1810
3
        }
1811
12
        input.scriptSig.clear();
1812
12
        input.scriptWitness.SetNull();
1813
12
    }
1814
1815
    // Make a blank psbt
1816
9
    const uint32_t psbt_version{self.Arg<uint32_t>("psbt_version")};
1817
9
    if (psbt_version != 2 && psbt_version != 0) {
1818
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, "The PSBT version can only be 2 or 0");
1819
1
    }
1820
8
    PartiallySignedTransaction psbtx{tx, psbt_version};
1821
1822
    // Serialize the PSBT
1823
8
    DataStream ssTx{};
1824
8
    ssTx << psbtx;
1825
1826
8
    return EncodeBase64(ssTx);
1827
9
},
1828
2.60k
    };
1829
2.60k
}
1830
1831
static RPCMethod utxoupdatepsbt()
1832
2.60k
{
1833
2.60k
    return RPCMethod{
1834
2.60k
        "utxoupdatepsbt",
1835
2.60k
        "Updates all segwit inputs and outputs in a PSBT with data from output descriptors, the UTXO set, txindex, or the mempool.\n",
1836
2.60k
            {
1837
2.60k
                {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"},
1838
2.60k
                {"descriptors", RPCArg::Type::ARR, RPCArg::Optional::OMITTED, "An array of either strings or objects", {
1839
2.60k
                    {"", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
1840
2.60k
                    {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with an output descriptor and extra information", {
1841
2.60k
                         {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"},
1842
2.60k
                         {"range", RPCArg::Type::RANGE, RPCArg::Default{1000}, "Up to what index HD chains should be explored (either end or [begin,end])"},
1843
2.60k
                    }},
1844
2.60k
                }},
1845
2.60k
            },
1846
2.60k
            RPCResult {
1847
2.60k
                    RPCResult::Type::STR, "", "The base64-encoded partially signed transaction with inputs updated"
1848
2.60k
            },
1849
2.60k
            RPCExamples {
1850
2.60k
                HelpExampleCli("utxoupdatepsbt", "\"psbt\"")
1851
2.60k
            },
1852
2.60k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1853
2.60k
{
1854
    // Parse descriptors, if any.
1855
6
    FlatSigningProvider provider;
1856
6
    if (!request.params[1].isNull()) {
1857
1
        auto descs = request.params[1].get_array();
1858
4
        for (size_t i = 0; i < descs.size(); ++i) {
1859
3
            EvalDescriptorStringOrObject(descs[i], provider);
1860
3
        }
1861
1
    }
1862
1863
    // We don't actually need private keys further on; hide them as a precaution.
1864
6
    const PartiallySignedTransaction& psbtx = ProcessPSBT(
1865
6
        request.params[0].get_str(),
1866
6
        request.context,
1867
6
        HidingSigningProvider(&provider, /*hide_secret=*/true, /*hide_origin=*/false),
1868
6
        /*sighash_type=*/std::nullopt,
1869
6
        /*finalize=*/false);
1870
1871
6
    DataStream ssTx{};
1872
6
    ssTx << psbtx;
1873
6
    return EncodeBase64(ssTx);
1874
6
},
1875
2.60k
    };
1876
2.60k
}
1877
1878
static RPCMethod joinpsbts()
1879
2.60k
{
1880
2.60k
    return RPCMethod{
1881
2.60k
        "joinpsbts",
1882
2.60k
        "Joins multiple distinct version 0 PSBTs with different inputs and outputs into one version 0 PSBT with inputs and outputs from all of the PSBTs\n"
1883
2.60k
            "No input in any of the PSBTs can be in more than one of the PSBTs.\n",
1884
2.60k
            {
1885
2.60k
                {"txs", RPCArg::Type::ARR, RPCArg::Optional::NO, "The base64 strings of partially signed transactions",
1886
2.60k
                    {
1887
2.60k
                        {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"}
1888
2.60k
                    }}
1889
2.60k
            },
1890
2.60k
            RPCResult {
1891
2.60k
                    RPCResult::Type::STR, "", "The base64-encoded partially signed transaction"
1892
2.60k
            },
1893
2.60k
            RPCExamples {
1894
2.60k
                HelpExampleCli("joinpsbts", "\"psbt\"")
1895
2.60k
            },
1896
2.60k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
1897
2.60k
{
1898
    // Unserialize the transactions
1899
7
    std::vector<PartiallySignedTransaction> psbtxs;
1900
7
    UniValue txs = request.params[0].get_array();
1901
1902
7
    if (txs.size() <= 1) {
1903
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "At least two PSBTs are required to join PSBTs.");
1904
0
    }
1905
1906
7
    uint32_t best_version = 1;
1907
7
    uint32_t best_locktime = 0xffffffff;
1908
20
    for (unsigned int i = 0; i < txs.size(); ++i) {
1909
14
        util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(txs[i].get_str());
1910
14
        if (!psbt_res) {
1911
0
            throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));
1912
0
        }
1913
14
        psbtxs.push_back(*psbt_res);
1914
14
        const PartiallySignedTransaction& psbtx = psbtxs.back();
1915
14
        if (psbtx.GetVersion() != 0) {
1916
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "joinpsbts only operates on version 0 PSBTs");
1917
1
        }
1918
        // Choose the highest version number
1919
13
        if (psbtx.tx_version > best_version) {
1920
7
            best_version = psbtx.tx_version;
1921
7
        }
1922
        // Choose the lowest lock time
1923
13
        uint32_t psbt_locktime = psbtx.fallback_locktime.value_or(0);
1924
13
        if (psbt_locktime < best_locktime) {
1925
7
            best_locktime = psbt_locktime;
1926
7
        }
1927
13
    }
1928
1929
    // Create a blank psbt where everything will be added
1930
6
    CMutableTransaction tx;
1931
6
    tx.version = best_version;
1932
6
    tx.nLockTime = best_locktime;
1933
6
    PartiallySignedTransaction merged_psbt(tx, psbtxs.at(0).GetVersion());
1934
1935
    // Merge
1936
12
    for (auto& psbt : psbtxs) {
1937
22
        for (const PSBTInput& input : psbt.inputs) {
1938
22
            if (!merged_psbt.AddInput(input)) {
1939
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Input %s:%d exists in multiple PSBTs", input.prev_txid.ToString(), input.prev_out));
1940
1
            }
1941
22
        }
1942
11
        for (const PSBTOutput& output : psbt.outputs) {
1943
11
            merged_psbt.AddOutput(output);
1944
11
        }
1945
11
        merged_psbt.MergeGlobalXPubs(psbt);
1946
11
        merged_psbt.m_proprietary.insert(psbt.m_proprietary.begin(), psbt.m_proprietary.end());
1947
11
        merged_psbt.unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
1948
11
    }
1949
1950
    // Shuffle the inputs and outputs for privacy
1951
5
    std::shuffle(merged_psbt.inputs.begin(), merged_psbt.inputs.end(), FastRandomContext());
1952
5
    std::shuffle(merged_psbt.outputs.begin(), merged_psbt.outputs.end(), FastRandomContext());
1953
1954
5
    DataStream ssTx{};
1955
5
    ssTx << merged_psbt;
1956
5
    return EncodeBase64(ssTx);
1957
6
},
1958
2.60k
    };
1959
2.60k
}
1960
1961
static RPCMethod analyzepsbt()
1962
2.60k
{
1963
2.60k
    return RPCMethod{
1964
2.60k
        "analyzepsbt",
1965
2.60k
        "Analyzes and provides information about the current status of a PSBT and its inputs\n",
1966
2.60k
            {
1967
2.60k
                {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "A base64 string of a PSBT"}
1968
2.60k
            },
1969
2.60k
            RPCResult {
1970
2.60k
                RPCResult::Type::OBJ, "", "",
1971
2.60k
                {
1972
2.60k
                    {RPCResult::Type::ARR, "inputs", /*optional=*/true, "",
1973
2.60k
                    {
1974
2.60k
                        {RPCResult::Type::OBJ, "", "",
1975
2.60k
                        {
1976
2.60k
                            {RPCResult::Type::BOOL, "has_utxo", "Whether a UTXO is provided"},
1977
2.60k
                            {RPCResult::Type::BOOL, "is_final", "Whether the input is finalized"},
1978
2.60k
                            {RPCResult::Type::OBJ, "missing", /*optional=*/true, "Things that are missing that are required to complete this input",
1979
2.60k
                            {
1980
2.60k
                                {RPCResult::Type::ARR, "pubkeys", /*optional=*/true, "",
1981
2.60k
                                {
1982
2.60k
                                    {RPCResult::Type::STR_HEX, "keyid", "Public key ID, hash160 of the public key, of a public key whose BIP 32 derivation path is missing"},
1983
2.60k
                                }},
1984
2.60k
                                {RPCResult::Type::ARR, "signatures", /*optional=*/true, "",
1985
2.60k
                                {
1986
2.60k
                                    {RPCResult::Type::STR_HEX, "keyid", "Public key ID, hash160 of the public key, of a public key whose signature is missing"},
1987
2.60k
                                }},
1988
2.60k
                                {RPCResult::Type::STR_HEX, "redeemscript", /*optional=*/true, "Hash160 of the redeem script that is missing"},
1989
2.60k
                                {RPCResult::Type::STR_HEX, "witnessscript", /*optional=*/true, "SHA256 of the witness script that is missing"},
1990
2.60k
                            }},
1991
2.60k
                            {RPCResult::Type::STR, "next", /*optional=*/true, "Role of the next person that this input needs to go to"},
1992
2.60k
                        }},
1993
2.60k
                    }},
1994
2.60k
                    {RPCResult::Type::NUM, "estimated_vsize", /*optional=*/true, "Estimated vsize of the final signed transaction"},
1995
2.60k
                    {RPCResult::Type::STR_AMOUNT, "estimated_feerate", /*optional=*/true, "Estimated feerate of the final signed transaction in " + CURRENCY_UNIT + "/kvB. Shown only if all UTXO slots in the PSBT have been filled"},
1996
2.60k
                    {RPCResult::Type::STR_AMOUNT, "fee", /*optional=*/true, "The transaction fee paid. Shown only if all UTXO slots in the PSBT have been filled"},
1997
2.60k
                    {RPCResult::Type::STR, "next", "Role of the next person that this psbt needs to go to"},
1998
2.60k
                    {RPCResult::Type::STR, "error", /*optional=*/true, "Error message (if there is one)"},
1999
2.60k
                }
2000
2.60k
            },
2001
2.60k
            RPCExamples {
2002
2.60k
                HelpExampleCli("analyzepsbt", "\"psbt\"")
2003
2.60k
            },
2004
2.60k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
2005
2.60k
{
2006
    // Unserialize the transaction
2007
15
    util::Result<PartiallySignedTransaction> psbt_res = DecodeBase64PSBT(request.params[0].get_str());
2008
15
    if (!psbt_res) {
2009
1
        throw JSONRPCError(RPC_DESERIALIZATION_ERROR, strprintf("TX decode failed %s", util::ErrorString(psbt_res).original));
2010
1
    }
2011
14
    const PartiallySignedTransaction& psbtx = *psbt_res;
2012
2013
14
    PSBTAnalysis psbta = AnalyzePSBT(psbtx);
2014
2015
14
    UniValue result(UniValue::VOBJ);
2016
14
    UniValue inputs_result(UniValue::VARR);
2017
15
    for (const auto& input : psbta.inputs) {
2018
15
        UniValue input_univ(UniValue::VOBJ);
2019
15
        UniValue missing(UniValue::VOBJ);
2020
2021
15
        input_univ.pushKV("has_utxo", input.has_utxo);
2022
15
        input_univ.pushKV("is_final", input.is_final);
2023
15
        input_univ.pushKV("next", PSBTRoleName(input.next));
2024
2025
15
        if (!input.missing_pubkeys.empty()) {
2026
0
            UniValue missing_pubkeys_univ(UniValue::VARR);
2027
0
            for (const CKeyID& pubkey : input.missing_pubkeys) {
2028
0
                missing_pubkeys_univ.push_back(HexStr(pubkey));
2029
0
            }
2030
0
            missing.pushKV("pubkeys", std::move(missing_pubkeys_univ));
2031
0
        }
2032
15
        if (!input.missing_redeem_script.IsNull()) {
2033
0
            missing.pushKV("redeemscript", HexStr(input.missing_redeem_script));
2034
0
        }
2035
15
        if (!input.missing_witness_script.IsNull()) {
2036
0
            missing.pushKV("witnessscript", HexStr(input.missing_witness_script));
2037
0
        }
2038
15
        if (!input.missing_sigs.empty()) {
2039
1
            UniValue missing_sigs_univ(UniValue::VARR);
2040
1
            for (const CKeyID& pubkey : input.missing_sigs) {
2041
1
                missing_sigs_univ.push_back(HexStr(pubkey));
2042
1
            }
2043
1
            missing.pushKV("signatures", std::move(missing_sigs_univ));
2044
1
        }
2045
15
        if (!missing.getKeys().empty()) {
2046
1
            input_univ.pushKV("missing", std::move(missing));
2047
1
        }
2048
15
        inputs_result.push_back(std::move(input_univ));
2049
15
    }
2050
14
    if (!inputs_result.empty()) result.pushKV("inputs", std::move(inputs_result));
2051
2052
14
    if (psbta.estimated_vsize != std::nullopt) {
2053
6
        result.pushKV("estimated_vsize", *psbta.estimated_vsize);
2054
6
    }
2055
14
    if (psbta.estimated_feerate != std::nullopt) {
2056
6
        result.pushKV("estimated_feerate", ValueFromAmount(psbta.estimated_feerate->GetFeePerK()));
2057
6
    }
2058
14
    if (psbta.fee != std::nullopt) {
2059
9
        result.pushKV("fee", ValueFromAmount(*psbta.fee));
2060
9
    }
2061
14
    result.pushKV("next", PSBTRoleName(psbta.next));
2062
14
    if (!psbta.error.empty()) {
2063
3
        result.pushKV("error", psbta.error);
2064
3
    }
2065
2066
14
    return result;
2067
15
},
2068
2.60k
    };
2069
2.60k
}
2070
2071
RPCMethod descriptorprocesspsbt()
2072
2.61k
{
2073
2.61k
    return RPCMethod{
2074
2.61k
        "descriptorprocesspsbt",
2075
2.61k
        "Update all segwit inputs in a PSBT with information from output descriptors, the UTXO set or the mempool. \n"
2076
2.61k
                "Then, sign the inputs we are able to with information from the output descriptors. ",
2077
2.61k
                {
2078
2.61k
                    {"psbt", RPCArg::Type::STR, RPCArg::Optional::NO, "The transaction base64 string"},
2079
2.61k
                    {"descriptors", RPCArg::Type::ARR, RPCArg::Optional::NO, "An array of either strings or objects", {
2080
2.61k
                        {"", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "An output descriptor"},
2081
2.61k
                        {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "An object with an output descriptor and extra information", {
2082
2.61k
                             {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "An output descriptor"},
2083
2.61k
                             {"range", RPCArg::Type::RANGE, RPCArg::Default{1000}, "Up to what index HD chains should be explored (either end or [begin,end])"},
2084
2.61k
                        }},
2085
2.61k
                    }},
2086
2.61k
                    {"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"
2087
2.61k
            "       \"DEFAULT\"\n"
2088
2.61k
            "       \"ALL\"\n"
2089
2.61k
            "       \"NONE\"\n"
2090
2.61k
            "       \"SINGLE\"\n"
2091
2.61k
            "       \"ALL|ANYONECANPAY\"\n"
2092
2.61k
            "       \"NONE|ANYONECANPAY\"\n"
2093
2.61k
            "       \"SINGLE|ANYONECANPAY\""},
2094
2.61k
                    {"bip32derivs", RPCArg::Type::BOOL, RPCArg::Default{true}, "Include BIP 32 derivation paths for public keys if we know them"},
2095
2.61k
                    {"finalize", RPCArg::Type::BOOL, RPCArg::Default{true}, "Also finalize inputs if possible"},
2096
2.61k
                },
2097
2.61k
                RPCResult{
2098
2.61k
                    RPCResult::Type::OBJ, "", "",
2099
2.61k
                    {
2100
2.61k
                        {RPCResult::Type::STR, "psbt", "The base64-encoded partially signed transaction"},
2101
2.61k
                        {RPCResult::Type::BOOL, "complete", "If the transaction has a complete set of signatures"},
2102
2.61k
                        {RPCResult::Type::STR_HEX, "hex", /*optional=*/true, "The hex-encoded network transaction if complete"},
2103
2.61k
                    }
2104
2.61k
                },
2105
2.61k
                RPCExamples{
2106
2.61k
                    HelpExampleCli("descriptorprocesspsbt", "\"psbt\" \"[\\\"descriptor1\\\", \\\"descriptor2\\\"]\"") +
2107
2.61k
                    HelpExampleCli("descriptorprocesspsbt", "\"psbt\" \"[{\\\"desc\\\":\\\"mydescriptor\\\", \\\"range\\\":21}]\"")
2108
2.61k
                },
2109
2.61k
        [](const RPCMethod& self, const JSONRPCRequest& request) -> UniValue
2110
2.61k
{
2111
    // Add descriptor information to a signing provider
2112
21
    FlatSigningProvider provider;
2113
2114
21
    auto descs = request.params[1].get_array();
2115
111
    for (size_t i = 0; i < descs.size(); ++i) {
2116
90
        EvalDescriptorStringOrObject(descs[i], provider, /*expand_priv=*/true);
2117
90
    }
2118
2119
21
    std::optional<int> sighash_type = ParseSighashString(request.params[2]);
2120
21
    const bool bip32derivs{self.Arg<bool>("bip32derivs")};
2121
21
    const bool finalize{self.Arg<bool>("finalize")};
2122
2123
21
    const PartiallySignedTransaction& psbtx = ProcessPSBT(
2124
21
        request.params[0].get_str(),
2125
21
        request.context,
2126
21
        HidingSigningProvider(&provider, /*hide_secret=*/false, !bip32derivs),
2127
21
        sighash_type,
2128
21
        finalize);
2129
2130
    // Check whether or not all of the inputs are now correctly signed
2131
21
    bool complete = true;
2132
21
    const std::optional<PrecomputedTransactionData> txdata_opt{PrecomputePSBTData(psbtx)};
2133
21
    const PrecomputedTransactionData txdata{*CHECK_NONFATAL(txdata_opt)};
2134
42
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
2135
21
        complete = complete && PSBTInputSignedAndVerified(psbtx, i, &txdata);
2136
21
    }
2137
2138
21
    DataStream ssTx{};
2139
21
    ssTx << psbtx;
2140
2141
21
    UniValue result(UniValue::VOBJ);
2142
2143
21
    result.pushKV("psbt", EncodeBase64(ssTx));
2144
21
    result.pushKV("complete", complete);
2145
21
    if (complete) {
2146
4
        CMutableTransaction mtx;
2147
4
        PartiallySignedTransaction psbtx_copy = psbtx;
2148
4
        CHECK_NONFATAL(FinalizeAndExtractPSBT(psbtx_copy, mtx));
2149
4
        DataStream ssTx_final;
2150
4
        ssTx_final << TX_WITH_WITNESS(mtx);
2151
4
        result.pushKV("hex", HexStr(ssTx_final));
2152
4
    }
2153
21
    return result;
2154
21
},
2155
2.61k
    };
2156
2.61k
}
2157
2158
void RegisterRawTransactionRPCCommands(CRPCTable& t)
2159
1.44k
{
2160
1.44k
    static const CRPCCommand commands[]{
2161
1.44k
        {"rawtransactions", &getrawtransaction},
2162
1.44k
        {"rawtransactions", &createrawtransaction},
2163
1.44k
        {"rawtransactions", &decoderawtransaction},
2164
1.44k
        {"rawtransactions", &decodescript},
2165
1.44k
        {"rawtransactions", &combinerawtransaction},
2166
1.44k
        {"rawtransactions", &signrawtransactionwithkey},
2167
1.44k
        {"rawtransactions", &decodepsbt},
2168
1.44k
        {"rawtransactions", &combinepsbt},
2169
1.44k
        {"rawtransactions", &finalizepsbt},
2170
1.44k
        {"rawtransactions", &createpsbt},
2171
1.44k
        {"rawtransactions", &converttopsbt},
2172
1.44k
        {"rawtransactions", &utxoupdatepsbt},
2173
1.44k
        {"rawtransactions", &descriptorprocesspsbt},
2174
1.44k
        {"rawtransactions", &joinpsbts},
2175
1.44k
        {"rawtransactions", &analyzepsbt},
2176
1.44k
    };
2177
21.7k
    for (const auto& c : commands) {
2178
21.7k
        t.appendCommand(c.name, &c);
2179
21.7k
    }
2180
1.44k
}