Coverage Report

Created: 2026-04-20 22: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
6.22k
PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx) : tx(tx)
17
6.22k
{
18
6.22k
    inputs.resize(tx.vin.size());
19
6.22k
    outputs.resize(tx.vout.size());
20
6.22k
}
21
22
bool PartiallySignedTransaction::IsNull() const
23
5.22k
{
24
5.22k
    return !tx && inputs.empty() && outputs.empty() && unknown.empty();
25
5.22k
}
26
27
bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt)
28
17.7k
{
29
    // Prohibited to merge two PSBTs over different transactions
30
17.7k
    if (tx->GetHash() != psbt.tx->GetHash()) {
31
526
        return false;
32
526
    }
33
34
52.7k
    for (unsigned int i = 0; i < inputs.size(); ++i) {
35
35.5k
        inputs[i].Merge(psbt.inputs[i]);
36
35.5k
    }
37
64.4k
    for (unsigned int i = 0; i < outputs.size(); ++i) {
38
47.2k
        outputs[i].Merge(psbt.outputs[i]);
39
47.2k
    }
40
17.1k
    for (auto& xpub_pair : psbt.m_xpubs) {
41
5.22k
        if (!m_xpubs.contains(xpub_pair.first)) {
42
1.16k
            m_xpubs[xpub_pair.first] = xpub_pair.second;
43
4.06k
        } else {
44
4.06k
            m_xpubs[xpub_pair.first].insert(xpub_pair.second.begin(), xpub_pair.second.end());
45
4.06k
        }
46
5.22k
    }
47
17.1k
    unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
48
49
17.1k
    return true;
50
17.7k
}
51
52
bool PartiallySignedTransaction::AddInput(const CTxIn& txin, PSBTInput& psbtin)
53
14.8k
{
54
14.8k
    if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) {
55
11.3k
        return false;
56
11.3k
    }
57
3.46k
    tx->vin.push_back(txin);
58
3.46k
    psbtin.partial_sigs.clear();
59
3.46k
    psbtin.final_script_sig.clear();
60
3.46k
    psbtin.final_script_witness.SetNull();
61
3.46k
    inputs.push_back(psbtin);
62
3.46k
    return true;
63
14.8k
}
64
65
bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput& psbtout)
66
47.4k
{
67
47.4k
    tx->vout.push_back(txout);
68
47.4k
    outputs.push_back(psbtout);
69
47.4k
    return true;
70
47.4k
}
71
72
bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const
73
70.0k
{
74
70.0k
    const PSBTInput& input = inputs[input_index];
75
70.0k
    uint32_t prevout_index = tx->vin[input_index].prevout.n;
76
70.0k
    if (input.non_witness_utxo) {
77
965
        if (prevout_index >= input.non_witness_utxo->vout.size()) {
78
0
            return false;
79
0
        }
80
965
        if (input.non_witness_utxo->GetHash() != tx->vin[input_index].prevout.hash) {
81
0
            return false;
82
0
        }
83
965
        utxo = input.non_witness_utxo->vout[prevout_index];
84
69.1k
    } else if (!input.witness_utxo.IsNull()) {
85
37.9k
        utxo = input.witness_utxo;
86
37.9k
    } else {
87
31.1k
        return false;
88
31.1k
    }
89
38.9k
    return true;
90
70.0k
}
91
92
bool PSBTInput::IsNull() const
93
11.4k
{
94
11.4k
    return !non_witness_utxo && witness_utxo.IsNull() && partial_sigs.empty() && unknown.empty() && hd_keypaths.empty() && redeem_script.empty() && witness_script.empty();
95
11.4k
}
96
97
void PSBTInput::FillSignatureData(SignatureData& sigdata) const
98
40.1k
{
99
40.1k
    if (!final_script_sig.empty()) {
100
6.42k
        sigdata.scriptSig = final_script_sig;
101
6.42k
        sigdata.complete = true;
102
6.42k
    }
103
40.1k
    if (!final_script_witness.IsNull()) {
104
584
        sigdata.scriptWitness = final_script_witness;
105
584
        sigdata.complete = true;
106
584
    }
107
40.1k
    if (sigdata.complete) {
108
7.01k
        return;
109
7.01k
    }
110
111
33.1k
    sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
112
33.1k
    if (!redeem_script.empty()) {
113
888
        sigdata.redeem_script = redeem_script;
114
888
    }
115
33.1k
    if (!witness_script.empty()) {
116
1.36k
        sigdata.witness_script = witness_script;
117
1.36k
    }
118
33.1k
    for (const auto& key_pair : hd_keypaths) {
119
4.43k
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
120
4.43k
    }
121
33.1k
    if (!m_tap_key_sig.empty()) {
122
1.07k
        sigdata.taproot_key_path_sig = m_tap_key_sig;
123
1.07k
    }
124
33.1k
    for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
125
5.91k
        sigdata.taproot_script_sigs.emplace(pubkey_leaf, sig);
126
5.91k
    }
