Coverage Report

Created: 2025-09-08 17:07

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