Coverage Report

Created: 2026-04-29 19:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/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
412
PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx) : tx(tx)
17
412
{
18
412
    inputs.resize(tx.vin.size());
19
412
    outputs.resize(tx.vout.size());
20
412
}
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
97
{
29
    // Prohibited to merge two PSBTs over different transactions
30
97
    if (tx->GetHash() != psbt.tx->GetHash()) {
31
1
        return false;
32
1
    }
33
34
194
    for (unsigned int i = 0; i < inputs.size(); ++i) {
35
98
        inputs[i].Merge(psbt.inputs[i]);
36
98
    }
37
284
    for (unsigned int i = 0; i < outputs.size(); ++i) {
38
188
        outputs[i].Merge(psbt.outputs[i]);
39
188
    }
40
96
    for (auto& xpub_pair : psbt.m_xpubs) {
41
0
        if (!m_xpubs.contains(xpub_pair.first)) {
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
96
    unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
48
49
96
    return true;
50
97
}
51
52
bool PartiallySignedTransaction::AddInput(const CTxIn& txin, PSBTInput& psbtin)
53
18
{
54
18
    if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) {
55
1
        return false;
56
1
    }
57
17
    tx->vin.push_back(txin);
58
17
    psbtin.partial_sigs.clear();
59
17
    psbtin.final_script_sig.clear();
60
17
    psbtin.final_script_witness.SetNull();
61
17
    inputs.push_back(psbtin);
62
17
    return true;
63
18
}
64
65
bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput& psbtout)
66
9
{
67
9
    tx->vout.push_back(txout);
68
9
    outputs.push_back(psbtout);
69
9
    return true;
70
9
}
71
72
bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const
73
5.50k
{
74
5.50k
    const PSBTInput& input = inputs[input_index];
75
5.50k
    uint32_t prevout_index = tx->vin[input_index].prevout.n;
76
5.50k
    if (input.non_witness_utxo) {
77
4.82k
        if (prevout_index >= input.non_witness_utxo->vout.size()) {
78
1
            return false;
79
1
        }
80
4.82k
        if (input.non_witness_utxo->GetHash() != tx->vin[input_index].prevout.hash) {
81
0
            return false;
82
0
        }
83
4.82k
        utxo = input.non_witness_utxo->vout[prevout_index];
84
4.82k
    } else if (!input.witness_utxo.IsNull()) {
85
635
        utxo = input.witness_utxo;
86
635
    } else {
87
38
        return false;
88
38
    }
89
5.46k
    return true;
90
5.50k
}
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
23.5k
{
99
23.5k
    if (!final_script_sig.empty()) {
100
0
        sigdata.scriptSig = final_script_sig;
101
0
        sigdata.complete = true;
102
0
    }
103
23.5k
    if (!final_script_witness.IsNull()) {
104
0
        sigdata.scriptWitness = final_script_witness;
105
0
        sigdata.complete = true;
106
0
    }
107
23.5k
    if (sigdata.complete) {
108
0
        return;
109
0
    }
110
111
23.5k
    sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
112
23.5k
    if (!redeem_script.empty()) {
113
4.36k
        sigdata.redeem_script = redeem_script;
114
4.36k
    }
115
23.5k
    if (!witness_script.empty()) {
116
299
        sigdata.witness_script = witness_script;
117
299
    }
118
23.5k
    for (const auto& key_pair : hd_keypaths) {
119
14.1k
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
120
14.1k
    }
121
23.5k
    if (!m_tap_key_sig.empty()) {
122
206
        sigdata.taproot_key_path_sig = m_tap_key_sig;
123
206
    }
124
23.5k
    for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
125
539
        sigdata.taproot_script_sigs.emplace(pubkey_leaf, sig);
126
539
    }
127
23.5k
    if (!m_tap_internal_key.IsNull()) {
128
2.39k
        sigdata.tr_spenddata.internal_key = m_tap_internal_key;
129
2.39k
    }