127
33.1k
    if (!m_tap_internal_key.IsNull()) {
128
373
        sigdata.tr_spenddata.internal_key = m_tap_internal_key;
129
373
    }
130
33.1k
    if (!m_tap_merkle_root.IsNull()) {
131
337
        sigdata.tr_spenddata.merkle_root = m_tap_merkle_root;
132
337
    }
133
33.1k
    for (const auto& [leaf_script, control_block] : m_tap_scripts) {
134
19.6k
        sigdata.tr_spenddata.scripts.emplace(leaf_script, control_block);
135
19.6k
    }
136
33.1k
    for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
137
5.95k
        sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
138
5.95k
        sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
139
5.95k
    }
140
33.1k
    for (const auto& [hash, preimage] : ripemd160_preimages) {
141
1.84k
        sigdata.ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
142
1.84k
    }
143
33.1k
    for (const auto& [hash, preimage] : sha256_preimages) {
144
13.2k
        sigdata.sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
145
13.2k
    }
146
33.1k
    for (const auto& [hash, preimage] : hash160_preimages) {
147
6.64k
        sigdata.hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
148
6.64k
    }
149
33.1k
    for (const auto& [hash, preimage] : hash256_preimages) {
150
4.28k
        sigdata.hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
151
4.28k
    }
152
33.1k
    sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
153
33.1k
    for (const auto& [agg_key_lh, pubnonces] : m_musig2_pubnonces) {
154
590
        sigdata.musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
155
590
    }
156
33.1k
    for (const auto& [agg_key_lh, psigs] : m_musig2_partial_sigs) {
157
342
        sigdata.musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
158
342
    }
159
33.1k
}
160
161
void PSBTInput::FromSignatureData(const SignatureData& sigdata)
162
9.20k
{
163
9.20k
    if (sigdata.complete) {
164
834
        partial_sigs.clear();
165
834
        hd_keypaths.clear();
166
834
        redeem_script.clear();
167
834
        witness_script.clear();
168
169
834
        if (!sigdata.scriptSig.empty()) {
170
370
            final_script_sig = sigdata.scriptSig;
171
370
        }
172
834
        if (!sigdata.scriptWitness.IsNull()) {
173
493
            final_script_witness = sigdata.scriptWitness;
174
493
        }
175
834
        return;
176
834
    }
177
178
8.37k
    partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
179
8.37k
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
180
11
        redeem_script = sigdata.redeem_script;
181
11
    }
182
8.37k
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
183
2
        witness_script = sigdata.witness_script;
184
2
    }
185
8.37k
    for (const auto& entry : sigdata.misc_pubkeys) {
186
3.25k
        hd_keypaths.emplace(entry.second);
187
3.25k
    }
188
8.37k
    if (!sigdata.taproot_key_path_sig.empty()) {
189
558
        m_tap_key_sig = sigdata.taproot_key_path_sig;
190
558
    }
191
8.37k
    for (const auto& [pubkey_leaf, sig] : sigdata.taproot_script_sigs) {
192
322
        m_tap_script_sigs.emplace(pubkey_leaf, sig);
193
322
    }
194
8.37k
    if (!sigdata.tr_spenddata.internal_key.IsNull()) {
195
51
        m_tap_internal_key = sigdata.tr_spenddata.internal_key;
196
51
    }
197
8.37k
    if (!sigdata.tr_spenddata.merkle_root.IsNull()) {
198
113
        m_tap_merkle_root = sigdata.tr_spenddata.merkle_root;
199
113
    }
200
8.37k
    for (const auto& [leaf_script, control_block] : sigdata.tr_spenddata.scripts) {
201
4.25k
        m_tap_scripts.emplace(leaf_script, control_block);
202
4.25k
    }
203
8.37k
    for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
204
1.07k
        m_tap_bip32_paths.emplace(pubkey, leaf_origin);
205
1.07k
    }
206
8.37k
    m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
207
8.37k
    for (const auto& [agg_key_lh, pubnonces] : sigdata.musig2_pubnonces) {
208
493
        m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
209
493
    }
