Coverage Report

Created: 2026-09-02 14:16

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 <primitives/transaction.h>
11
#include <script/signingprovider.h>
12
#include <util/check.h>
13
#include <util/result.h>
14
#include <util/strencodings.h>
15
16
#include <algorithm>
17
#include <set>
18
19
using common::PSBTError;
20
21
545
PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx, uint32_t version) : m_version(version)
22
545
{
23
545
    assert(m_version == 0 || m_version == 2);
24
25
545
    tx_version = tx.version;
26
545
    fallback_locktime = tx.nLockTime;
27
545
    inputs.reserve(tx.vin.size());
28
1.78k
    for (const CTxIn& input : tx.vin) {
29
1.78k
        inputs.emplace_back(GetVersion(), input.prevout.hash, input.prevout.n, input.nSequence);
30
1.78k
    }
31
545
    outputs.reserve(tx.vout.size());
32
4.22k
    for (const CTxOut& output : tx.vout) {
33
4.22k
        outputs.emplace_back(GetVersion(), output.nValue, output.scriptPubKey);
34
4.22k
    }
35
545
}
36
37
bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt)
38
203
{
39
    // Prohibited to merge two PSBTs over different transactions
40
203
    std::optional<Txid> this_id = GetUniqueID();
41
203
    std::optional<Txid> psbt_id = psbt.GetUniqueID();
42
203
    if (!this_id || !psbt_id || this_id != psbt_id) {
43
1
        return false;
44
1
    }
45
202
    if (GetVersion() != psbt.GetVersion()) {
46
0
        return false;
47
0
    }
48
49
406
    for (unsigned int i = 0; i < inputs.size(); ++i) {
50
204
        if (!inputs[i].Merge(psbt.inputs[i])) {
51
0
            return false;
52
0
        }
53
204
    }
54
590
    for (unsigned int i = 0; i < outputs.size(); ++i) {
55
388
        if (!outputs[i].Merge(psbt.outputs[i])) {
56
0
            return false;
57
0
        }
58
388
    }
59
202
    MergeGlobalXPubs(psbt);
60
202
    if (fallback_locktime == std::nullopt && psbt.fallback_locktime != std::nullopt) fallback_locktime = psbt.fallback_locktime;
61
62
    // Set m_tx_modifiable only if either PSBT had it set
63
202
    if (m_tx_modifiable.has_value() || psbt.m_tx_modifiable.has_value()) {
64
        // In general, we AND the modifiable flags
65
0
        std::bitset<8> this_modifiable = m_tx_modifiable.value_or(0);
66
0
        std::bitset<8> psbt_modifiable = psbt.m_tx_modifiable.value_or(0);
67
0
        std::bitset<8> final_modifiable = this_modifiable & psbt_modifiable;
68
        // SIGHASH_SINGLE Modifiable (bit 2) needs to be bitwise OR'd
69
0
        final_modifiable.set(2, this_modifiable[2] || psbt_modifiable[2]);
70
71
0
        m_tx_modifiable = final_modifiable;
72
0
    }
73
74
202
    m_proprietary.insert(psbt.m_proprietary.begin(), psbt.m_proprietary.end());
75
202
    unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
76
77
202
    return true;
78
202
}
79
80
void PartiallySignedTransaction::MergeGlobalXPubs(const PartiallySignedTransaction& psbt)
81
213
{
82
213
    for (const auto& [origin, xpubs] : psbt.m_xpubs) {
83
5
        for (const CExtPubKey& xpub : xpubs) {
84
5
            const bool known{std::ranges::any_of(m_xpubs, [&](const auto& entry) { return entry.second.contains(xpub); })};
85
5
            if (!known) m_xpubs[origin].insert(xpub);
86
5
        }
87
5
    }
88
213
}
89
90
std::optional<uint32_t> PartiallySignedTransaction::ComputeTimeLock() const
91
61.1k
{
92
61.1k
    if (GetVersion() >= 2) {
93
60.3k
        std::optional<uint32_t> time_lock{0};
94
60.3k
        std::optional<uint32_t> height_lock{0};
95
7.49M
        for (const PSBTInput& input : inputs) {
96
7.49M
            if (input.time_locktime.has_value() && !input.height_locktime.has_value()) {
97
10
                height_lock.reset(); // Transaction can no longer have a height locktime
98
10
                if (!time_lock.has_value()) {
99
2
                    return std::nullopt;
100
2
                }
101
7.49M
            } else if (!input.time_locktime.has_value() && input.height_locktime.has_value()) {
102
10
                time_lock.reset(); // Transaction can no longer have a time locktime
103
10
                if (!height_lock.has_value()) {
104
0
                    return std::nullopt;
105
0
                }
106
10
            }
107
7.49M
            if (input.time_locktime && time_lock.has_value()) {
108
19
                time_lock = std::max(time_lock, input.time_locktime);
109
19
            }
110
7.49M
            if (input.height_locktime && height_lock.has_value()) {
111
21
                height_lock = std::max(height_lock, input.height_locktime);
112
21
            }
113
7.49M
        }
114
60.3k
        if (height_lock.has_value() && *height_lock > 0) {
115
9
            return *height_lock;
116
9
        }
117
60.3k
        if (time_lock.has_value() && *time_lock > 0) {
118
8
            return *time_lock;
119
8
        }
120
60.3k
    }
121
61.1k
    return fallback_locktime.value_or(0);
122
61.1k
}
123
124
std::optional<CMutableTransaction> PartiallySignedTransaction::GetUnsignedTx() const
125
61.1k
{
126
61.1k
    CMutableTransaction mtx;
127
61.1k
    mtx.version = tx_version;
128
61.1k
    std::optional<uint32_t> locktime = ComputeTimeLock();
129
61.1k
    if (!locktime) {
130
1
        return std::nullopt;
131
1
    }
132
61.1k
    mtx.nLockTime = *locktime;
133
61.1k
    uint32_t max_sequence = CTxIn::SEQUENCE_FINAL;
134
7.49M
    for (const PSBTInput& input : inputs) {
135
7.49M
        CTxIn txin;
136
7.49M
        txin.prevout.hash = input.prev_txid;
137
7.49M
        txin.prevout.n = input.prev_out;
138
7.49M
        txin.nSequence = input.sequence.value_or(max_sequence);
139
7.49M
        mtx.vin.push_back(txin);
140
7.49M
    }
141
816k
    for (const PSBTOutput& output : outputs) {
142
816k
        CTxOut txout;
143
816k
        txout.nValue = output.amount;
144
816k
        txout.scriptPubKey = output.script;
145
816k
        mtx.vout.push_back(txout);
146
816k
    }
147
61.1k
    return mtx;
148
61.1k
}
149
150
std::optional<Txid> PartiallySignedTransaction::GetUniqueID() const
151
406
{
152
    // Get the unsigned transaction
153
406
    std::optional<CMutableTransaction> mtx = GetUnsignedTx();
154
406
    if (!mtx) {
155
0
        return std::nullopt;
156
0
    }
157
406
    if (GetVersion() >= 2) {
158
376
        for (CTxIn& txin : mtx->vin) {
159
376
            txin.nSequence = 0;
160
376
        }
161
374
    }
162
406
    return mtx->GetHash();
163
406
}
164
165
bool PartiallySignedTransaction::AddInput(const PSBTInput& psbtin)
166
37
{
167
    // The input being added must be for this PSBT's version
168
37
    if (psbtin.GetVersion() != GetVersion()) {
169
1
        return false;
170
1
    }
171
172
    // Prevent duplicate inputs
173
36
    if (std::find_if(inputs.begin(), inputs.end(),
174
78
        [psbtin](const PSBTInput& psbt) {
175
78
            return psbt.prev_txid == psbtin.prev_txid && psbt.prev_out == psbtin.prev_out;
176
78
        }
177
36
    ) != inputs.end()) {
178
7
        return false;
179
7
    }
180
181
29
    if (GetVersion() < 2) {
182
        // This is a v0 psbt, so do the v0 AddInput
183
21
        inputs.push_back(psbtin);
184
21
        inputs.back().partial_sigs.clear();
185
21
        inputs.back().final_script_sig.clear();
186
21
        inputs.back().final_script_witness.SetNull();
187
21
        return true;
188
21
    }
189
190
    // Check inputs modifiable flag
191
8
    if (!m_tx_modifiable.has_value() || !m_tx_modifiable->test(0)) {
192
1
        return false;
193
1
    }
194
195
    // Determine if we need to iterate the inputs.
196
    // For now, we only do this if the new input has a required time lock.
197
    // BIP 370 states that we should also do this if m_tx_modifiable's bit 2 is set
198
    // (Has SIGHASH_SINGLE flag) but since we are only adding inputs at the end of the vector,
199
    // we don't care about that.
200
7
    bool iterate_inputs = psbtin.time_locktime != std::nullopt || psbtin.height_locktime != std::nullopt;
201
7
    if (iterate_inputs) {
202
4
        std::optional<uint32_t> old_timelock = ComputeTimeLock();
203
4
        if (!old_timelock) {
204
0
            return false;
205
0
        }
206
207
4
        std::optional<uint32_t> time_lock = psbtin.time_locktime;
208
4
        std::optional<uint32_t> height_lock = psbtin.height_locktime;
209
4
        bool has_sigs = false;
210
14
        for (const PSBTInput& input : inputs) {
211
14
            if (input.time_locktime.has_value() && !input.height_locktime.has_value()) {
212
2
                height_lock.reset(); // Transaction can no longer have a height locktime
213
2
                if (time_lock == std::nullopt) {
214
1
                    return false;
215
1
                }
216
12
            } else if (!input.time_locktime.has_value() && input.height_locktime.has_value()) {
217
0
                time_lock.reset(); // Transaction can no longer have a time locktime
218
0
                if (height_lock == std::nullopt) {
219
0
                    return false;
220
0
                }
221
0
            }
222
13
            if (input.time_locktime && time_lock.has_value()) {
223
3
                time_lock = std::max(time_lock, input.time_locktime);
224
3
            }
225
13
            if (input.height_locktime && height_lock.has_value()) {
226
1
                height_lock = std::max(height_lock, input.height_locktime);
227
1
            }
228
13
            if (input.HasSignatures()) {
229
1
                has_sigs = true;
230
1
            }
231
13
        }
232
3
        uint32_t new_timelock = fallback_locktime.value_or(0);
233
3
        if (height_lock.has_value() && *height_lock > 0) {
234
1
            new_timelock = *height_lock;
235
2
        } else if (time_lock.has_value() && *time_lock > 0) {
236
2
            new_timelock = *time_lock;
237
2
        }
238
3
        if (has_sigs && *old_timelock != new_timelock) {
239
1
            return false;
240
1
        }
241
3
    }
242
243
    // Add the input to the end
244
5
    inputs.push_back(psbtin);
245
5
    return true;
246
7
}
247
248
bool PartiallySignedTransaction::AddOutput(const PSBTOutput& psbtout)
249
15
{
250
    // The output being added must be for this PSBT's version
251
15
    if (psbtout.GetVersion() != GetVersion()) {
252
1
        return false;
253
1
    }
254
255
14
    if (GetVersion() < 2) {
256
        // This is a v0 psbt, do the v0 AddOutput
257
11
        outputs.push_back(psbtout);
258
11
        return true;
259
11
    }
260
261
    // No global tx, must be PSBTv2
262
    // Check outputs are modifiable
263
3
    if (!m_tx_modifiable.has_value() || !m_tx_modifiable->test(1)) {
264
1
        return false;
265
1
    }
266
2
    outputs.push_back(psbtout);
267
268
2
    return true;
269
3
}
270
271
bool PSBTInput::GetUTXO(CTxOut& utxo) const
272
5.84k
{
273
5.84k
    if (non_witness_utxo) {
274
5.11k
        if (prev_out >= non_witness_utxo->vout.size()) {
275
1
            return false;
276
1
        }
277
5.10k
        if (non_witness_utxo->GetHash() != prev_txid) {
278
0
            return false;
279
0
        }
280
5.10k
        utxo = non_witness_utxo->vout[prev_out];
281
5.10k
    } else if (!witness_utxo.IsNull()) {
282
701
        utxo = witness_utxo;
283
701
    } else {
284
38
        return false;
285
38
    }
286
5.81k
    return true;
287
5.84k
}
288
289
COutPoint PSBTInput::GetOutPoint() const
290
52.1k
{
291
52.1k
    return COutPoint(prev_txid, prev_out);
292
52.1k
}
293
294
void PSBTInput::FillSignatureData(SignatureData& sigdata) const
295
25.0k
{
296
25.0k
    if (!final_script_sig.empty()) {
297
0
        sigdata.scriptSig = final_script_sig;
298
0
        sigdata.complete = true;
299
0
    }
300
25.0k
    if (!final_script_witness.IsNull()) {
301
0
        sigdata.scriptWitness = final_script_witness;
302
0
        sigdata.complete = true;
303
0
    }
304
25.0k
    if (sigdata.complete) {
305
0
        return;
306
0
    }
307
308
25.0k
    sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
309
25.0k
    if (!redeem_script.empty()) {
310
4.42k
        sigdata.redeem_script = redeem_script;
311
4.42k
    }
312
25.0k
    if (!witness_script.empty()) {
313
404
        sigdata.witness_script = witness_script;
314
404
    }
315
25.0k
    for (const auto& key_pair : hd_keypaths) {
316
14.7k
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
317
14.7k
    }
318
25.0k
    if (!m_tap_key_sig.empty()) {
319
191
        sigdata.taproot_key_path_sig = m_tap_key_sig;
320
191
    }
321
25.0k
    for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
322
593
        sigdata.taproot_script_sigs.emplace(pubkey_leaf, sig);
323
593
    }
