Coverage Report

Created: 2026-05-30 09:47

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/rpc/rawtransaction_util.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 <rpc/rawtransaction_util.h>
7
8
#include <coins.h>
9
#include <consensus/amount.h>
10
#include <core_io.h>
11
#include <key_io.h>
12
#include <policy/policy.h>
13
#include <primitives/transaction.h>
14
#include <rpc/request.h>
15
#include <rpc/util.h>
16
#include <script/sign.h>
17
#include <script/signingprovider.h>
18
#include <tinyformat.h>
19
#include <univalue.h>
20
#include <util/rbf.h>
21
#include <util/string.h>
22
#include <util/strencodings.h>
23
#include <util/translation.h>
24
25
void AddInputs(CMutableTransaction& rawTx, const UniValue& inputs_in, std::optional<bool> rbf)
26
1.13k
{
27
1.13k
    UniValue inputs;
28
1.13k
    if (inputs_in.isNull()) {
29
314
        inputs = UniValue::VARR;
30
823
    } else {
31
823
        inputs = inputs_in.get_array();
32
823
    }
33
34
4.40k
    for (unsigned int idx = 0; idx < inputs.size(); idx++) {
35
3.27k
        const UniValue& input = inputs[idx];
36
3.27k
        const UniValue& o = input.get_obj();
37
38
3.27k
        Txid txid = Txid::FromUint256(ParseHashO(o, "txid"));
39
40
3.27k
        const UniValue& vout_v = o.find_value("vout");
41
3.27k
        if (!vout_v.isNum())
42
2
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
43
3.26k
        int nOutput = vout_v.getInt<int>();
44
3.26k
        if (nOutput < 0)
45
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
46
47
3.26k
        uint32_t nSequence;
48
49
3.26k
        if (rbf.value_or(true)) {
50
3.25k
            nSequence = MAX_BIP125_RBF_SEQUENCE; /* CTxIn::SEQUENCE_FINAL - 2 */
51
3.25k
        } else if (rawTx.nLockTime) {
52
1
            nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; /* CTxIn::SEQUENCE_FINAL - 1 */
53
7
        } else {
54
7
            nSequence = CTxIn::SEQUENCE_FINAL;
55
7
        }
56
57
        // set the sequence number if passed in the parameters object
58
3.26k
        const UniValue& sequenceObj = o.find_value("sequence");
59
3.26k
        if (sequenceObj.isNum()) {
60
54
            int64_t seqNr64 = sequenceObj.getInt<int64_t>();
61
54
            if (seqNr64 < 0 || seqNr64 > CTxIn::SEQUENCE_FINAL) {
62
2
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
63
52
            } else {
64
52
                nSequence = (uint32_t)seqNr64;
65
52
            }
66
54
        }
67
68
3.26k
        CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
69
70
3.26k
        rawTx.vin.push_back(in);
71
3.26k
    }
72
1.13k
}
73
74
UniValue NormalizeOutputs(const UniValue& outputs_in)
75
1.57k
{
76
1.57k
    if (outputs_in.isNull()) {
77
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output argument must be non-null");
78
0
    }
79
80
1.57k
    const bool outputs_is_obj = outputs_in.isObject();
81
1.57k
    UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array();
82
83
1.57k
    if (!outputs_is_obj) {
84
        // Translate array of key-value pairs into dict
85
895
        UniValue outputs_dict = UniValue(UniValue::VOBJ);
86
8.53k
        for (size_t i = 0; i < outputs.size(); ++i) {
87
7.64k
            const UniValue& output = outputs[i];
88
7.64k
            if (!output.isObject()) {
89
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected");
90
1
            }
91
7.64k
            if (output.size() != 1) {
92
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair must contain exactly one key");
93
1
            }
94
7.63k
            outputs_dict.pushKVs(output);
95
7.63k
        }
96
893
        outputs = std::move(outputs_dict);
97
893
    }
98
1.57k
    return outputs;
99
1.57k
}
100
101
std::vector<std::pair<CTxDestination, CAmount>> ParseOutputs(const UniValue& outputs)
102
2.84k
{
103
    // Duplicate checking
104
2.84k
    std::set<CTxDestination> destinations;
105
2.84k
    std::vector<std::pair<CTxDestination, CAmount>> parsed_outputs;
106
2.84k
    bool has_data{false};
107
14.9k
    for (const std::string& name_ : outputs.getKeys()) {
108
14.9k
        if (name_ == "data") {
109
24
            if (has_data) {
110
3
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, duplicate key: data");
111
3
            }
112
21
            has_data = true;
113
21
            std::vector<unsigned char> data = ParseHexV(outputs[name_].getValStr(), "Data");
114
21
            CTxDestination destination{CNoDestination{CScript() << OP_RETURN << data}};
115
21
            CAmount amount{0};
116
21
            parsed_outputs.emplace_back(destination, amount);
117
14.8k
        } else {
118
14.8k
            CTxDestination destination{DecodeDestination(name_)};
119
14.8k
            CAmount amount{AmountFromValue(outputs[name_])};
120
14.8k
            if (!IsValidDestination(destination)) {
121
1
                throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, std::string("Invalid Bitcoin address: ") + name_);
122
1
            }
123
124
14.8k
            if (!destinations.insert(destination).second) {
125
4
                throw JSONRPCError(RPC_INVALID_PARAMETER, std::string("Invalid parameter, duplicated address: ") + name_);
126
4
            }
127
14.8k
            parsed_outputs.emplace_back(destination, amount);
128
14.8k
        }
129
14.9k
    }