210
8.37k
    for (const auto& [agg_key_lh, psigs] : sigdata.musig2_partial_sigs) {
211
102
        m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
212
102
    }
213
8.37k
}
214
215
void PSBTInput::Merge(const PSBTInput& input)
216
35.5k
{
217
35.5k
    if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
218
35.5k
    if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
219
166
        witness_utxo = input.witness_utxo;
220
166
    }
221
222
35.5k
    partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
223
35.5k
    ripemd160_preimages.insert(input.ripemd160_preimages.begin(), input.ripemd160_preimages.end());
224
35.5k
    sha256_preimages.insert(input.sha256_preimages.begin(), input.sha256_preimages.end());
225
35.5k
    hash160_preimages.insert(input.hash160_preimages.begin(), input.hash160_preimages.end());
226
35.5k
    hash256_preimages.insert(input.hash256_preimages.begin(), input.hash256_preimages.end());
227
35.5k
    hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
228
35.5k
    unknown.insert(input.unknown.begin(), input.unknown.end());
229
35.5k
    m_tap_script_sigs.insert(input.m_tap_script_sigs.begin(), input.m_tap_script_sigs.end());
230
35.5k
    m_tap_scripts.insert(input.m_tap_scripts.begin(), input.m_tap_scripts.end());
231
35.5k
    m_tap_bip32_paths.insert(input.m_tap_bip32_paths.begin(), input.m_tap_bip32_paths.end());
232
233
35.5k
    if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
234
35.5k
    if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
235
35.5k
    if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
236
35.5k
    if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
237
35.5k
    if (m_tap_key_sig.empty() && !input.m_tap_key_sig.empty()) m_tap_key_sig = input.m_tap_key_sig;
238
35.5k
    if (m_tap_internal_key.IsNull() && !input.m_tap_internal_key.IsNull()) m_tap_internal_key = input.m_tap_internal_key;
239
35.5k
    if (m_tap_merkle_root.IsNull() && !input.m_tap_merkle_root.IsNull()) m_tap_merkle_root = input.m_tap_merkle_root;
240
35.5k
    m_musig2_participants.insert(input.m_musig2_participants.begin(), input.m_musig2_participants.end());
241
35.5k
    for (const auto& [agg_key_lh, pubnonces] : input.m_musig2_pubnonces) {
242
576
        m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
243
576
    }
244
35.5k
    for (const auto& [agg_key_lh, psigs] : input.m_musig2_partial_sigs) {
245
239
        m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
246
239
    }
247
35.5k
}
248
249
void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
250
1.63k
{
251
1.63k
    if (!redeem_script.empty()) {
252
97
        sigdata.redeem_script = redeem_script;
253
97
    }
254
1.63k
    if (!witness_script.empty()) {
255
71
        sigdata.witness_script = witness_script;
256
71
    }
257
1.63k
    for (const auto& key_pair : hd_keypaths) {
258
701
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
259
701
    }
260
1.63k
    if (!m_tap_tree.empty() && m_tap_internal_key.IsFullyValid()) {
261
88
        TaprootBuilder builder;
262
260
        for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
263
260
            builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
264
260
        }
265
88
        assert(builder.IsComplete());
266
88
        builder.Finalize(m_tap_internal_key);
267
88
        TaprootSpendData spenddata = builder.GetSpendData();
268
269
88
        sigdata.tr_spenddata.internal_key = m_tap_internal_key;
270
88
        sigdata.tr_spenddata.Merge(spenddata);
271
88
    }
272
1.63k
    for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
273
311
        sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
274
311
        sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
275
311
    }
276
1.63k
    sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
277
1.63k
}
278
279
void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
280
1.63k
{
281
1.63k
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
282
0
        redeem_script = sigdata.redeem_script;
283
0
    }
284
1.63k
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
285
0
        witness_script = sigdata.witness_script;
286
0
    }
287
1.63k
    for (const auto& entry : sigdata.misc_pubkeys) {
288
702
        hd_keypaths.emplace(entry.second);
289
702
    }
290
1.63k
    if (!sigdata.tr_spenddata.internal_key.IsNull()) {
291
88
        m_tap_internal_key = sigdata.tr_spenddata.internal_key;
292
88
    }
293
1.63k
    if (sigdata.tr_builder.has_value() && sigdata.tr_builder->HasScripts()) {
294
0
        m_tap_tree = sigdata.tr_builder->GetTreeTuples();
295
0
    }