324
25.0k
    if (!m_tap_internal_key.IsNull()) {
325
3.74k
        sigdata.tr_spenddata.internal_key = m_tap_internal_key;
326
3.74k
    }
327
25.0k
    if (!m_tap_merkle_root.IsNull()) {
328
2.85k
        sigdata.tr_spenddata.merkle_root = m_tap_merkle_root;
329
2.85k
    }
330
25.0k
    for (const auto& [leaf_script, control_block] : m_tap_scripts) {
331
4.22k
        sigdata.tr_spenddata.scripts.emplace(leaf_script, control_block);
332
4.22k
    }
333
25.0k
    for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
334
18.5k
        sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
335
18.5k
        sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
336
18.5k
    }
337
25.0k
    for (const auto& [hash, preimage] : ripemd160_preimages) {
338
0
        sigdata.ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
339
0
    }
340
25.0k
    for (const auto& [hash, preimage] : sha256_preimages) {
341
12
        sigdata.sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
342
12
    }
343
25.0k
    for (const auto& [hash, preimage] : hash160_preimages) {
344
0
        sigdata.hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
345
0
    }
346
25.0k
    for (const auto& [hash, preimage] : hash256_preimages) {
347
0
        sigdata.hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
348
0
    }
349
25.0k
    sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
350
25.0k
    for (const auto& [agg_key_lh, pubnonces] : m_musig2_pubnonces) {
351
3.71k
        sigdata.musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
352
3.71k
    }