130
2.84k
    return parsed_outputs;
131
2.84k
}
132
133
void AddOutputs(CMutableTransaction& rawTx, const UniValue& outputs_in)
134
1.13k
{
135
1.13k
    UniValue outputs(UniValue::VOBJ);
136
1.13k
    outputs = NormalizeOutputs(outputs_in);
137
138
1.13k
    std::vector<std::pair<CTxDestination, CAmount>> parsed_outputs = ParseOutputs(outputs);
139
5.31k
    for (const auto& [destination, nAmount] : parsed_outputs) {
140
5.31k
        CScript scriptPubKey = GetScriptForDestination(destination);
141
142
5.31k
        CTxOut out(nAmount, scriptPubKey);
143
5.31k
        rawTx.vout.push_back(out);
144
5.31k
    }
145
1.13k
}
146
147
CMutableTransaction ConstructTransaction(const UniValue& inputs_in, const UniValue& outputs_in, const UniValue& locktime, std::optional<bool> rbf, const uint32_t version)
148
1.14k
{
149
1.14k
    CMutableTransaction rawTx;
150
151
1.14k
    if (!locktime.isNull()) {
152
160
        int64_t nLockTime = locktime.getInt<int64_t>();
153
160
        if (nLockTime < 0 || nLockTime > LOCKTIME_MAX)
154
2
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
155
158
        rawTx.nLockTime = nLockTime;
156
158
    }
157
158
1.13k
    if (version < TX_MIN_STANDARD_VERSION || version > TX_MAX_STANDARD_VERSION) {
159
2
        throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Invalid parameter, version out of range(%d~%d)", TX_MIN_STANDARD_VERSION, TX_MAX_STANDARD_VERSION));
160
2
    }
161
1.13k
    rawTx.version = version;
162
163
1.13k
    AddInputs(rawTx, inputs_in, rbf);
164
1.13k
    AddOutputs(rawTx, outputs_in);
165
166
1.13k
    if (rbf.has_value() && rbf.value() && rawTx.vin.size() > 0 && !SignalsOptInRBF(CTransaction(rawTx))) {
167
1
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter combination: Sequence number(s) contradict replaceable option");
168
1
    }
169
170
1.13k
    return rawTx;
171
1.13k
}
172
173
/** Pushes a JSON object for script verification or signing errors to vErrorsRet. */
174
static void TxInErrorToJSON(const CTxIn& txin, UniValue& vErrorsRet, const std::string& strMessage)
175
96
{
176
96
    UniValue entry(UniValue::VOBJ);
177
96
    entry.pushKV("txid", txin.prevout.hash.ToString());
178
96
    entry.pushKV("vout", txin.prevout.n);
179
96
    UniValue witness(UniValue::VARR);
180
598
    for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
181
502
        witness.push_back(HexStr(txin.scriptWitness.stack[i]));
182
502
    }
