Coverage Report

Created: 2026-05-30 09:47

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