Coverage Report

Created: 2026-04-29 19:21

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.12k
{
27
1.12k
    UniValue inputs;
28
1.12k
    if (inputs_in.isNull()) {
29
316
        inputs = UniValue::VARR;
30
807
    } else {
31
807
        inputs = inputs_in.get_array();
32
807
    }
33
34
4.37k
    for (unsigned int idx = 0; idx < inputs.size(); idx++) {
35
3.25k
        const UniValue& input = inputs[idx];
36
3.25k
        const UniValue& o = input.get_obj();
37
38
3.25k
        Txid txid = Txid::FromUint256(ParseHashO(o, "txid"));
39
40
3.25k
        const UniValue& vout_v = o.find_value("vout");
41
3.25k
        if (!vout_v.isNum())
42
2
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
43
3.25k
        int nOutput = vout_v.getInt<int>();
44
3.25k
        if (nOutput < 0)
45
1
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout cannot be negative");
46
47
3.24k
        uint32_t nSequence;
48
49
3.24k
        if (rbf.value_or(true)) {
50
3.02k
            nSequence = MAX_BIP125_RBF_SEQUENCE; /* CTxIn::SEQUENCE_FINAL - 2 */
51
3.02k
        } else if (rawTx.nLockTime) {
52
2
            nSequence = CTxIn::MAX_SEQUENCE_NONFINAL; /* CTxIn::SEQUENCE_FINAL - 1 */
53
224
        } else {
54
224
            nSequence = CTxIn::SEQUENCE_FINAL;
55
224
        }
56
57
        // set the sequence number if passed in the parameters object
58
3.24k
        const UniValue& sequenceObj = o.find_value("sequence");
59
3.24k
        if (sequenceObj.isNum()) {
60
53
            int64_t seqNr64 = sequenceObj.getInt<int64_t>();
61
53
            if (seqNr64 < 0 || seqNr64 > CTxIn::SEQUENCE_FINAL) {
62
2
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, sequence number is out of range");
63
51
            } else {
64
51
                nSequence = (uint32_t)seqNr64;
65
51
            }
66
53
        }
67
68
3.24k
        CTxIn in(COutPoint(txid, nOutput), CScript(), nSequence);
69
70
3.24k
        rawTx.vin.push_back(in);
71
3.24k
    }
72
1.12k
}
73
74
UniValue NormalizeOutputs(const UniValue& outputs_in)
75
1.56k
{
76
1.56k
    if (outputs_in.isNull()) {
77
0
        throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, output argument must be non-null");
78
0
    }
79
80
1.56k
    const bool outputs_is_obj = outputs_in.isObject();
81
1.56k
    UniValue outputs = outputs_is_obj ? outputs_in.get_obj() : outputs_in.get_array();
82
83
1.56k
    if (!outputs_is_obj) {
84
        // Translate array of key-value pairs into dict
85
876
        UniValue outputs_dict = UniValue(UniValue::VOBJ);
86
8.49k
        for (size_t i = 0; i < outputs.size(); ++i) {
87
7.62k
            const UniValue& output = outputs[i];
88
7.62k
            if (!output.isObject()) {
89
1
                throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, key-value pair not an object as expected");
90
1
            }
91
7.62k
            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.62k
            outputs_dict.pushKVs(output);
95
7.62k
        }
96
874
        outputs = std::move(outputs_dict);
97
874
    }
98
1.56k
    return outputs;
99
1.56k
}
100
101
std::vector<std::pair<CTxDestination, CAmount>> ParseOutputs(const UniValue& outputs)
102
2.83k
{
103
    // Duplicate checking
104
2.83k
    std::set<CTxDestination> destinations;
105
2.83k
    std::vector<std::pair<CTxDestination, CAmount>> parsed_outputs;
106
2.83k
    bool has_data{false};
107
14.8k
    for (const std::string& name_ : outputs.getKeys()) {
108
14.8k
        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.8k
    }
130
2.82k
    return parsed_outputs;
131
2.83k
}
132
133
void AddOutputs(CMutableTransaction& rawTx, const UniValue& outputs_in)
134
1.12k
{
135
1.12k
    UniValue outputs(UniValue::VOBJ);
136
1.12k
    outputs = NormalizeOutputs(outputs_in);
137
138
1.12k
    std::vector<std::pair<CTxDestination, CAmount>> parsed_outputs = ParseOutputs(outputs);
139
5.29k
    for (const auto& [destination, nAmount] : parsed_outputs) {
140
5.29k
        CScript scriptPubKey = GetScriptForDestination(destination);
141
142
5.29k
        CTxOut out(nAmount, scriptPubKey);
143
5.29k
        rawTx.vout.push_back(out);
144
5.29k
    }
145
1.12k
}
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.12k
{
149
1.12k
    CMutableTransaction rawTx;
150
151
1.12k
    if (!locktime.isNull()) {
152
161
        int64_t nLockTime = locktime.getInt<int64_t>();
153
161
        if (nLockTime < 0 || nLockTime > LOCKTIME_MAX)
154
2
            throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, locktime out of range");
155
159
        rawTx.nLockTime = nLockTime;
156
159
    }
157
158
1.12k
    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.12k
    rawTx.version = version;
162
163
1.12k
    AddInputs(rawTx, inputs_in, rbf);
164
1.12k
    AddOutputs(rawTx, outputs_in);
165
166
1.12k
    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.12k
    return rawTx;
171
1.12k
}
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
92
{
176
92
    UniValue entry(UniValue::VOBJ);
177
92
    entry.pushKV("txid", txin.prevout.hash.ToString());
178
92
    entry.pushKV("vout", txin.prevout.n);
179
92
    UniValue witness(UniValue::VARR);
180
578
    for (unsigned int i = 0; i < txin.scriptWitness.stack.size(); i++) {
181
486
        witness.push_back(HexStr(txin.scriptWitness.stack[i]));
182
486
    }
183
92
    entry.pushKV("witness", std::move(witness));
184
92
    entry.pushKV("scriptSig", HexStr(txin.scriptSig));
185
92
    entry.pushKV("sequence", txin.nSequence);
186
92
    entry.pushKV("error", strMessage);
187
92
    vErrorsRet.push_back(std::move(entry));
188
92
}
189
190
void ParsePrevouts(const UniValue& prevTxsUnival, FlatSigningProvider* keystore, std::map<COutPoint, Coin>& coins)
191
510
{
192
510
    if (!prevTxsUnival.isNull()) {
193
189
        const UniValue& prevTxs = prevTxsUnival.get_array();
194
299
        for (unsigned int idx = 0; idx < prevTxs.size(); ++idx) {
195
190
            const UniValue& p = prevTxs[idx];
196
190
            if (!p.isObject()) {
197
0
                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
198
0
            }
199
200
190
            const UniValue& prevOut = p.get_obj();
201
202
190
            RPCTypeCheckObj(prevOut,
203
190
                {
204
190
                    {"txid", UniValueType(UniValue::VSTR)},
205
190
                    {"vout", UniValueType(UniValue::VNUM)},
206
190
                    {"scriptPubKey", UniValueType(UniValue::VSTR)},
207
190
                });
208
209
190
            Txid txid = Txid::FromUint256(ParseHashO(prevOut, "txid"));
210
211
190
            int nOut = prevOut.find_value("vout").getInt<int>();
212
190
            if (nOut < 0) {
213
0
                throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout cannot be negative");
214
0
            }
215
216
190
            COutPoint out(txid, nOut);
217
190
            std::vector<unsigned char> pkData(ParseHexO(prevOut, "scriptPubKey"));
218
190
            CScript scriptPubKey(pkData.begin(), pkData.end());
219
220
190
            {
221
190
                auto coin = coins.find(out);
222
190
                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
190
                Coin newcoin;
229
190
                newcoin.out.scriptPubKey = scriptPubKey;
230
190
                newcoin.out.nValue = MAX_MONEY;
231
190
                if (prevOut.exists("amount")) {
232
168
                    newcoin.out.nValue = AmountFromValue(prevOut.find_value("amount"));
233
168
                }
234
190
                newcoin.nHeight = 1;
235
190
                coins[out] = std::move(newcoin);
236
190
            }
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
190
            const bool is_p2wsh = scriptPubKey.IsPayToWitnessScriptHash();
241
190
            if (keystore && (is_p2sh || is_p2wsh)) {
242
169
                RPCTypeCheckObj(prevOut,
243
169
                    {
244
169
                        {"redeemScript", UniValueType(UniValue::VSTR)},
245
169
                        {"witnessScript", UniValueType(UniValue::VSTR)},
246
169
                    }, true);
247
169
                const UniValue& rs{prevOut.find_value("redeemScript")};
248
169
                const UniValue& ws{prevOut.find_value("witnessScript")};
249
169
                if (rs.isNull() && ws.isNull()) {
250
20
                    throw JSONRPCError(RPC_INVALID_PARAMETER, "Missing redeemScript/witnessScript");
251
20
                }
252
253
                // work from witnessScript when possible
254
149
                std::vector<unsigned char> scriptData(!ws.isNull() ? ParseHexV(ws, "witnessScript") : ParseHexV(rs, "redeemScript"));
255
149
                CScript script(scriptData.begin(), scriptData.end());
256
149
                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
149
                CScript witness_output_script{GetScriptForDestination(WitnessV0ScriptHash(script))};
260
149
                keystore->scripts.emplace(CScriptID(witness_output_script), witness_output_script);
261
262
149
                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
43
                    if (ws.get_str() != rs.get_str()) {
268
23
                        std::vector<unsigned char> redeemScriptData(ParseHexV(rs, "redeemScript"));
269
23
                        CScript redeemScript(redeemScriptData.begin(), redeemScriptData.end());
270
23
                        if (redeemScript != witness_output_script) {
271
20
                            throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript does not correspond to witnessScript");
272
20
                        }
273
23
                    }
274
43
                }
275
276
129
                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
42
                    const CTxDestination p2wsh{WitnessV0ScriptHash(script)};
302
42
                    if (scriptPubKey != GetScriptForDestination(p2wsh)) {
303
14
                        throw JSONRPCError(RPC_INVALID_PARAMETER, "redeemScript/witnessScript does not match scriptPubKey");
304
14
                    }
305
42
                }
306
129
            }
307
190
        }