130
23.5k
    if (!m_tap_merkle_root.IsNull()) {
131
1.84k
        sigdata.tr_spenddata.merkle_root = m_tap_merkle_root;
132
1.84k
    }
133
23.5k
    for (const auto& [leaf_script, control_block] : m_tap_scripts) {
134
2.81k
        sigdata.tr_spenddata.scripts.emplace(leaf_script, control_block);
135
2.81k
    }
136
23.5k
    for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
137
10.9k
        sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
138
10.9k
        sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
139
10.9k
    }
140
23.5k
    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
23.5k
    for (const auto& [hash, preimage] : sha256_preimages) {
144
12
        sigdata.sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
145
12
    }
146
23.5k
    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
23.5k
    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
23.5k
    sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
153
23.5k
    for (const auto& [agg_key_lh, pubnonces] : m_musig2_pubnonces) {
154
1.83k
        sigdata.musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
155
1.83k
    }
156
23.5k
    for (const auto& [agg_key_lh, psigs] : m_musig2_partial_sigs) {
157
394
        sigdata.musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
158
394
    }
159
23.5k
}
160
161
void PSBTInput::FromSignatureData(const SignatureData& sigdata)
162
23.4k
{
163
23.4k
    if (sigdata.complete) {
164
1.68k
        partial_sigs.clear();
165
1.68k
        hd_keypaths.clear();
166
1.68k
        redeem_script.clear();
167
1.68k
        witness_script.clear();
168
169
1.68k
        if (!sigdata.scriptSig.empty()) {
170
748
            final_script_sig = sigdata.scriptSig;
171
748
        }
172
1.68k
        if (!sigdata.scriptWitness.IsNull()) {
173
1.44k
            final_script_witness = sigdata.scriptWitness;
174
1.44k
        }
175
1.68k
        return;
176
1.68k
    }
177
178
21.8k
    partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
179
21.8k
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
180
541
        redeem_script = sigdata.redeem_script;
181
541
    }
182
21.8k
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
183
32
        witness_script = sigdata.witness_script;
184
32
    }
185
21.8k
    for (const auto& entry : sigdata.misc_pubkeys) {
186
14.2k
        hd_keypaths.emplace(entry.second);
187
14.2k
    }
188
21.8k
    if (!sigdata.taproot_key_path_sig.empty()) {
189
231
        m_tap_key_sig = sigdata.taproot_key_path_sig;
190
231
    }
191
21.8k
    for (const auto& [pubkey_leaf, sig] : sigdata.taproot_script_sigs) {
192
602
        m_tap_script_sigs.emplace(pubkey_leaf, sig);
193
602
    }
194
21.8k
    if (!sigdata.tr_spenddata.internal_key.IsNull()) {
195
2.31k
        m_tap_internal_key = sigdata.tr_spenddata.internal_key;
196
2.31k
    }
197
21.8k
    if (!sigdata.tr_spenddata.merkle_root.IsNull()) {
198
1.77k
        m_tap_merkle_root = sigdata.tr_spenddata.merkle_root;
199
1.77k
    }
200
21.8k
    for (const auto& [leaf_script, control_block] : sigdata.tr_spenddata.scripts) {
201
2.70k
        m_tap_scripts.emplace(leaf_script, control_block);
202
2.70k
    }
203
21.8k
    for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
204
10.7k
        m_tap_bip32_paths.emplace(pubkey, leaf_origin);
205
10.7k
    }
206
21.8k
    m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
207
21.8k
    for (const auto& [agg_key_lh, pubnonces] : sigdata.musig2_pubnonces) {
208
1.89k
        m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
209
1.89k
    }
210
21.8k
    for (const auto& [agg_key_lh, psigs] : sigdata.musig2_partial_sigs) {
211
415
        m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
212
415
    }
213
21.8k
}
214
215
void PSBTInput::Merge(const PSBTInput& input)
216
98
{
217
98
    if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
218
98
    if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
219
1
        witness_utxo = input.witness_utxo;
220
1
    }
221
222
98
    partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