296
1.63k
    for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
297
311
        m_tap_bip32_paths.emplace(pubkey, leaf_origin);
298
311
    }
299
1.63k
    m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
300
1.63k
}
301
302
bool PSBTOutput::IsNull() const
303
15.0k
{
304
15.0k
    return redeem_script.empty() && witness_script.empty() && hd_keypaths.empty() && unknown.empty();
305
15.0k
}
306
307
void PSBTOutput::Merge(const PSBTOutput& output)
308
47.2k
{
309
47.2k
    hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
310
47.2k
    unknown.insert(output.unknown.begin(), output.unknown.end());
311
47.2k
    m_tap_bip32_paths.insert(output.m_tap_bip32_paths.begin(), output.m_tap_bip32_paths.end());
312
313
47.2k
    if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
314
47.2k
    if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
315
47.2k
    if (m_tap_internal_key.IsNull() && !output.m_tap_internal_key.IsNull()) m_tap_internal_key = output.m_tap_internal_key;
316
47.2k
    if (m_tap_tree.empty() && !output.m_tap_tree.empty()) m_tap_tree = output.m_tap_tree;
317
47.2k
    m_musig2_participants.insert(output.m_musig2_participants.begin(), output.m_musig2_participants.end());
318
47.2k
}
319
320
bool PSBTInputSigned(const PSBTInput& input)
321
30.0k
{
322
30.0k
    return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
323
30.0k
}
324
325
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
326
54.0k
{
327
54.0k
    CTxOut utxo;
328
54.0k
    assert(input_index < psbt.inputs.size());
329
54.0k
    const PSBTInput& input = psbt.inputs[input_index];
330
331
54.0k
    if (input.non_witness_utxo) {
332
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
333
771
        COutPoint prevout = psbt.tx->vin[input_index].prevout;
334
771
        if (prevout.n >= input.non_witness_utxo->vout.size()) {
335
0
            return false;
336
0
        }
337
771
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
338
0
            return false;
339
0
        }
340
771
        utxo = input.non_witness_utxo->vout[prevout.n];
341
53.2k
    } else if (!input.witness_utxo.IsNull()) {
342
30.5k
        utxo = input.witness_utxo;
343
30.5k
    } else {
344
22.7k
        return false;
345
22.7k
    }
346
347
31.3k
    if (txdata) {
348
28.5k
        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.5k
    } else {
350
2.82k
        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
2.82k
    }
352
31.3k
}
353
354
5.22k
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt) {
355
5.22k
    size_t count = 0;
356
11.4k
    for (const auto& input : psbt.inputs) {
357
11.4k
        if (!PSBTInputSigned(input)) {
358
9.55k
            count++;
359
9.55k
        }
360
11.4k
    }
361
362
5.22k
    return count;
363
5.22k
}
364
365
void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index)
366
1.63k
{
367
1.63k
    CMutableTransaction& tx = *Assert(psbt.tx);
368
1.63k
    const CTxOut& out = tx.vout.at(index);
369
1.63k
    PSBTOutput& psbt_out = psbt.outputs.at(index);
370
371
    // Fill a SignatureData with output info
372
1.63k
    SignatureData sigdata;
373
1.63k
    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
1.63k
    MutableTransactionSignatureCreator creator(tx, /*input_idx=*/0, out.nValue, SIGHASH_ALL);
379
1.63k
    ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
380
381
    // Put redeem_script, witness_script, key paths, into PSBTOutput.
382
1.63k
    psbt_out.FromSignatureData(sigdata);
383
1.63k
}
384
385
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt)
386
26.1k
{
387
26.1k
    const CMutableTransaction& tx = *psbt.tx;
388
26.1k
    bool have_all_spent_outputs = true;
389
26.1k
    std::vector<CTxOut> utxos(tx.vin.size());
390
70.1k
    for (size_t idx = 0; idx < tx.vin.size(); ++idx) {
391
44.0k
        if (!psbt.GetInputUTXO(utxos[idx], idx)) have_all_spent_outputs = false;
392
44.0k
    }
393
26.1k
    PrecomputedTransactionData txdata;
394
26.1k
    if (have_all_spent_outputs) {
395
18.4k
        txdata.Init(tx, std::move(utxos), true);
396
18.4k
    } else {
397
7.62k
        txdata.Init(tx, {}, true);
398
7.62k
    }
399
26.1k
    return txdata;
400
26.1k
}
401
402
PSBTError SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, std::optional<int> sighash,  SignatureData* out_sigdata, bool finalize)
403
41.4k
{
404
41.4k
    PSBTInput& input = psbt.inputs.at(index);
405
41.4k
    const CMutableTransaction& tx = *psbt.tx;
406
407
41.4k
    if (PSBTInputSignedAndVerified(psbt, index, txdata)) {
408
1.25k
        return PSBTError::OK;
409
1.25k
    }
410
411
    // Fill SignatureData with input info
412
40.1k
    SignatureData sigdata;
413
40.1k
    input.FillSignatureData(sigdata);
414
415
    // Get UTXO
416
40.1k
    bool require_witness_sig = false;
417
40.1k
    CTxOut utxo;
418
419
40.1k
    if (input.non_witness_utxo) {
420
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
421
610
        COutPoint prevout = tx.vin[index].prevout;
422
610
        if (prevout.n >= input.non_witness_utxo->vout.size()) {
423
0
            return PSBTError::MISSING_INPUTS;
424
0
        }
425
610
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
426
0
            return PSBTError::MISSING_INPUTS;
427
0
        }
428
610
        utxo = input.non_witness_utxo->vout[prevout.n];
429
39.5k
    } else if (!input.witness_utxo.IsNull()) {
430
22.7k
        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
22.7k
        require_witness_sig = true;
436
22.7k
    } else {
437
16.8k
        return PSBTError::MISSING_INPUTS;
438
16.8k
    }
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.3k
    if (!sighash) sighash = utxo.scriptPubKey.IsPayToTaproot() ? SIGHASH_DEFAULT : SIGHASH_ALL;