308
189
    }
309
510
}
310
311
void SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const UniValue& hashType, UniValue& result)
312
96
{
313
96
    std::optional<int> nHashType = ParseSighashString(hashType);
314
96
    if (!nHashType) {
315
95
        nHashType = SIGHASH_DEFAULT;
316
95
    }
317
318
    // Script verification errors
319
96
    std::map<int, bilingual_str> input_errors;
320
321
96
    bool complete = SignTransaction(mtx, keystore, coins, {.sighash_type = *nHashType}, input_errors);
322
96
    SignTransactionResultToJSON(mtx, complete, coins, input_errors, result);
323
96
}
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
419
{
327
    // Make errors UniValue
328
419
    UniValue vErrors(UniValue::VARR);
329
419
    for (const auto& err_pair : input_errors) {
330
94
        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
92
        TxInErrorToJSON(mtx.vin.at(err_pair.first), vErrors, err_pair.second.original);
335
92
    }
336
337
417
    result.pushKV("hex", EncodeHexTx(CTransaction(mtx)));
338
417
    result.pushKV("complete", complete);
339
417
    if (!vErrors.empty()) {
340
90
        if (result.exists("errors")) {
341
0
            vErrors.push_backV(result["errors"].getValues());
342
0
        }
343
90
        result.pushKV("errors", std::move(vErrors));
344
90
    }
345
417
}
346
347
std::vector<RPCResult> TxDoc(const TxDocOptions& opts)
348
17.0k
{
349
17.0k
    std::optional<std::string> maybe_skip{};
350
17.0k
    if (opts.elision_description) maybe_skip.emplace();
351
17.0k
    return {
352
17.0k
        {RPCResult::Type::STR_HEX, "txid", opts.txid_field_doc, {}, {.print_elision=opts.elision_description}},
353
17.0k
        {RPCResult::Type::STR_HEX, "hash", "The transaction hash (differs from txid for witness transactions)", {}, {.print_elision=maybe_skip}},
354
17.0k
        {RPCResult::Type::NUM, "size", "The serialized transaction size", {}, {.print_elision=maybe_skip}},
355
17.0k
        {RPCResult::Type::NUM, "vsize", "The virtual transaction size (differs from size for witness transactions)", {}, {.print_elision=maybe_skip}},
356
17.0k
        {RPCResult::Type::NUM, "weight", "The transaction's weight (between vsize*4-3 and vsize*4)", {}, {.print_elision=maybe_skip}},
357
17.0k
        {RPCResult::Type::NUM, "version", "The version", {}, {.print_elision=maybe_skip}},
358
17.0k
        {RPCResult::Type::NUM_TIME, "locktime", "The lock time", {}, {.print_elision=maybe_skip}},
359
17.0k
        {RPCResult::Type::ARR, "vin", "",
360
17.0k
        {
361
17.0k
            {RPCResult::Type::OBJ, "", "",
362
17.0k
            {
363
17.0k
                {RPCResult::Type::STR_HEX, "coinbase", /*optional=*/true, "The coinbase value (only if coinbase transaction)"},
364
17.0k
                {RPCResult::Type::STR_HEX, "txid", /*optional=*/true, "The transaction id (if not coinbase transaction)"},
365
17.0k
                {RPCResult::Type::NUM, "vout", /*optional=*/true, "The output number (if not coinbase transaction)"},
366
17.0k
                {RPCResult::Type::OBJ, "scriptSig", /*optional=*/true, "The script (if not coinbase transaction)",
367
17.0k
                {
368
17.0k
                    {RPCResult::Type::STR, "asm", "Disassembly of the signature script"},
369
17.0k
                    {RPCResult::Type::STR_HEX, "hex", "The raw signature script bytes, hex-encoded"},
370
17.0k
                }},
371
17.0k
                {RPCResult::Type::ARR, "txinwitness", /*optional=*/true, "",
372
17.0k
                {
373
17.0k
                    {RPCResult::Type::STR_HEX, "hex", "hex-encoded witness data (if any)"},
374
17.0k
                }},
375
17.0k
                {RPCResult::Type::NUM, "sequence", "The script sequence number"},
376
17.0k
            }},
377
17.0k
        }, {.print_elision=maybe_skip}},
378
17.0k
        {RPCResult::Type::ARR, "vout", "",
379
17.0k
        {
380
17.0k
            {RPCResult::Type::OBJ, "", "", Cat(
381
17.0k
                {
382
17.0k
                    {RPCResult::Type::STR_AMOUNT, "value", "The value in " + CURRENCY_UNIT},
383
17.0k
                    {RPCResult::Type::NUM, "n", "index"},
384
17.0k
                    {RPCResult::Type::OBJ, "scriptPubKey", "", ScriptPubKeyDoc()},
385
17.0k
                },
386
17.0k
                    opts.wallet ?
387
1.28k
                    std::vector<RPCResult>{{RPCResult::Type::BOOL, "ischange", /*optional=*/true, "Output script is change (only present if true)"}} :
388
17.0k
                    std::vector<RPCResult>{}
389
17.0k
                )
390
17.0k
            },
391
17.0k
        }, {.print_elision=maybe_skip}},
392
17.0k
    };
393
17.0k
}