353
25.0k
    for (const auto& [agg_key_lh, psigs] : m_musig2_partial_sigs) {
354
845
        sigdata.musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
355
845
    }
356
25.0k
}
357
358
void PSBTInput::FromSignatureData(const SignatureData& sigdata)
359
24.9k
{
360
24.9k
    if (sigdata.complete) {
361
1.75k
        partial_sigs.clear();
362
1.75k
        hd_keypaths.clear();
363
1.75k
        redeem_script.clear();
364
1.75k
        witness_script.clear();
365
366
1.75k
        if (!sigdata.scriptSig.empty()) {
367
776
            final_script_sig = sigdata.scriptSig;
368
776
        }
369
1.75k
        if (!sigdata.scriptWitness.IsNull()) {
370
1.48k
            final_script_witness = sigdata.scriptWitness;
371
1.48k
        }
372
1.75k
        return;
373
1.75k
    }
374
375
23.2k
    partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
376
23.2k
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
377
543
        redeem_script = sigdata.redeem_script;
378
543
    }
379
23.2k
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
380
33
        witness_script = sigdata.witness_script;
381
33
    }
382
23.2k
    for (const auto& entry : sigdata.misc_pubkeys) {
383
14.8k
        hd_keypaths.emplace(entry.second);
384
14.8k
    }
