Bitcoin Core Fuzz Coverage Report for wallet_tx_can_be_bumped

Coverage Report

Created: 2025-11-19 11:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/Users/brunogarcia/projects/bitcoin-core-dev/src/psbt.cpp
Line
Count
Source
1
// Copyright (c) 2009-present The Bitcoin Core developers
2
// Distributed under the MIT software license, see the accompanying
3
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5
#include <psbt.h>
6
7
#include <common/types.h>
8
#include <node/types.h>
9
#include <policy/policy.h>
10
#include <script/signingprovider.h>
11
#include <util/check.h>
12
#include <util/strencodings.h>
13
14
using common::PSBTError;
15
16
0
PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx) : tx(tx)
17
0
{
18
0
    inputs.resize(tx.vin.size());
19
0
    outputs.resize(tx.vout.size());
20
0
}
21
22
bool PartiallySignedTransaction::IsNull() const
23
0
{
24
0
    return !tx && inputs.empty() && outputs.empty() && unknown.empty();
25
0
}
26
27
bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt)
28
0
{
29
    // Prohibited to merge two PSBTs over different transactions
30
0
    if (tx->GetHash() != psbt.tx->GetHash()) {
31
0
        return false;
32
0
    }
33
34
0
    for (unsigned int i = 0; i < inputs.size(); ++i) {
35
0
        inputs[i].Merge(psbt.inputs[i]);
36
0
    }
37
0
    for (unsigned int i = 0; i < outputs.size(); ++i) {
38
0
        outputs[i].Merge(psbt.outputs[i]);
39
0
    }
40
0
    for (auto& xpub_pair : psbt.m_xpubs) {
41
0
        if (m_xpubs.count(xpub_pair.first) == 0) {
42
0
            m_xpubs[xpub_pair.first] = xpub_pair.second;
43
0
        } else {
44
0
            m_xpubs[xpub_pair.first].insert(xpub_pair.second.begin(), xpub_pair.second.end());
45
0
        }
46
0
    }
47
0
    unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
48
49
0
    return true;
50
0
}
51
52
bool PartiallySignedTransaction::AddInput(const CTxIn& txin, PSBTInput& psbtin)
53
0
{
54
0
    if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) {
55
0
        return false;
56
0
    }
57
0
    tx->vin.push_back(txin);
58
0
    psbtin.partial_sigs.clear();
59
0
    psbtin.final_script_sig.clear();
60
0
    psbtin.final_script_witness.SetNull();
61
0
    inputs.push_back(psbtin);
62
0
    return true;
63
0
}
64
65
bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput& psbtout)
66
0
{
67
0
    tx->vout.push_back(txout);
68
0
    outputs.push_back(psbtout);
69
0
    return true;
70
0
}
71
72
bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const
73
0
{
74
0
    const PSBTInput& input = inputs[input_index];
75
0
    uint32_t prevout_index = tx->vin[input_index].prevout.n;
76
0
    if (input.non_witness_utxo) {
77
0
        if (prevout_index >= input.non_witness_utxo->vout.size()) {
78
0
            return false;
79
0
        }
80
0
        if (input.non_witness_utxo->GetHash() != tx->vin[input_index].prevout.hash) {
81
0
            return false;
82
0
        }
83
0
        utxo = input.non_witness_utxo->vout[prevout_index];
84
0
    } else if (!input.witness_utxo.IsNull()) {
85
0
        utxo = input.witness_utxo;
86
0
    } else {
87
0
        return false;
88
0
    }
89
0
    return true;
90
0
}
91
92
bool PSBTInput::IsNull() const
93
0
{
94
0
    return !non_witness_utxo && witness_utxo.IsNull() && partial_sigs.empty() && unknown.empty() && hd_keypaths.empty() && redeem_script.empty() && witness_script.empty();
95
0
}
96
97
void PSBTInput::FillSignatureData(SignatureData& sigdata) const
98
0
{
99
0
    if (!final_script_sig.empty()) {
100
0
        sigdata.scriptSig = final_script_sig;
101
0
        sigdata.complete = true;
102
0
    }
103
0
    if (!final_script_witness.IsNull()) {
104
0
        sigdata.scriptWitness = final_script_witness;
105
0
        sigdata.complete = true;
106
0
    }
107
0
    if (sigdata.complete) {
108
0
        return;
109
0
    }
110
111
0
    sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
112
0
    if (!redeem_script.empty()) {
113
0
        sigdata.redeem_script = redeem_script;
114
0
    }
115
0
    if (!witness_script.empty()) {
116
0
        sigdata.witness_script = witness_script;
117
0
    }
118
0
    for (const auto& key_pair : hd_keypaths) {
119
0
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
120
0
    }
121
0
    if (!m_tap_key_sig.empty()) {
122
0
        sigdata.taproot_key_path_sig = m_tap_key_sig;
123
0
    }
124
0
    for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
125
0
        sigdata.taproot_script_sigs.emplace(pubkey_leaf, sig);
126
0
    }
