Coverage Report

Created: 2026-09-02 14:16

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