183
96
    entry.pushKV("witness", std::move(witness));
184
96
    entry.pushKV("scriptSig", HexStr(txin.scriptSig));
185
96
    entry.pushKV("sequence", txin.nSequence);
186
96
    entry.pushKV("error", strMessage);
187
96
    vErrorsRet.push_back(std::move(entry));
188
96
}
189
190
void ParsePrevouts(const UniValue& prevTxsUnival, FlatSigningProvider* keystore, std::map<COutPoint, Coin>& coins)
191
516
{
192
516
    if (!prevTxsUnival.isNull()) {
193
197
        const UniValue& prevTxs = prevTxsUnival.get_array();
194
311
        for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) {
195
198
            const UniValue& p = prevTxs[idx];
196
198
            if (!p.isObject()) {
197
0
                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
198
0
            }
199
200
198
            const UniValue& prevOut = p.get_obj();
201
202
198
            RPCTypeCheckObj(prevOut,
203
198
                {
204
198
                    {"txid", UniValueType(UniValue::VSTR)},
205
198
                    {"vout", UniValueType(UniValue::VNUM)},
206
198
                    {"scriptPubKey", UniValueType(UniValue::VSTR)},
207
198
                });
208
209
198
            Txid txid = Txid::FromUint256(ParseHashO(prevOut, "txid"));
210
211
198
            int nOut = prevOut.find_value("vout").getInt<int>();
212
198
            if (nOut < 0) {
213
0
                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout cannot be negative");
214
0
            }
215
216
198
            COutPoint out(txid, nOut);
217
198
            std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
218
198
            CScript scriptPubKey(pkData.begin(), pkData.end());
219
220
198
            {
221
198
                auto coin = coins.find(out);
222
198
                if (coin != coins.end() && !coin->second.IsSpent() && coin->second.out.scriptPubKey != scriptPubKey) {
223
0
                    std::string err("Previous output scriptPubKey mismatch:\n");
224
0
                    err = err + ScriptToAsmStr(coin->second.out.scriptPubKey) + "\nvs:\n"+
225
0
                        ScriptToAsmStr(scriptPubKey);
226
0
                    throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
227
0
                }
228
198
                Coin newcoin;
229
198
                newcoin.out.scriptPubKey = scriptPubKey;
230
198
                newcoin.out.nValue = MAX_MONEY;
231
198
                if (prevOut.exists("amount")) {
232
176
                    newcoin.out.nValue = AmountFromValue(prevOut.find_value("amount"));
233
176
                }
234
198
                newcoin.nHeight = 1;
235
198
                coins[out] = std::move(newcoin);
236
198
            }
237
238
            // if redeemScript and private keys were given, add redeemScript to the keystore so it can be signed
239
0
            const bool is_p2sh = scriptPubKey.IsPayToScriptHash();
240
198
            const bool is_p2wsh = scriptPubKey.IsPayToWitnessScriptHash();
241
198
            if (keystore && (is_p2sh || is_p2wsh)) {
242
177
                RPCTypeCheckObj(prevOut,
243
177
                    {
244
177
                        {"redeemScript", UniValueType(UniValue::VSTR)},
245
177
                        {"witnessScript", UniValueType(UniValue::VSTR)},
246
177
                    }, true);
247
177
                const UniValue& rs{prevOut.find_value("redeemScript")};
248
177
                const UniValue& ws{prevOut.find_value("witnessScript")};
249
177
                if (rs.isNull() && ws.isNull()) {
250
21
                    throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing redeemScript/witnessScript");
251
21
                }
252
253
                // work from witnessScript when possible
254
156
                std::vector<unsigned char> scriptData(!ws.isNull() ? ParseHexV(ws, "witnessScript") : ParseHexV(rs, "redeemScript"));
255
156
                CScript script(scriptData.begin(), scriptData.end());
256
156
                keystore->scripts.emplace(CScriptID(script), script);
257
                // Automatically also add the P2WSH wrapped version of the script (to deal with P2SH-P2WSH).
258
                // This is done for redeemScript only for compatibility, it is encouraged to use the explicit witnessScript field instead.
259
156
                CScript witness_output_script{GetScriptForDestination(WitnessV0ScriptHash(script))};
260
156
                keystore->scripts.emplace(CScriptID(witness_output_script), witness_output_script);
261
262
156
                if (!ws.isNull() && !rs.isNull()) {
263
                    // if both witnessScript and redeemScript are provided,
264
                    // they should either be the same (for backwards compat),
265
                    // or the redeemScript should be the encoded form of
266
                    // the witnessScript (ie, for p2sh-p2wsh)
267
45
                    if (ws.get_str() != rs.get_str()) {
268
24
                        std::vector<unsigned char> redeemScriptData(ParseHexV(rs, "redeemScript"));
269
24
                        CScript redeemScript(redeemScriptData.begin(), redeemScriptData.end());
270
24
                        if (redeemScript != witness_output_script) {
271
21
                            throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript does not correspond to witnessScript");
272
21
                        }
273
24
                    }
274
45
                }
275
276
135
                if (is_p2sh) {
277
87
                    const CTxDestination p2sh{ScriptHash(script)};
278
87
                    const CTxDestination p2sh_p2wsh{ScriptHash(witness_output_script)};
279
87
                    if (scriptPubKey == GetScriptForDestination(p2sh)) {
280
                        // traditional p2sh; arguably an error if
281
                        // we got here with rs.IsNull(), because
282
                        // that means the p2sh script was specified
283
                        // via witnessScript param, but for now
284
                        // we'll just quietly accept it
285
58
                    } else if (scriptPubKey == GetScriptForDestination(p2sh_p2wsh)) {
286
                        // p2wsh encoded as p2sh; ideally the witness
287
                        // script was specified in the witnessScript
288
                        // param, but also support specifying it via
289
                        // redeemScript param for backwards compat
290
                        // (in which case ws.IsNull() == true)
291
32
                    } else {
292
                        // otherwise, can't generate scriptPubKey from
293
                        // either script, so we got unusable parameters
294
26
                        throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey");
295
26
                    }
296
87
                } else if (is_p2wsh) {
297
                    // plain p2wsh; could throw an error if script
298
                    // was specified by redeemScript rather than
299
                    // witnessScript (ie, ws.IsNull() == true), but
300
                    // accept it for backwards compat
301
48
                    const CTxDestination p2wsh{WitnessV0ScriptHash(script)};
302
48
                    if (scriptPubKey != GetScriptForDestination(p2wsh)) {
303
16
                        throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey");
304
16
                    }
305
48
                }
306
135
            }
307
198
        }
308
197
    }