127
0
    if (!m_tap_internal_key.IsNull()) {
128
0
        sigdata.tr_spenddata.internal_key = m_tap_internal_key;
129
0
    }
130
0
    if (!m_tap_merkle_root.IsNull()) {
131
0
        sigdata.tr_spenddata.merkle_root = m_tap_merkle_root;
132
0
    }
133
0
    for (const auto& [leaf_script, control_block] : m_tap_scripts) {
134
0
        sigdata.tr_spenddata.scripts.emplace(leaf_script, control_block);
135
0
    }
136
0
    for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
137
0
        sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
138
0
        sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
139
0
    }
140
0
    for (const auto& [hash, preimage] : ripemd160_preimages) {
141
0
        sigdata.ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
142
0
    }
143
0
    for (const auto& [hash, preimage] : sha256_preimages) {
144
0
        sigdata.sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
145
0
    }
146
0
    for (const auto& [hash, preimage] : hash160_preimages) {
147
0
        sigdata.hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
148
0
    }
149
0
    for (const auto& [hash, preimage] : hash256_preimages) {
150
0
        sigdata.hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
151
0
    }
152
0
    sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
153
0
    for (const auto& [agg_key_lh, pubnonces] : m_musig2_pubnonces) {
154
0
        sigdata.musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
155
0
    }
156
0
    for (const auto& [agg_key_lh, psigs] : m_musig2_partial_sigs) {
157
0
        sigdata.musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
158
0
    }
159
0
}
160
161
void PSBTInput::FromSignatureData(const SignatureData& sigdata)
162
0
{
163
0
    if (sigdata.complete) {
164
0
        partial_sigs.clear();
165
0
        hd_keypaths.clear();
166
0
        redeem_script.clear();
167
0
        witness_script.clear();
168
169
0
        if (!sigdata.scriptSig.empty()) {
170
0
            final_script_sig = sigdata.scriptSig;
171
0
        }
172
0
        if (!sigdata.scriptWitness.IsNull()) {
173
0
            final_script_witness = sigdata.scriptWitness;
174
0
        }
175
0
        return;
176
0
    }
177
178
0
    partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
179
0
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
180
0
        redeem_script = sigdata.redeem_script;
181
0
    }
182
0
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
183
0
        witness_script = sigdata.witness_script;
184
0
    }
185
0
    for (const auto& entry : sigdata.misc_pubkeys) {
186
0
        hd_keypaths.emplace(entry.second);
187
0
    }
188
0
    if (!sigdata.taproot_key_path_sig.empty()) {
189
0
        m_tap_key_sig = sigdata.taproot_key_path_sig;
190
0
    }
191
0
    for (const auto& [pubkey_leaf, sig] : sigdata.taproot_script_sigs) {
192
0
        m_tap_script_sigs.emplace(pubkey_leaf, sig);
193
0
    }
194
0
    if (!sigdata.tr_spenddata.internal_key.IsNull()) {
195
0
        m_tap_internal_key = sigdata.tr_spenddata.internal_key;
196
0
    }