385
23.2k
    if (!sigdata.taproot_key_path_sig.empty()) {
386
216
        m_tap_key_sig = sigdata.taproot_key_path_sig;
387
216
    }
388
23.2k
    for (const auto& [pubkey_leaf, sig] : sigdata.taproot_script_sigs) {
389
657
        m_tap_script_sigs.emplace(pubkey_leaf, sig);
390
657
    }
391
23.2k
    if (!sigdata.tr_spenddata.internal_key.IsNull()) {
392
3.64k
        m_tap_internal_key = sigdata.tr_spenddata.internal_key;
393
3.64k
    }
394
23.2k
    if (!sigdata.tr_spenddata.merkle_root.IsNull()) {
395
2.76k
        m_tap_merkle_root = sigdata.tr_spenddata.merkle_root;
396
2.76k
    }
397
23.2k
    for (const auto& [leaf_script, control_block] : sigdata.tr_spenddata.scripts) {
398
4.09k
        m_tap_scripts.emplace(leaf_script, control_block);
399
4.09k
    }
400
23.2k
    for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
401
18.1k
        m_tap_bip32_paths.emplace(pubkey, leaf_origin);
402
18.1k
    }
403
23.2k
    m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
404
23.2k
    for (const auto& [agg_key_lh, pubnonces] : sigdata.musig2_pubnonces) {
405
3.85k
        m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
406
3.85k
    }
407
23.2k
    for (const auto& [agg_key_lh, psigs] : sigdata.musig2_partial_sigs) {
408
916
        m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
409
916
    }
410
23.2k
    for (const auto& [hash, preimage] : sigdata.ripemd160_preimages) {
411
0
        ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
412
0
    }
413
23.2k
    for (const auto& [hash, preimage] : sigdata.sha256_preimages) {
414
11
        sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
415
11
    }
416
23.2k
    for (const auto& [hash, preimage] : sigdata.hash160_preimages) {
417
0
        hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
418
0
    }
419
23.2k
    for (const auto& [hash, preimage] : sigdata.hash256_preimages) {
420
0
        hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
421
0
    }
422
23.2k
}
423
424
bool PSBTInput::Merge(const PSBTInput& input)
425
204
{
426
204
    if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
427
204
    if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
428
1
        witness_utxo = input.witness_utxo;
429
1
    }
430
431
204
    partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
432
204
    ripemd160_preimages.insert(input.ripemd160_preimages.begin(), input.ripemd160_preimages.end());
433
204
    sha256_preimages.insert(input.sha256_preimages.begin(), input.sha256_preimages.end());
434
204
    hash160_preimages.insert(input.hash160_preimages.begin(), input.hash160_preimages.end());
435
204
    hash256_preimages.insert(input.hash256_preimages.begin(), input.hash256_preimages.end());
436
204
    hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
437
204
    m_proprietary.insert(input.m_proprietary.begin(), input.m_proprietary.end());
438
204
    unknown.insert(input.unknown.begin(), input.unknown.end());
439
204
    m_tap_script_sigs.insert(input.m_tap_script_sigs.begin(), input.m_tap_script_sigs.end());
440
    // Merge by control block, the serialized key (BIP 371), to avoid duplicate keys. Keep the
441
    // leaf script already present; BIP 174 lets the Combiner pick arbitrarily on conflict.
442
204
    std::set<std::vector<unsigned char>> seen_control_blocks;
443
204
    for (const auto& [_, control_blocks] : m_tap_scripts) {
444
161
        seen_control_blocks.insert(control_blocks.begin(), control_blocks.end());
445
161
    }
446
204
    for (const auto& [leaf, control_blocks] : input.m_tap_scripts) {
447
161
        for (const auto& control_block : control_blocks) {
448
161
            if (seen_control_blocks.insert(control_block).second) m_tap_scripts[leaf].insert(control_block);
449
161
        }
450
160
    }
451
204
    m_tap_bip32_paths.insert(input.m_tap_bip32_paths.begin(), input.m_tap_bip32_paths.end());
452
453
204
    if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
454
204
    if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
455
204
    if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
456
204
    if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
457
204
    if (m_tap_key_sig.empty() && !input.m_tap_key_sig.empty()) m_tap_key_sig = input.m_tap_key_sig;