309
516
}
310
311
void SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const UniValue& hashType, UniValue& result)
312
100
{
313
100
    std::optional<int> nHashType = ParseSighashString(hashType);
314
100
    if (!nHashType) {
315
99
        nHashType = SIGHASH_DEFAULT;
316
99
    }
317
318
    // Script verification errors
319
100
    std::map<int, bilingual_str> input_errors;
320
321
100
    bool complete = SignTransaction(mtx, keystore, coins, {.sighash_type = *nHashType}, input_errors);
322
100
    SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
323
100
}
324
325
void SignTransactionResultToJSON(CMutableTransaction& mtx, bool complete, const std::map<COutPoint, Coin>& coins, const std::map<int, bilingual_str>& input_errors, UniValue& result)
326
421
{
327
    // Make errors UniValue
328
421
    UniValue vErrors(UniValue::VARR);
329
421
    for (const auto& err_pair : input_errors) {
330
98
        if (err_pair.second.original == "Missing amount") {
331
            // This particular error needs to be an exception for some reason
332
2
            throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing amount for %s", coins.at(mtx.vin.at(err_pair.first).prevout).out.ToString()));
333
2
        }
334
96
        TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second.original);
335
96
    }
336
337
419
    result.pushKV("hex", EncodeHexTx(CTransaction(mtx)));