197
0
    if (!sigdata.tr_spenddata.merkle_root.IsNull()) {
198
0
        m_tap_merkle_root = sigdata.tr_spenddata.merkle_root;
199
0
    }
200
0
    for (const auto& [leaf_script, control_block] : sigdata.tr_spenddata.scripts) {
201
0
        m_tap_scripts.emplace(leaf_script, control_block);
202
0
    }
203
0
    for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
204
0
        m_tap_bip32_paths.emplace(pubkey, leaf_origin);
205
0
    }
206
0
    m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
207
0
    for (const auto& [agg_key_lh, pubnonces] : sigdata.musig2_pubnonces) {
208
0
        m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
209
0
    }
210
0
    for (const auto& [agg_key_lh, psigs] : sigdata.musig2_partial_sigs) {
211
0
        m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
212
0
    }
213
0
}
214
215
void PSBTInput::Merge(const PSBTInput& input)
216
0
{
217
0
    if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
218
0
    if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
219
0
        witness_utxo = input.witness_utxo;
220
0
    }
221
222
0
    partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
223
0
    ripemd160_preimages.insert(input.ripemd160_preimages.begin(), input.ripemd160_preimages.end());
224
0
    sha256_preimages.insert(input.sha256_preimages.begin(), input.sha256_preimages.end());
225
0
    hash160_preimages.insert(input.hash160_preimages.begin(), input.hash160_preimages.end());
226
0
    hash256_preimages.insert(input.hash256_preimages.begin(), input.hash256_preimages.end());
227
0
    hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
228
0
    unknown.insert(input.unknown.begin(), input.unknown.end());
229
0
    m_tap_script_sigs.insert(input.m_tap_script_sigs.begin(), input.m_tap_script_sigs.end());
230
0
    m_tap_scripts.insert(input.m_tap_scripts.begin(), input.m_tap_scripts.end());
231
0
    m_tap_bip32_paths.insert(input.m_tap_bip32_paths.begin(), input.m_tap_bip32_paths.end());
232
233
0
    if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
234
0
    if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
235
0
    if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
236
0
    if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
237
0
    if (m_tap_key_sig.empty() && !input.m_tap_key_sig.empty()) m_tap_key_sig = input.m_tap_key_sig;
238
0
    if (m_tap_internal_key.IsNull() && !input.m_tap_internal_key.IsNull()) m_tap_internal_key = input.m_tap_internal_key;
239
0
    if (m_tap_merkle_root.IsNull() && !input.m_tap_merkle_root.IsNull()) m_tap_merkle_root = input.m_tap_merkle_root;
240
0
    m_musig2_participants.insert(input.m_musig2_participants.begin(), input.m_musig2_participants.end());
241
0
    for (const auto& [agg_key_lh, pubnonces] : input.m_musig2_pubnonces) {
242
0
        m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
243
0
    }
244
0
    for (const auto& [agg_key_lh, psigs] : input.m_musig2_partial_sigs) {
245
0
        m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
246
0
    }
247
0
}
248
249
void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
250
0
{
251
0
    if (!redeem_script.empty()) {
252
0
        sigdata.redeem_script = redeem_script;
253
0
    }
254
0
    if (!witness_script.empty()) {
255
0
        sigdata.witness_script = witness_script;
256
0
    }
257
0
    for (const auto& key_pair : hd_keypaths) {
258
0
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
259
0
    }
260
0
    if (!m_tap_tree.empty() && m_tap_internal_key.IsFullyValid()) {
261
0
        TaprootBuilder builder;
262
0
        for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
263
0
            builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
264
0
        }
265
0
        assert(builder.IsComplete());
266
0
        builder.Finalize(m_tap_internal_key);
267
0
        TaprootSpendData spenddata = builder.GetSpendData();
268
269
0
        sigdata.tr_spenddata.internal_key = m_tap_internal_key;
270
0
        sigdata.tr_spenddata.Merge(spenddata);
271
0
    }
272
0
    for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
273
0
        sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
274
0
        sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
275
0
    }
276
0
    sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
277
0
}
278
279
void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
280
0
{
281
0
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
282
0
        redeem_script = sigdata.redeem_script;
283
0
    }