458
204
    if (m_tap_internal_key.IsNull() && !input.m_tap_internal_key.IsNull()) m_tap_internal_key = input.m_tap_internal_key;
459
204
    if (m_tap_merkle_root.IsNull() && !input.m_tap_merkle_root.IsNull()) m_tap_merkle_root = input.m_tap_merkle_root;
460
204
    m_musig2_participants.insert(input.m_musig2_participants.begin(), input.m_musig2_participants.end());
461
233
    for (const auto& [agg_key_lh, pubnonces] : input.m_musig2_pubnonces) {
462
233
        m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
463
233
    }
464
204
    for (const auto& [agg_key_lh, psigs] : input.m_musig2_partial_sigs) {
465
105
        m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
466
105
    }
467
204
    if (sequence == std::nullopt && input.sequence != std::nullopt) sequence = input.sequence;
468
204
    if (time_locktime == std::nullopt && input.time_locktime != std::nullopt) time_locktime = input.time_locktime;
469
204
    if (height_locktime == std::nullopt && input.height_locktime != std::nullopt) height_locktime = input.height_locktime;
470
471
204
    return true;
472
204
}
473
474
bool PSBTInput::HasSignatures() const
475
13
{
476
13
    return !final_script_sig.empty()
477
13
           || !final_script_witness.IsNull()
478
13
           || !partial_sigs.empty()
479
13
           || !m_tap_key_sig.empty()
480
13
           || !m_tap_script_sigs.empty()
481
13
           || !m_musig2_partial_sigs.empty();
482
13
}
483
484
void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
485
1.14k
{
486
1.14k
    if (!redeem_script.empty()) {
487
7
        sigdata.redeem_script = redeem_script;
488
7
    }
489
1.14k
    if (!witness_script.empty()) {
490
8
        sigdata.witness_script = witness_script;
491
8
    }
492
1.14k
    for (const auto& key_pair : hd_keypaths) {
493
358
        sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
494
358
    }
495
1.14k
    if (!m_tap_tree.empty() && m_tap_internal_key.IsFullyValid()) {
496
145
        TaprootBuilder builder;
497
325
        for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
498
325
            builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
499
325
        }
500
145
        assert(builder.IsComplete());
501
145
        builder.Finalize(m_tap_internal_key);
502
145
        TaprootSpendData spenddata = builder.GetSpendData();
503
504
145
        sigdata.tr_spenddata.internal_key = m_tap_internal_key;
505
145
        sigdata.tr_spenddata.Merge(spenddata);
506
145
        sigdata.tr_builder = builder;
507
145
    }
508
1.14k
    for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
509
737
        sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
510
737
        sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
511
737
    }
512
1.14k
    sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
513
1.14k
}
514
515
void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
516
1.14k
{
517
1.14k
    if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
518
25
        redeem_script = sigdata.redeem_script;
519
25
    }
520
1.14k
    if (witness_script.empty() && !sigdata.witness_script.empty()) {
521
14
        witness_script = sigdata.witness_script;
522
14
    }
523
1.14k
    for (const auto& entry : sigdata.misc_pubkeys) {
524
830
        hd_keypaths.emplace(entry.second);
525
830
    }
526
1.14k
    if (!sigdata.tr_spenddata.internal_key.IsNull()) {
527
283
        m_tap_internal_key = sigdata.tr_spenddata.internal_key;
528
283
    }
529
1.14k
    if (sigdata.tr_builder.has_value() && sigdata.tr_builder->HasScripts()) {
530
209
        m_tap_tree = sigdata.tr_builder->GetTreeTuples();
531
209
    }
532
1.14k
    for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
533
1.02k
        m_tap_bip32_paths.emplace(pubkey, leaf_origin);
534
1.02k
    }
535
1.14k
    m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
536
1.14k
}
537
538
bool PSBTOutput::Merge(const PSBTOutput& output)
539
388
{
540
388
    hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
541
388
    m_proprietary.insert(output.m_proprietary.begin(), output.m_proprietary.end());
542
388
    unknown.insert(output.unknown.begin(), output.unknown.end());
543
388
    m_tap_bip32_paths.insert(output.m_tap_bip32_paths.begin(), output.m_tap_bip32_paths.end());
544
545
388
    if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
546
388
    if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
547
388
    if (m_tap_internal_key.IsNull() && !output.m_tap_internal_key.IsNull()) m_tap_internal_key = output.m_tap_internal_key;
548
388
    if (m_tap_tree.empty() && !output.m_tap_tree.empty()) m_tap_tree = output.m_tap_tree;
549
388
    m_musig2_participants.insert(output.m_musig2_participants.begin(), output.m_musig2_participants.end());
550
551
388
    return true;
552
388
}
553
554
bool PSBTInputSigned(const PSBTInput& input)
555
61.3k
{
556
61.3k
    return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
557
61.3k
}
558
559
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
560
30.4k
{
561
30.4k
    CTxOut utxo;
562
30.4k
    assert(input_index < psbt.inputs.size());
563
30.4k
    const PSBTInput& input = psbt.inputs[input_index];
564
565
30.4k
    if (input.non_witness_utxo) {
566
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
567
28.2k
        COutPoint prevout = input.GetOutPoint();
568
28.2k
        if (prevout.n >= input.non_witness_utxo->vout.size()) {
569
0
            return false;
570
0
        }
571
28.2k
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
572
0
            return false;
573
0
        }
574
28.2k
        utxo = input.non_witness_utxo->vout[prevout.n];
575
28.2k
    } else if (!input.witness_utxo.IsNull()) {
576
2.12k
        utxo = input.witness_utxo;
577
2.12k
    } else {
578
38
        return false;
579
38
    }
