Coverage Report

Created: 2026-07-14 18:13

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