284
0
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
285
0
        witness_script = sigdata.witness_script;
286
0
    }
287
0
    for (const auto& entry : sigdata.misc_pubkeys) {
288
0
        hd_keypaths.emplace(entry.second);
289
0
    }
290
0
    if (!sigdata.tr_spenddata.internal_key.IsNull()) {
291
0
        m_tap_internal_key = sigdata.tr_spenddata.internal_key;
292
0
    }
293
0
    if (sigdata.tr_builder.has_value() && sigdata.tr_builder->HasScripts()) {
294
0
        m_tap_tree = sigdata.tr_builder->GetTreeTuples();
295
0
    }
296
0
    for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
297
0
        m_tap_bip32_paths.emplace(pubkey, leaf_origin);
298
0
    }
299
0
    m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
300
0
}
301
302
bool PSBTOutput::IsNull() const
303
0
{
304
0
    return redeem_script.empty() && witness_script.empty() && hd_keypaths.empty() && unknown.empty();
305
0
}
306
307
void PSBTOutput::Merge(const PSBTOutput& output)
308
0
{
309
0
    hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
310
0
    unknown.insert(output.unknown.begin(), output.unknown.end());
311
0
    m_tap_bip32_paths.insert(output.m_tap_bip32_paths.begin(), output.m_tap_bip32_paths.end());
312
313
0
    if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
314
0
    if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
315
0
    if (m_tap_internal_key.IsNull() && !output.m_tap_internal_key.IsNull()) m_tap_internal_key = output.m_tap_internal_key;
316
0
    if (m_tap_tree.empty() && !output.m_tap_tree.empty()) m_tap_tree = output.m_tap_tree;
317
0
    m_musig2_participants.insert(output.m_musig2_participants.begin(), output.m_musig2_participants.end());
318
0
}
319
320
bool PSBTInputSigned(const PSBTInput& input)
321
0
{
322
0
    return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
323
0
}
324
325
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
326
0
{
327
0
    CTxOut utxo;
328
0
    assert(psbt.inputs.size() >= input_index);
329
0
    const PSBTInput& input = psbt.inputs[input_index];
330
331
0
    if (input.non_witness_utxo) {
332
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
333
0
        COutPoint prevout = psbt.tx->vin[input_index].prevout;
334
0
        if (prevout.n >= input.non_witness_utxo->vout.size()) {
335
0
            return false;
336
0
        }
337
0
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
338
0
            return false;
339
0
        }
340
0
        utxo = input.non_witness_utxo->vout[prevout.n];
341
0
    } else if (!input.witness_utxo.IsNull()) {
342
0
        utxo = input.witness_utxo;
343
0
    } else {
344
0
        return false;
345
0
    }
346
347
0
    if (txdata) {
348
0
        return VerifyScript(input.final_script_sig, utxo.scriptPubKey, &input.final_script_witness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker{&(*psbt.tx), input_index, utxo.nValue, *txdata, MissingDataBehavior::FAIL});
349
0
    } else {
350
0
        return VerifyScript(input.final_script_sig, utxo.scriptPubKey, &input.final_script_witness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker{&(*psbt.tx), input_index, utxo.nValue, MissingDataBehavior::FAIL});
351
0
    }