580
581
30.3k
    std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
582
30.3k
    if (!unsigned_tx) {
583
0
        return false;
584
0
    }
585
30.3k
    const CMutableTransaction& tx = *unsigned_tx;
586
30.3k
    if (txdata) {
587
30.3k
        return VerifyScript(input.final_script_sig, utxo.scriptPubKey, &input.final_script_witness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker{&tx, input_index, utxo.nValue, *txdata, MissingDataBehavior::FAIL});
588
30.3k
    } else {
589
6
        return VerifyScript(input.final_script_sig, utxo.scriptPubKey, &input.final_script_witness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker{&tx, input_index, utxo.nValue, MissingDataBehavior::FAIL});
590
6
    }
591
30.3k
}
592
593
0
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt) {
594
0
    size_t count = 0;
595
0
    for (const auto& input : psbt.inputs) {
596
0
        if (!PSBTInputSigned(input)) {
597
0
            count++;
598
0
        }
599
0
    }
600
601
0
    return count;
602
0
}
603
604
void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index)
605
1.14k
{
606
1.14k
    std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
607
1.14k
    if (!unsigned_tx) {
608
0
        return;
609
0
    }
610
1.14k
    const CTxOut& out = unsigned_tx->vout.at(index);
611
1.14k
    PSBTOutput& psbt_out = psbt.outputs.at(index);
612
613
    // Fill a SignatureData with output info
614
1.14k
    SignatureData sigdata;
615
1.14k
    psbt_out.FillSignatureData(sigdata);
616
617
    // Construct a would-be spend of this output, to update sigdata with.
618
    // Note that ProduceSignature is used to fill in metadata (not actual signatures),
619
    // so provider does not need to provide any private keys (it can be a HidingSigningProvider).
620
1.14k
    CMutableTransaction tx{};
621
1.14k
    tx.vin.emplace_back();
622
1.14k
    MutableTransactionSignatureCreator creator(tx, /*input_idx=*/0, out.nValue, {.sighash_type = SIGHASH_ALL});
623
1.14k
    ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
624
625
    // Put redeem_script, witness_script, key paths, into PSBTOutput.
626
1.14k
    psbt_out.FromSignatureData(sigdata);
627
1.14k
}
628
629
std::optional<PrecomputedTransactionData> PrecomputePSBTData(const PartiallySignedTransaction& psbt)
630
1.99k
{
631
1.99k
    std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
632
1.99k
    if (!unsigned_tx) {
633
0
        return std::nullopt;
634
0
    }
635
1.99k
    const CMutableTransaction& tx = *unsigned_tx;
636
1.99k
    bool have_all_spent_outputs = true;
637
1.99k
    std::vector<CTxOut> utxos;
638
5.83k
    for (const PSBTInput& input : psbt.inputs) {
639
5.83k
        if (!input.GetUTXO(utxos.emplace_back())) have_all_spent_outputs = false;
640
5.83k
    }
641
1.99k
    PrecomputedTransactionData txdata;
642
1.99k
    if (have_all_spent_outputs) {
643
1.96k
        txdata.Init(tx, std::move(utxos), true);
644
1.96k
    } else {
645
32
        txdata.Init(tx, {}, true);
646
32
    }
647
1.99k
    return txdata;
648
1.99k
}
649
650
util::Expected<void, PSBTError> SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options,  SignatureData* out_sigdata)
651
26.5k
{
652
26.5k
    PSBTInput& input = psbt.inputs.at(index);
653
26.5k
    std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
654
26.5k
    if (!unsigned_tx) {
655
0
        return util::Unexpected{PSBTError::INVALID_TX};
656
0
    }
657
26.5k
    const CMutableTransaction& tx = *unsigned_tx;
658
659
26.5k
    if (PSBTInputSignedAndVerified(psbt, index, txdata)) {
660
1.46k
        return {};
661
1.46k
    }
662
663
    // Fill SignatureData with input info
664
25.0k
    SignatureData sigdata;
665
25.0k
    input.FillSignatureData(sigdata);
666
667
    // Get UTXO
668
25.0k
    bool require_witness_sig = false;
669
25.0k
    CTxOut utxo;
670
671
25.0k
    if (input.non_witness_utxo) {
672
        // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
673
23.8k
        COutPoint prevout = input.GetOutPoint();
674
23.8k
        if (prevout.n >= input.non_witness_utxo->vout.size()) {
675
0
            return util::Unexpected{PSBTError::MISSING_INPUTS};
676
0
        }
677
23.8k
        if (input.non_witness_utxo->GetHash() != prevout.hash) {
678
0
            return util::Unexpected{PSBTError::MISSING_INPUTS};
679
0
        }
680
23.8k
        utxo = input.non_witness_utxo->vout[prevout.n];
681
23.8k
    } else if (!input.witness_utxo.IsNull()) {
682
1.20k
        utxo = input.witness_utxo;
683
        // When we're taking our information from a witness UTXO, we can't verify it is actually data from
684
        // the output being spent. This is safe in case a witness signature is produced (which includes this
685
        // information directly in the hash), but not for non-witness signatures. Remember that we require
686
        // a witness signature in this situation.
687
1.20k
        require_witness_sig = true;
688
1.20k
    } else {
689
10
        return util::Unexpected{PSBTError::MISSING_INPUTS};
690
10
    }
691
692
    // Get the sighash type
693
    // If both the field and the parameter are provided, they must match
694
    // If only the parameter is provided, use it and add it to the PSBT if it is other than SIGHASH_DEFAULT
695
    // for all input types, and not SIGHASH_ALL for non-taproot input types.
696
    // If neither are provided, use SIGHASH_DEFAULT if it is taproot, and SIGHASH_ALL for everything else.
697
25.0k
    int sighash{options.sighash_type.value_or(utxo.scriptPubKey.IsPayToTaproot() ? SIGHASH_DEFAULT : SIGHASH_ALL)};
698
699
    // For user safety, the desired sighash must be provided if the PSBT wants something other than the default set in the previous line.
700
25.0k
    if (input.sighash_type && input.sighash_type != sighash) {
701
14
        return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
702
14
    }
703
    // Set the PSBT sighash field when sighash is not DEFAULT or ALL
704
    // DEFAULT is allowed for non-taproot inputs since DEFAULT may be passed for them (e.g. the psbt being signed also has taproot inputs)
705
    // Note that signing already aliases DEFAULT to ALL for non-taproot inputs.
706
25.0k
    if (utxo.scriptPubKey.IsPayToTaproot() ? sighash != SIGHASH_DEFAULT :
707
25.0k
                                            (sighash != SIGHASH_DEFAULT && sighash != SIGHASH_ALL)) {
708
154
        input.sighash_type = sighash;
709
154
    }
710
711
    // Check all existing signatures use the sighash type
712
25.0k
    if (sighash == SIGHASH_DEFAULT) {
713
4.82k
        if (!input.m_tap_key_sig.empty() && input.m_tap_key_sig.size() != 64) {
714
0
            return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
715
0
        }
716
4.82k
        for (const auto& [_, sig] : input.m_tap_script_sigs) {
717
593
            if (sig.size() != 64) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
718
593
        }
719
20.1k
    } else {
720
20.1k
        if (!input.m_tap_key_sig.empty() && (input.m_tap_key_sig.size() != 65 || input.m_tap_key_sig.back() != sighash)) {
721
2
            return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
722
2
        }
723
20.1k
        for (const auto& [_, sig] : input.m_tap_script_sigs) {
724
0
            if (sig.size() != 65 || sig.back() != sighash) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
725
0
        }
726
20.1k
        for (const auto& [_, sig] : input.partial_sigs) {
727
466
            if (sig.second.back() != sighash) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
728
466
        }
729
20.1k
    }
730
731
25.0k
    sigdata.witness = false;
732
25.0k
    bool sig_complete;
733
25.0k
    if (txdata == nullptr) {
734
3
        sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
735
25.0k
    } else {
736
25.0k
        MutableTransactionSignatureCreator creator(tx, index, utxo.nValue, txdata, {.sighash_type = sighash});
737
25.0k
        sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
738
25.0k
    }
739
    // Verify that a witness signature was produced in case one was required.
740
25.0k
    if (require_witness_sig && !sigdata.witness) return util::Unexpected{PSBTError::INCOMPLETE};
741
742
    // If we are not finalizing, set sigdata.complete to false to not set the scriptWitness
743
24.9k
    if (!options.finalize && sigdata.complete) sigdata.complete = false;
744
745
24.9k
    input.FromSignatureData(sigdata);
746
747
    // If we have a witness signature, put a witness UTXO.
748
24.9k
    if (sigdata.witness) {
749
19.6k
        input.witness_utxo = utxo;
750
        // We can remove the non_witness_utxo if and only if there are no non-segwit or segwit v0
751
        // inputs in this transaction. Since this requires inspecting the entire transaction, this
752
        // is something for the caller to deal with (i.e. FillPSBT).
753
19.6k
    }
754
755
    // Fill in the missing info
756
24.9k
    if (out_sigdata) {
757
6
        out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
758
6
        out_sigdata->missing_sigs = sigdata.missing_sigs;
759
6
        out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
760
6
        out_sigdata->missing_witness_script = sigdata.missing_witness_script;
761
6
    }
762
763
24.9k
    if (!sig_complete) return util::Unexpected{PSBTError::INCOMPLETE};
764
2.47k
    return {};
765
24.9k
}
766
767
void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx)
768
1.37k
{
769
    // Figure out if any non_witness_utxos should be dropped
770
1.37k
    std::vector<unsigned int> to_drop;
771
2.22k
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
772
1.57k
        const auto& input = psbtx.inputs.at(i);
773
1.57k
        int wit_ver;
774
1.57k
        std::vector<unsigned char> wit_prog;
775
1.57k
        if (input.witness_utxo.IsNull() || !input.witness_utxo.scriptPubKey.IsWitnessProgram(wit_ver, wit_prog)) {
776
            // There's a non-segwit input, so we cannot drop any non_witness_utxos
777
251
            to_drop.clear();
778
251
            break;
779
251
        }
780
1.32k
        if (wit_ver == 0) {
781
            // Segwit v0, so we cannot drop any non_witness_utxos
782
466
            to_drop.clear();
783
466
            break;
784
466
        }
785
        // non_witness_utxos cannot be dropped if the sighash type includes SIGHASH_ANYONECANPAY
786
        // Since callers should have called SignPSBTInput which updates the sighash type in the PSBT, we only
787
        // need to look at that field. If it is not present, then we can assume SIGHASH_DEFAULT or SIGHASH_ALL.
788
861
        if (input.sighash_type != std::nullopt && (*input.sighash_type & 0x80) == SIGHASH_ANYONECANPAY) {
789
12
            to_drop.clear();
790
12
            break;
791
12
        }
792
793
849
        if (input.non_witness_utxo) {
794
556
            to_drop.push_back(i);
795
556
        }
796
849
    }