223
98
    ripemd160_preimages.insert(input.ripemd160_preimages.begin(), input.ripemd160_preimages.end());
224
98
    sha256_preimages.insert(input.sha256_preimages.begin(), input.sha256_preimages.end());
225
98
    hash160_preimages.insert(input.hash160_preimages.begin(), input.hash160_preimages.end());
226
98
    hash256_preimages.insert(input.hash256_preimages.begin(), input.hash256_preimages.end());
227
98
    hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
228
98
    unknown.insert(input.unknown.begin(), input.unknown.end());
229
98
    m_tap_script_sigs.insert(input.m_tap_script_sigs.begin(), input.m_tap_script_sigs.end());
230
98
    m_tap_scripts.insert(input.m_tap_scripts.begin(), input.m_tap_scripts.end());
231
98
    m_tap_bip32_paths.insert(input.m_tap_bip32_paths.begin(), input.m_tap_bip32_paths.end());
232
233
98
    if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
234
98
    if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
235
98
    if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
236
98
    if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
237
98
    if (m_tap_key_sig.empty() && !input.m_tap_key_sig.empty()) m_tap_key_sig = input.m_tap_key_sig;
238
98
    if (m_tap_internal_key.IsNull() && !input.m_tap_internal_key.IsNull()) m_tap_internal_key = input.m_tap_internal_key;
239
98
    if (m_tap_merkle_root.IsNull() && !input.m_tap_merkle_root.IsNull()) m_tap_merkle_root = input.m_tap_merkle_root;
240
98
    m_musig2_participants.insert(input.m_musig2_participants.begin(), input.m_musig2_participants.end());
241
111
    for (const auto& [agg_key_lh, pubnonces] : input.m_musig2_pubnonces) {
242
111
        m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
243
111
    }
244
98
    for (const auto& [agg_key_lh, psigs] : input.m_musig2_partial_sigs) {
245
49
        m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
246
49
    }
247
98
}
248
249
void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
250
950
{
251
950
    if (!redeem_script.empty()) {
252
5
        sigdata.redeem_script = redeem_script;
253
5
    }
254
950
    if (!witness_script.empty()) {
255
8
        sigdata.witness_script = witness_script;
256
8
    }
257
950
    for (const auto& key_pair : hd_keypaths) {
258
293
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
259
293
    }
260
950
    if (!m_tap_tree.empty() && m_tap_internal_key.IsFullyValid()) {
261
123
        TaprootBuilder builder;
262
297
        for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
263
297
            builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
264
297
        }
265
123
        assert(builder.IsComplete());
266
123
        builder.Finalize(m_tap_internal_key);
267
123
        TaprootSpendData spenddata = builder.GetSpendData();
268
269
123
        sigdata.tr_spenddata.internal_key = m_tap_internal_key;
270
123
        sigdata.tr_spenddata.Merge(spenddata);
271
123
    }
272
950
    for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
273
545
        sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
274
545
        sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
275
545
    }
276
950
    sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
277
950
}
278
279
void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
280
950
{
281
950
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
282
21
        redeem_script = sigdata.redeem_script;
283
21
    }
284
950
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
285
10
        witness_script = sigdata.witness_script;
286
10
    }
287
950
    for (const auto& entry : sigdata.misc_pubkeys) {
288
696
        hd_keypaths.emplace(entry.second);
289
696
    }
290
950
    if (!sigdata.tr_spenddata.internal_key.IsNull()) {
291
240
        m_tap_internal_key = sigdata.tr_spenddata.internal_key;
292
240
    }
293
950
    if (sigdata.tr_builder.has_value() && sigdata.tr_builder->HasScripts()) {
294
186
        m_tap_tree = sigdata.tr_builder->GetTreeTuples();
295
186
    }
296
950
    for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
297
820
        m_tap_bip32_paths.emplace(pubkey, leaf_origin);
298
820
    }
299
950
    m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