352
0
}
353
354
0
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt) {
355
0
    size_t count = 0;
356
0
    for (const auto& input : psbt.inputs) {
357
0
        if (!PSBTInputSigned(input)) {
358
0
            count++;
359
0
        }
360
0
    }
361
362
0
    return count;
363
0
}
364
365
void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index)
366
0
{
367
0
    CMutableTransaction& tx = *Assert(psbt.tx);
Line
Count
Source
113
0
#define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val)
368
0
    const CTxOut& out = tx.vout.at(index);
369
0
    PSBTOutput& psbt_out = psbt.outputs.at(index);
370
371
    // Fill a SignatureData with output info
372
0
    SignatureData sigdata;
373
0
    psbt_out.FillSignatureData(sigdata);
374
375
    // Construct a would-be spend of this output, to update sigdata with.
376
    // Note that ProduceSignature is used to fill in metadata (not actual signatures),
377
    // so provider does not need to provide any private keys (it can be a HidingSigningProvider).
378
0
    MutableTransactionSignatureCreator creator(tx, /*input_idx=*/0, out.nValue, SIGHASH_ALL);
379
0
    ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
380
381
    // Put redeem_script, witness_script, key paths, into PSBTOutput.
382
0
    psbt_out.FromSignatureData(sigdata);
383
0
}
384
385
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt)
386
0
{
387
0
    const CMutableTransaction& tx = *psbt.tx;
388
0
    bool have_all_spent_outputs = true;
389
0
    std::vector<CTxOut> utxos(tx.vin.size());
390
0
    for (size_t idx = 0; idx < tx.vin.size(); ++idx) {
391
0
        if (!psbt.GetInputUTXO(utxos[idx], idx)) have_all_spent_outputs = false;
392
0
    }
393
0
    PrecomputedTransactionData txdata;
394
0
    if (have_all_spent_outputs) {
395
0
        txdata.Init(tx, std::move(utxos), true);
396
0
    } else {
397
0
        txdata.Init(tx, {}, true);
398
0
    }
399
0
    return txdata;
400
0
}
401
402
PSBTError SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, std::optional<int> sighash,  SignatureData* out_sigdata, bool finalize)
403
0
{
404
0
    PSBTInput& input = psbt.inputs.at(index);
405
0
    const CMutableTransaction& tx = *psbt.tx;
406
407
0
    if (PSBTInputSignedAndVerified(psbt, index, txdata)) {
408
0
        return PSBTError::OK;
409
0
    }
410
411
    // Fill SignatureData with input info
412
0
    SignatureData sigdata;
413
0
    input.FillSignatureData(sigdata);
414
415
    // Get UTXO
416
0
    bool require_witness_sig = false;
417
0
    CTxOut utxo;
418
419
0
    if (input.non_witness_utxo) {
420
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
421
0
        COutPoint prevout = tx.vin[index].prevout;
422
0
        if (prevout.n >= input.non_witness_utxo->vout.size()) {
423
0
            return PSBTError::MISSING_INPUTS;
424
0
        }
425
0
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
426
0
            return PSBTError::MISSING_INPUTS;
427
0
        }
428
0
        utxo = input.non_witness_utxo->vout[prevout.n];
429
0
    } else if (!input.witness_utxo.IsNull()) {
430
0
        utxo = input.witness_utxo;
431
        // When we're taking our information from a witness UTXO, we can't verify it is actually data from
432
        // the output being spent. This is safe in case a witness signature is produced (which includes this
433
        // information directly in the hash), but not for non-witness signatures. Remember that we require
434
        // a witness signature in this situation.
435
0
        require_witness_sig = true;
436
0
    } else {
437
0
        return PSBTError::MISSING_INPUTS;
438
0
    }
439
440
    // Get the sighash type
441
    // If both the field and the parameter are provided, they must match
442
    // If only the parameter is provided, use it and add it to the PSBT if it is other than SIGHASH_DEFAULT
443
    // for all input types, and not SIGHASH_ALL for non-taproot input types.
444
    // If neither are provided, use SIGHASH_DEFAULT if it is taproot, and SIGHASH_ALL for everything else.
445
0
    if (!sighash) sighash = utxo.scriptPubKey.IsPayToTaproot() ? SIGHASH_DEFAULT : SIGHASH_ALL;
446
0
    Assert(sighash.has_value());
Line
Count
Source
113
0
#define Assert(val) inline_assertion_check<true>(val, std::source_location::current(), #val)
447
    // For user safety, the desired sighash must be provided if the PSBT wants something other than the default set in the previous line.
448
0
    if (input.sighash_type && input.sighash_type != sighash) {
449
0
        return PSBTError::SIGHASH_MISMATCH;
450
0
    }
451
    // Set the PSBT sighash field when sighash is not DEFAULT or ALL
452
    // DEFAULT is allowed for non-taproot inputs since DEFAULT may be passed for them (e.g. the psbt being signed also has taproot inputs)