797
798
    // Drop the non_witness_utxos that we can drop
799
1.37k
    for (unsigned int i : to_drop) {
800
556
        psbtx.inputs.at(i).non_witness_utxo = nullptr;
801
556
    }
802
1.37k
}
803
804
bool FinalizePSBT(PartiallySignedTransaction& psbtx)
805
585
{
806
    // Finalize input signatures -- in case we have partial signatures that add up to a complete
807
    //   signature, but have not combined them yet (e.g. because the combiner that created this
808
    //   PartiallySignedTransaction did not understand them), this will combine them into a final
809
    //   script.
810
585
    bool complete = true;
811
585
    std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbtx);
812
585
    if (!txdata_res) {
813
0
        return false;
814
0
    }
815
585
    const PrecomputedTransactionData& txdata = *txdata_res;
816
2.44k
    for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
817
1.85k
        PSBTInput& input = psbtx.inputs.at(i);
818
1.85k
        const auto sign_result = SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, {.sighash_type = input.sighash_type, .finalize = true}, /*out_sigdata=*/nullptr);
819
1.85k
        complete &= sign_result.has_value();
820
1.85k
    }
821
822
585
    return complete;
823
585
}
824
825
bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result)
826
582
{
827
    // It's not safe to extract a PSBT that isn't finalized, and there's no easy way to check
828
    //   whether a PSBT is finalized without finalizing it, so we just do this.
829
582
    if (!FinalizePSBT(psbtx)) {
830
41
        return false;
831
41
    }
832
833
541
    std::optional<CMutableTransaction> unsigned_tx = psbtx.GetUnsignedTx();
834
541
    if (!unsigned_tx) {
835
0
        return false;
836
0
    }
837
541
    result = *unsigned_tx;
838
2.30k
    for (unsigned int i = 0; i < result.vin.size(); ++i) {
839
1.76k
        result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
840
1.76k
        result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
841
1.76k
    }
842
541
    return true;
843
541
}
844
845
std::optional<PartiallySignedTransaction> CombinePSBTs(const std::vector<PartiallySignedTransaction>& psbtxs)
846
108
{
847
108
    PartiallySignedTransaction out = psbtxs[0]; // Copy the first one
848
849
    // Merge
850
309
    for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
851
202
        if (!out.Merge(*it)) {
852
1
            return std::nullopt;
853
1
        }
854
202
    }