300
950
}
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
188
{
309
188
    hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
310
188
    unknown.insert(output.unknown.begin(), output.unknown.end());
311
188
    m_tap_bip32_paths.insert(output.m_tap_bip32_paths.begin(), output.m_tap_bip32_paths.end());
312
313
188
    if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
314
188
    if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
315
188
    if (m_tap_internal_key.IsNull() && !output.m_tap_internal_key.IsNull()) m_tap_internal_key = output.m_tap_internal_key;
316
188
    if (m_tap_tree.empty() && !output.m_tap_tree.empty()) m_tap_tree = output.m_tap_tree;
317
188
    m_musig2_participants.insert(output.m_musig2_participants.begin(), output.m_musig2_participants.end());
318
188
}
319
320
bool PSBTInputSigned(const PSBTInput& input)
321
57.3k
{
322
57.3k
    return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
323
57.3k
}
324
325
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
326
28.6k
{
327
28.6k
    CTxOut utxo;
328
28.6k
    assert(input_index < psbt.inputs.size());
329
28.6k
    const PSBTInput& input = psbt.inputs[input_index];
330
331
28.6k
    if (input.non_witness_utxo) {
332
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
333
26.7k
        COutPoint prevout = psbt.tx->vin[input_index].prevout;
334
26.7k
        if (prevout.n >= input.non_witness_utxo->vout.size()) {
335
0
            return false;
336
0
        }
337
26.7k
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
338
0
            return false;
339
0
        }
340
26.7k
        utxo = input.non_witness_utxo->vout[prevout.n];
341
26.7k
    } else if (!input.witness_utxo.IsNull()) {
342
1.86k
        utxo = input.witness_utxo;
343
1.86k
    } else {
344
38
        return false;
345
38
    }
346
347
28.6k
    if (txdata) {
348
28.6k
        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
28.6k
    } else {
350
3
        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
3
    }
352
28.6k
}
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
950
{
367
950
    CMutableTransaction& tx = *Assert(psbt.tx);
368
950
    const CTxOut& out = tx.vout.at(index);
369
950
    PSBTOutput& psbt_out = psbt.outputs.at(index);
370
371
    // Fill a SignatureData with output info
372
950
    SignatureData sigdata;
373
950
    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
950
    MutableTransactionSignatureCreator creator(tx, /*input_idx=*/0, out.nValue, {.sighash_type = SIGHASH_ALL});
379
950
    ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
380
381
    // Put redeem_script, witness_script, key paths, into PSBTOutput.
382
950
    psbt_out.FromSignatureData(sigdata);
383
950
}
384
385
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt)
386
1.68k
{
387
1.68k
    const CMutableTransaction& tx = *psbt.tx;
388
1.68k
    bool have_all_spent_outputs = true;
389
1.68k
    std::vector<CTxOut> utxos(tx.vin.size());
390
7.17k
    for (size_t idx = 0; idx < tx.vin.size(); ++idx) {
391
5.48k
        if (!psbt.GetInputUTXO(utxos[idx], idx)) have_all_spent_outputs = false;
392
5.48k
    }
393
1.68k
    PrecomputedTransactionData txdata;
394
1.68k
    if (have_all_spent_outputs) {
395
1.65k
        txdata.Init(tx, std::move(utxos), true);
396
1.65k
    } else {
397
32
        txdata.Init(tx, {}, true);
398
32
    }
399
1.68k
    return txdata;
400
1.68k
}
401
402
PSBTError SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options,  SignatureData* out_sigdata)
403
24.9k
{
404
24.9k
    PSBTInput& input = psbt.inputs.at(index);
405
24.9k
    const CMutableTransaction& tx = *psbt.tx;
406
407
24.9k
    if (PSBTInputSignedAndVerified(psbt, index, txdata)) {
408
1.41k
        return PSBTError::OK;
409
1.41k
    }
410
411
    // Fill SignatureData with input info
412
23.5k
    SignatureData sigdata;
413
23.5k
    input.FillSignatureData(sigdata);
414
415
    // Get UTXO
416
23.5k
    bool require_witness_sig = false;
417
23.5k
    CTxOut utxo;
418
419
23.5k
    if (input.non_witness_utxo) {
420
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
421
22.4k
        COutPoint prevout = tx.vin[index].prevout;
422
22.4k
        if (prevout.n >= input.non_witness_utxo->vout.size()) {
423
0
            return PSBTError::MISSING_INPUTS;
424
0
        }
425
22.4k
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
426
0
            return PSBTError::MISSING_INPUTS;
427
0
        }
428
22.4k
        utxo = input.non_witness_utxo->vout[prevout.n];
429
22.4k
    } else if (!input.witness_utxo.IsNull()) {
430
1.09k
        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
1.09k
        require_witness_sig = true;
436
1.09k
    } else {
437
10
        return PSBTError::MISSING_INPUTS;
438
10
    }
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
23.5k
    int sighash{options.sighash_type.value_or(utxo.scriptPubKey.IsPayToTaproot() ? SIGHASH_DEFAULT : SIGHASH_ALL)};