453
    // Note that signing already aliases DEFAULT to ALL for non-taproot inputs.
454
0
    if (utxo.scriptPubKey.IsPayToTaproot() ? sighash != SIGHASH_DEFAULT :
455
0
                                            (sighash != SIGHASH_DEFAULT && sighash != SIGHASH_ALL)) {
456
0
        input.sighash_type = sighash;
457
0
    }
458
459
    // Check all existing signatures use the sighash type
460
0
    if (sighash == SIGHASH_DEFAULT) {
461
0
        if (!input.m_tap_key_sig.empty() && input.m_tap_key_sig.size() != 64) {
462
0
            return PSBTError::SIGHASH_MISMATCH;
463
0
        }
464
0
        for (const auto& [_, sig] : input.m_tap_script_sigs) {
465
0
            if (sig.size() != 64) return PSBTError::SIGHASH_MISMATCH;
466
0
        }
467
0
    } else {
468
0
        if (!input.m_tap_key_sig.empty() && (input.m_tap_key_sig.size() != 65 || input.m_tap_key_sig.back() != *sighash)) {
469
0
            return PSBTError::SIGHASH_MISMATCH;
470
0
        }
471
0
        for (const auto& [_, sig] : input.m_tap_script_sigs) {
472
0
            if (sig.size() != 65 || sig.back() != *sighash) return PSBTError::SIGHASH_MISMATCH;
473
0
        }
474
0
        for (const auto& [_, sig] : input.partial_sigs) {
475
0
            if (sig.second.back() != *sighash) return PSBTError::SIGHASH_MISMATCH;
476
0
        }
477
0
    }
478
479
0
    sigdata.witness = false;
480
0
    bool sig_complete;
481
0
    if (txdata == nullptr) {
482
0
        sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
483
0
    } else {
484
0
        MutableTransactionSignatureCreator creator(tx, index, utxo.nValue, txdata, *sighash);
485
0
        sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
486
0
    }
487
    // Verify that a witness signature was produced in case one was required.
488
0
    if (require_witness_sig && !sigdata.witness) return PSBTError::INCOMPLETE;
489
490
    // If we are not finalizing, set sigdata.complete to false to not set the scriptWitness
491
0
    if (!finalize && sigdata.complete) sigdata.complete = false;
492
493
0
    input.FromSignatureData(sigdata);
494
495
    // If we have a witness signature, put a witness UTXO.
496
0
    if (sigdata.witness) {
497
0
        input.witness_utxo = utxo;
498
        // We can remove the non_witness_utxo if and only if there are no non-segwit or segwit v0
499
        // inputs in this transaction. Since this requires inspecting the entire transaction, this
500
        // is something for the caller to deal with (i.e. FillPSBT).
501
0
    }
502
503
    // Fill in the missing info
504
0
    if (out_sigdata) {
505
0
        out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
506
0
        out_sigdata->missing_sigs = sigdata.missing_sigs;
507
0
        out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
508
0
        out_sigdata->missing_witness_script = sigdata.missing_witness_script;
509
0
    }
510
511
0
    return sig_complete ? PSBTError::OK : PSBTError::INCOMPLETE;
512
0
}
513
514
void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx)
515
0
{
516
    // Figure out if any non_witness_utxos should be dropped
517
0
    std::vector<unsigned int> to_drop;
518
0
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
519
0
        const auto& input = psbtx.inputs.at(i);
520
0
        int wit_ver;
521
0
        std::vector<unsigned char> wit_prog;
522
0
        if (input.witness_utxo.IsNull() || !input.witness_utxo.scriptPubKey.IsWitnessProgram(wit_ver, wit_prog)) {
523
            // There's a non-segwit input, so we cannot drop any non_witness_utxos
524
0
            to_drop.clear();
525
0
            break;
526
0
        }
527
0
        if (wit_ver == 0) {
528
            // Segwit v0, so we cannot drop any non_witness_utxos
529
0
            to_drop.clear();
530
0
            break;
531
0
        }
532
        // non_witness_utxos cannot be dropped if the sighash type includes SIGHASH_ANYONECANPAY
533
        // Since callers should have called SignPSBTInput which updates the sighash type in the PSBT, we only
534
        // need to look at that field. If it is not present, then we can assume SIGHASH_DEFAULT or SIGHASH_ALL.
535
0
        if (input.sighash_type != std::nullopt && (*input.sighash_type & 0x80) == SIGHASH_ANYONECANPAY) {
536
0
            to_drop.clear();
537
0
            break;
538
0
        }
539
540
0
        if (input.non_witness_utxo) {
541
0
            to_drop.push_back(i);
542
0
        }
543
0
    }