446
23.3k
    Assert(sighash.has_value());
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.3k
    if (input.sighash_type && input.sighash_type != sighash) {
449
91
        return PSBTError::SIGHASH_MISMATCH;
450
91
    }
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.2k
    if (utxo.scriptPubKey.IsPayToTaproot() ? sighash != SIGHASH_DEFAULT :
455
23.2k
                                            (sighash != SIGHASH_DEFAULT && sighash != SIGHASH_ALL)) {
456
1.86k
        input.sighash_type = sighash;
457
1.86k
    }
458
459
    // Check all existing signatures use the sighash type
460
23.2k
    if (sighash == SIGHASH_DEFAULT) {
461
4.32k
        if (!input.m_tap_key_sig.empty() && input.m_tap_key_sig.size() != 64) {
462
33
            return PSBTError::SIGHASH_MISMATCH;
463
33
        }
464
4.29k
        for (const auto& [_, sig] : input.m_tap_script_sigs) {
465
379
            if (sig.size() != 64) return PSBTError::SIGHASH_MISMATCH;
466
379
        }
467
18.9k
    } else {
468
18.9k
        if (!input.m_tap_key_sig.empty() && (input.m_tap_key_sig.size() != 65 || input.m_tap_key_sig.back() != *sighash)) {
469
198
            return PSBTError::SIGHASH_MISMATCH;
470
198
        }
471
18.7k
        for (const auto& [_, sig] : input.m_tap_script_sigs) {
472
1.24k
            if (sig.size() != 65 || sig.back() != *sighash) return PSBTError::SIGHASH_MISMATCH;
473
1.24k
        }
474
17.6k
        for (const auto& [_, sig] : input.partial_sigs) {
475
2.88k
            if (sig.second.back() != *sighash) return PSBTError::SIGHASH_MISMATCH;
476
2.88k
        }
477
17.6k
    }
478
479
21.8k
    sigdata.witness = false;
480
21.8k
    bool sig_complete;
481
21.8k
    if (txdata == nullptr) {
482
2.48k
        sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
483
19.3k
    } else {
484
19.3k
        MutableTransactionSignatureCreator creator(tx, index, utxo.nValue, txdata, *sighash);
485
19.3k
        sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
486
19.3k
    }
487
    // Verify that a witness signature was produced in case one was required.
488
21.8k
    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
9.20k
    if (!finalize && sigdata.complete) sigdata.complete = false;
492
493
9.20k
    input.FromSignatureData(sigdata);
494
495
    // If we have a witness signature, put a witness UTXO.
496
9.20k
    if (sigdata.witness) {
497
8.77k
        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
8.77k
    }
502
503
    // Fill in the missing info
504
9.20k
    if (out_sigdata) {
505
2.76k
        out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
506
2.76k
        out_sigdata->missing_sigs = sigdata.missing_sigs;
507
2.76k
        out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
508
2.76k
        out_sigdata->missing_witness_script = sigdata.missing_witness_script;
509
2.76k
    }
