Coverage Report

Created: 2026-09-14 20:36

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