855
107
    return out;
856
108
}
857
858
20
std::string PSBTRoleName(PSBTRole role) {
859
20
    switch (role) {
860
3
    case PSBTRole::CREATOR: return "creator";
861
9
    case PSBTRole::UPDATER: return "updater";
862
2
    case PSBTRole::SIGNER: return "signer";
863
4
    case PSBTRole::FINALIZER: return "finalizer";
864
2
    case PSBTRole::EXTRACTOR: return "extractor";
865
20
    } // no default case, so the compiler can warn about missing cases
866
20
    assert(false);
867
0
}
868
869
util::Result<PartiallySignedTransaction> DecodeBase64PSBT(const std::string& base64_tx)
870
1.82k
{
871
1.82k
    auto tx_data = DecodeBase64(base64_tx);
872
1.82k
    if (!tx_data) {
873
4
        return util::Error{Untranslated("invalid base64")};
874
4
    }
875
1.81k
    return DecodeRawPSBT(MakeByteSpan(*tx_data));
876
1.82k
}
877
878
util::Result<PartiallySignedTransaction> DecodeRawPSBT(std::span<const std::byte> tx_data)
879
1.81k
{
880
1.81k
    SpanReader ss_data{tx_data};
881
1.81k
    try {
882
1.81k
        PartiallySignedTransaction psbt(deserialize, ss_data);
883
1.81k
        if (!ss_data.empty()) {
884
0
            return util::Error{Untranslated("extra data after PSBT")};
885
0
        }
886
1.81k
        return psbt;
887
1.81k
    } catch (const std::exception& e) {
888
87
        return util::Error{Untranslated(e.what())};
889
87
    }
890
1.81k
}
891
892
uint32_t PartiallySignedTransaction::GetVersion() const
893
75.9k
{
894
75.9k
    if (m_version != std::nullopt) {
895
74.7k
        return *m_version;
896
74.7k
    }
897
1.24k
    return 0;
898
75.9k
}