510
511
9.20k
    return sig_complete ? PSBTError::OK : PSBTError::INCOMPLETE;
512
21.8k
}
513
514
void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx)
515
468
{
516
    // Figure out if any non_witness_utxos should be dropped
517
468
    std::vector<unsigned int> to_drop;
518
726
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
519
537
        const auto& input = psbtx.inputs.at(i);
520
537
        int wit_ver;
521
537
        std::vector<unsigned char> wit_prog;
522
537
        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
272
            to_drop.clear();
525
272
            break;
526
272
        }
527
265
        if (wit_ver == 0) {
528
            // Segwit v0, so we cannot drop any non_witness_utxos
529
7
            to_drop.clear();
530
7
            break;
531
7
        }
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
258
        if (input.sighash_type != std::nullopt && (*input.sighash_type & 0x80) == SIGHASH_ANYONECANPAY) {
536
0
            to_drop.clear();
537
0
            break;
538
0
        }
539
540
258
        if (input.non_witness_utxo) {
541
0
            to_drop.push_back(i);
542
0
        }
543
258
    }
544
545
    // Drop the non_witness_utxos that we can drop
546
468
    for (unsigned int i : to_drop) {
547
0
        psbtx.inputs.at(i).non_witness_utxo = nullptr;
548
0
    }
549
468
}
550
551
bool FinalizePSBT(PartiallySignedTransaction& psbtx)
552
10.8k
{
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
10.8k
    bool complete = true;
558
10.8k
    const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
559
34.4k
    for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
560
23.5k
        PSBTInput& input = psbtx.inputs.at(i);
561
23.5k
        complete &= (SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, input.sighash_type, nullptr, true) == PSBTError::OK);
562
23.5k
    }
563
564
10.8k
    return complete;
565
10.8k
}
566
567
bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result)
568
5.61k
{
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
5.61k
    if (!FinalizePSBT(psbtx)) {
572
4.58k
        return false;
573
4.58k
    }
574
575
1.02k
    result = *psbtx.tx;
576
1.48k
    for (unsigned int i = 0; i < result.vin.size(); ++i) {
577
456
        result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
578
456
        result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
579
456
    }
580
1.02k
    return true;
581
5.61k
}
582
583
bool CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs)
584
5.98k
{
585
5.98k
    out = psbtxs[0]; // Copy the first one
586
587
    // Merge
588
18.1k
    for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
589
12.4k
        if (!out.Merge(*it)) {
590
353
            return false;
591
353
        }
592
12.4k
    }
593
5.63k
    return true;
594
5.98k
}
595
596
17.4k
std::string PSBTRoleName(PSBTRole role) {
597
17.4k
    switch (role) {
598
2.49k
    case PSBTRole::CREATOR: return "creator";
599
13.8k
    case PSBTRole::UPDATER: return "updater";
600
281
    case PSBTRole::SIGNER: return "signer";
601
128
    case PSBTRole::FINALIZER: return "finalizer";
602
713
    case PSBTRole::EXTRACTOR: return "extractor";
603
17.4k
    } // no default case, so the compiler can warn about missing cases
604
17.4k
    assert(false);
605
0
}
606
607
bool DecodeBase64PSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
608
26.3k
{
609
26.3k
    auto tx_data = DecodeBase64(base64_tx);
610
26.3k
    if (!tx_data) {
611
124
        error = "invalid base64";
612
124
        return false;
613
124
    }
614
26.1k
    return DecodeRawPSBT(psbt, MakeByteSpan(*tx_data), error);
615
26.3k
}
616
617
bool DecodeRawPSBT(PartiallySignedTransaction& psbt, std::span<const std::byte> tx_data, std::string& error)
618
37.5k
{
619
37.5k
    SpanReader ss_data{tx_data};
620
37.5k
    try {
621
37.5k
        ss_data >> psbt;
622
37.5k
        if (!ss_data.empty()) {
623
585
            error = "extra data after PSBT";
624
585
            return false;
625
585
        }
626
37.5k
    } catch (const std::exception& e) {
627
7.34k
        error = e.what();
628
7.34k
        return false;
629
7.34k
    }
630
29.6k
    return true;
631
37.5k
}
632
633
uint32_t PartiallySignedTransaction::GetVersion() const
634
62.5k
{
635
62.5k
    if (m_version != std::nullopt) {
636
128
        return *m_version;
637
128
    }
638
62.4k
    return 0;
639
62.5k
}