544
545
    // Drop the non_witness_utxos that we can drop
546
0
    for (unsigned int i : to_drop) {
547
0
        psbtx.inputs.at(i).non_witness_utxo = nullptr;
548
0
    }
549
0
}
550
551
bool FinalizePSBT(PartiallySignedTransaction& psbtx)
552
0
{
553
    // Finalize input signatures -- in case we have partial signatures that add up to a complete
554
    //   signature, but have not combined them yet (e.g. because the combiner that created this
555
    //   PartiallySignedTransaction did not understand them), this will combine them into a final
556
    //   script.
557
0
    bool complete = true;
558
0
    const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
559
0
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
560
0
        PSBTInput& input = psbtx.inputs.at(i);
561
0
        complete &= (SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, input.sighash_type, nullptr, true) == PSBTError::OK);
562
0
    }
563
564
0
    return complete;
565
0
}
566
567
bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result)
568
0
{
569
    // It's not safe to extract a PSBT that isn't finalized, and there's no easy way to check
570
    //   whether a PSBT is finalized without finalizing it, so we just do this.
571
0
    if (!FinalizePSBT(psbtx)) {
572
0
        return false;
573
0
    }
574
575
0
    result = *psbtx.tx;
576
0
    for (unsigned int i = 0; i < result.vin.size(); ++i) {
577
0
        result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
578
0
        result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
579
0
    }
580
0
    return true;
581
0
}
582
583
bool CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs)
584
0
{
585
0
    out = psbtxs[0]; // Copy the first one
586
587
    // Merge
588
0
    for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
589
0
        if (!out.Merge(*it)) {
590
0
            return false;
591
0
        }
592
0
    }
593
0
    return true;
594
0
}
595
596
0
std::string PSBTRoleName(PSBTRole role) {
597
0
    switch (role) {
598
0
    case PSBTRole::CREATOR: return "creator";
599
0
    case PSBTRole::UPDATER: return "updater";
600
0
    case PSBTRole::SIGNER: return "signer";
601
0
    case PSBTRole::FINALIZER: return "finalizer";
602
0
    case PSBTRole::EXTRACTOR: return "extractor";
603
        // no default case, so the compiler can warn about missing cases
604
0
    }
605
0
    assert(false);
606
0
}
607
608
bool DecodeBase64PSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
609
0
{
610
0
    auto tx_data = DecodeBase64(base64_tx);
611
0
    if (!tx_data) {
612
0
        error = "invalid base64";
613
0
        return false;
614
0
    }
615
0
    return DecodeRawPSBT(psbt, MakeByteSpan(*tx_data), error);
616
0
}
617
618
bool DecodeRawPSBT(PartiallySignedTransaction& psbt, std::span<const std::byte> tx_data, std::string& error)
619
0
{
620
0
    DataStream ss_data{tx_data};
621
0
    try {
622
0
        ss_data >> psbt;
623
0
        if (!ss_data.empty()) {
624
0
            error = "extra data after PSBT";
625
0
            return false;
626
0
        }
627
0
    } catch (const std::exception& e) {
628
0
        error = e.what();
629
0
        return false;
630
0
    }
631
0
    return true;
632
0
}
633
634
uint32_t PartiallySignedTransaction::GetVersion() const
635
0
{
636
0
    if (m_version != std::nullopt) {
637
0
        return *m_version;
638
0
    }
639
0
    return 0;
640
0
}