338
419
    result.pushKV("complete", complete);
339
419
    if (!vErrors.empty()) {
340
94
        if (result.exists("errors")) {
341
0
            vErrors.push_backV(result["errors"].getValues());
342
0
        }
343
94
        result.pushKV("errors", std::move(vErrors));
344
94
    }
345
419
}
346
347
std::vector<RPCResult> TxDoc(const TxDocOptions& opts)
348
17.6k
{
349
17.6k
    std::optional<std::string> maybe_skip{};
350
17.6k
    if (opts.elision_description) maybe_skip.emplace();
351
17.6k
    return {
352
17.6k
        {RPCResult::Type::STR_HEX, "txid", opts.txid_field_doc, {}, {.print_elision=opts.elision_description}},
353
17.6k
        {RPCResult::Type::STR_HEX, "hash", "The transaction hash (differs from txid for witness transactions)", {}, {.print_elision=maybe_skip}},
354
17.6k
        {RPCResult::Type::NUM, "size", "The serialized transaction size", {}, {.print_elision=maybe_skip}},
355
17.6k
        {RPCResult::Type::NUM, "vsize", "The virtual transaction size (differs from size for witness transactions)", {}, {.print_elision=maybe_skip}},
356
17.6k
        {RPCResult::Type::NUM, "weight", "The transaction's weight (between vsize*4-3 and vsize*4)", {}, {.print_elision=maybe_skip}},
357
17.6k
        {RPCResult::Type::NUM, "version", "The version", {}, {.print_elision=maybe_skip}},
358
17.6k
        {RPCResult::Type::NUM_TIME, "locktime", "The lock time", {}, {.print_elision=maybe_skip}},
359
17.6k
        {RPCResult::Type::ARR, "vin", "",
360
17.6k
        {
361
17.6k
            {RPCResult::Type::OBJ, "", "",
362
17.6k
            {
363
17.6k
                {RPCResult::Type::STR_HEX, "coinbase", /*optional=*/true, "The coinbase value (only if coinbase transaction)"},
364
17.6k
                {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id (if not coinbase transaction)"},
365
17.6k
                {RPCResult::Type::NUM, "vout", /*optional=*/true, "The output number (if not coinbase transaction)"},
366
17.6k
                {RPCResult::Type::OBJ, "scriptSig", /*optional=*/true, "The script (if not coinbase transaction)",
367
17.6k
                {
368
17.6k
                    {RPCResult::Type::STR, "asm", "Disassembly of the signature script"},
369
17.6k
                    {RPCResult::Type::STR_HEX, "hex", "The raw signature script bytes, hex-encoded"},
370
17.6k
                }},
371
17.6k
                {RPCResult::Type::ARR, "txinwitness", /*optional=*/true, "",
372
17.6k
                {
373
17.6k
                    {RPCResult::Type::STR_HEX, "hex", "hex-encoded witness data (if any)"},
374
17.6k
                }},
375
17.6k
                {RPCResult::Type::NUM, "sequence", "The script sequence number"},
376
17.6k
            }},
377
17.6k
        }, {.print_elision=maybe_skip}},
378
17.6k
        {RPCResult::Type::ARR, "vout", "",
379
17.6k
        {
380
17.6k
            {RPCResult::Type::OBJ, "", "", Cat(
381
17.6k
                {
382
17.6k
                    {RPCResult::Type::STR_AMOUNT, "value", "The value in " + CURRENCY_UNIT},
383
17.6k
                    {RPCResult::Type::NUM, "n", "index"},
384
17.6k
                    {RPCResult::Type::OBJ, "scriptPubKey", "", ScriptPubKeyDoc()},
385
17.6k
                },
386
17.6k
                    opts.wallet ?
387
1.27k
                    std::vector<RPCResult>{{RPCResult::Type::BOOL, "ischange", /*optional=*/true, "Output script is change (only present if true)"}} :
388
17.6k
                    std::vector<RPCResult>{}
389
17.6k
                )
390
17.6k
            },
391
17.6k
        }, {.print_elision=maybe_skip}},
392
17.6k
    };
393
17.6k
}