446
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
23.5k
    if (input.sighash_type && input.sighash_type != sighash) {
449
14
        return PSBTError::SIGHASH_MISMATCH;
450
14
    }
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
23.5k
    if (utxo.scriptPubKey.IsPayToTaproot() ? sighash != SIGHASH_DEFAULT :
455
23.5k
                                            (sighash != SIGHASH_DEFAULT && sighash != SIGHASH_ALL)) {
456
94
        input.sighash_type = sighash;
457
94
    }
458
459
    // Check all existing signatures use the sighash type
460
23.5k
    if (sighash == SIGHASH_DEFAULT) {
461
3.26k
        if (!input.m_tap_key_sig.empty() && input.m_tap_key_sig.size() != 64) {
462
0
            return PSBTError::SIGHASH_MISMATCH;
463
0
        }
464
3.26k
        for (const auto& [_, sig] : input.m_tap_script_sigs) {
465
539
            if (sig.size() != 64) return PSBTError::SIGHASH_MISMATCH;
466
539
        }
467
20.2k
    } else {
468
20.2k
        if (!input.m_tap_key_sig.empty() && (input.m_tap_key_sig.size() != 65 || input.m_tap_key_sig.back() != sighash)) {
469
2
            return PSBTError::SIGHASH_MISMATCH;
470
2
        }
471
20.2k
        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
20.2k
        for (const auto& [_, sig] : input.partial_sigs) {
475
398
            if (sig.second.back() != sighash) return PSBTError::SIGHASH_MISMATCH;
476
398
        }
477
20.2k
    }
478
479
23.5k
    sigdata.witness = false;
480
23.5k
    bool sig_complete;
481
23.5k
    if (txdata == nullptr) {
482
1
        sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
483
23.5k
    } else {
484
23.5k
        MutableTransactionSignatureCreator creator(tx, index, utxo.nValue, txdata, {.sighash_type = sighash});
485
23.5k
        sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
486
23.5k
    }
487
    // Verify that a witness signature was produced in case one was required.
488
23.5k
    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
23.4k
    if (!options.finalize && sigdata.complete) sigdata.complete = false;
492
493
23.4k
    input.FromSignatureData(sigdata);
494
495
    // If we have a witness signature, put a witness UTXO.
496
23.4k
    if (sigdata.witness) {
497
19.0k
        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
19.0k
    }
502
503
    // Fill in the missing info
504
23.4k
    if (out_sigdata) {
505
3
        out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
506
3
        out_sigdata->missing_sigs = sigdata.missing_sigs;
507
3
        out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
508
3
        out_sigdata->missing_witness_script = sigdata.missing_witness_script;
509
3
    }
510
511
23.4k
    return sig_complete ? PSBTError::OK : PSBTError::INCOMPLETE;
512
23.5k
}
513
514
void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx)
515
1.14k
{
516
    // Figure out if any non_witness_utxos should be dropped
517
1.14k
    std::vector<unsigned int> to_drop;
518
1.84k
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
519
1.34k
        const auto& input = psbtx.inputs.at(i);
520
1.34k
        int wit_ver;
521
1.34k
        std::vector<unsigned char> wit_prog;
522
1.34k
        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
192
            to_drop.clear();
525
192
            break;
526
192
        }
527
1.15k
        if (wit_ver == 0) {
528
            // Segwit v0, so we cannot drop any non_witness_utxos
529
452
            to_drop.clear();
530
452
            break;
531
452
        }
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
705
        if (input.sighash_type != std::nullopt && (*input.sighash_type & 0x80) == SIGHASH_ANYONECANPAY) {
536
6
            to_drop.clear();
537
6
            break;
538
6
        }
539
540
699
        if (input.non_witness_utxo) {
541
426
            to_drop.push_back(i);
542
426
        }
543
699
    }
544
545
    // Drop the non_witness_utxos that we can drop
546
1.14k
    for (unsigned int i : to_drop) {
547
426
        psbtx.inputs.at(i).non_witness_utxo = nullptr;
548
426
    }
549
1.14k
}
550
551
bool FinalizePSBT(PartiallySignedTransaction& psbtx)
552
516
{
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
516
    bool complete = true;
558
516
    const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
559
2.29k
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
560
1.77k
        PSBTInput& input = psbtx.inputs.at(i);
561
1.77k
        complete &= (SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, {.sighash_type = input.sighash_type, .finalize = true}, /*out_sigdata=*/nullptr) == PSBTError::OK);
562
1.77k
    }
563
564
516
    return complete;
565
516
}
566
567
bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result)
568
513
{
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
513
    if (!FinalizePSBT(psbtx)) {
572
35
        return false;
573
35
    }
574
575
478
    result = *psbtx.tx;
576
2.16k
    for (unsigned int i = 0; i < result.vin.size(); ++i) {
577
1.69k
        result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
578
1.69k
        result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
579
1.69k
    }
580
478
    return true;
581
513
}
582
583
bool CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs)
584
52
{
585
52
    out = psbtxs[0]; // Copy the first one
586
587
    // Merge
588
148
    for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
589
97
        if (!out.Merge(*it)) {
590
1
            return false;
591
1
        }
592
97
    }
593
51
    return true;
594
52
}
595
596
14
std::string PSBTRoleName(PSBTRole role) {
597
14
    switch (role) {
598
3
    case PSBTRole::CREATOR: return "creator";
599
5
    case PSBTRole::UPDATER: return "updater";
600
2
    case PSBTRole::SIGNER: return "signer";
601
2
    case PSBTRole::FINALIZER: return "finalizer";
602
2
    case PSBTRole::EXTRACTOR: return "extractor";
603
14
    } // no default case, so the compiler can warn about missing cases
604
14
    assert(false);
605
0
}
606
607
bool DecodeBase64PSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
608
1.32k
{
609
1.32k
    auto tx_data = DecodeBase64(base64_tx);
610
1.32k
    if (!tx_data) {
611
3
        error = "invalid base64";
612
3
        return false;
613
3
    }
614
1.32k
    return DecodeRawPSBT(psbt, MakeByteSpan(*tx_data), error);
615
1.32k
}
616
617
bool DecodeRawPSBT(PartiallySignedTransaction& psbt, std::span<const std::byte> tx_data, std::string& error)
618
1.32k
{
619
1.32k
    SpanReader ss_data{tx_data};
620
1.32k
    try {
621
1.32k
        ss_data >> psbt;
622
1.32k
        if (!ss_data.empty()) {
623
0
            error = "extra data after PSBT";
624
0
            return false;
625
0
        }
626
1.32k
    } catch (const std::exception& e) {
627
63
        error = e.what();
628
63
        return false;
629
63
    }
630
1.26k
    return true;
631
1.32k
}
632
633
uint32_t PartiallySignedTransaction::GetVersion() const
634
1.22k
{
635
1.22k
    if (m_version != std::nullopt) {
636
1
        return *m_version;
637
1
    }
638
1.22k
    return 0;
639
1.22k
}