Coverage Report

Created: 2026-05-06 07:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/psbt.h
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
#ifndef BITCOIN_PSBT_H
6
#define BITCOIN_PSBT_H
7
8
#include <common/types.h>
9
#include <node/transaction.h>
10
#include <policy/feerate.h>
11
#include <primitives/transaction.h>
12
#include <pubkey.h>
13
#include <script/keyorigin.h>
14
#include <script/sign.h>
15
#include <script/signingprovider.h>
16
#include <span.h>
17
#include <streams.h>
18
#include <uint256.h>
19
#include <util/result.h>
20
21
#include <optional>
22
#include <bitset>
23
24
namespace node {
25
enum class TransactionError;
26
} // namespace node
27
28
using common::PSBTError;
29
30
// Magic bytes
31
static constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff};
32
33
// Global types
34
static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00;
35
static constexpr uint8_t PSBT_GLOBAL_XPUB = 0x01;
36
static constexpr uint8_t PSBT_GLOBAL_TX_VERSION = 0x02;
37
static constexpr uint8_t PSBT_GLOBAL_FALLBACK_LOCKTIME = 0x03;
38
static constexpr uint8_t PSBT_GLOBAL_INPUT_COUNT = 0x04;
39
static constexpr uint8_t PSBT_GLOBAL_OUTPUT_COUNT = 0x05;
40
static constexpr uint8_t PSBT_GLOBAL_TX_MODIFIABLE = 0x06;
41
static constexpr uint8_t PSBT_GLOBAL_VERSION = 0xFB;
42
static constexpr uint8_t PSBT_GLOBAL_PROPRIETARY = 0xFC;
43
44
// Input types
45
static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00;
46
static constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01;
47
static constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02;
48
static constexpr uint8_t PSBT_IN_SIGHASH = 0x03;
49
static constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04;
50
static constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05;
51
static constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06;
52
static constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07;
53
static constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08;
54
static constexpr uint8_t PSBT_IN_RIPEMD160 = 0x0A;
55
static constexpr uint8_t PSBT_IN_SHA256 = 0x0B;
56
static constexpr uint8_t PSBT_IN_HASH160 = 0x0C;
57
static constexpr uint8_t PSBT_IN_HASH256 = 0x0D;
58
static constexpr uint8_t PSBT_IN_PREVIOUS_TXID = 0x0e;
59
static constexpr uint8_t PSBT_IN_OUTPUT_INDEX = 0x0f;
60
static constexpr uint8_t PSBT_IN_SEQUENCE = 0x10;
61
static constexpr uint8_t PSBT_IN_REQUIRED_TIME_LOCKTIME = 0x11;
62
static constexpr uint8_t PSBT_IN_REQUIRED_HEIGHT_LOCKTIME = 0x12;
63
static constexpr uint8_t PSBT_IN_TAP_KEY_SIG = 0x13;
64
static constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG = 0x14;
65
static constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT = 0x15;
66
static constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
67
static constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY = 0x17;
68
static constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT = 0x18;
69
static constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS = 0x1a;
70
static constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE = 0x1b;
71
static constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG = 0x1c;
72
static constexpr uint8_t PSBT_IN_PROPRIETARY = 0xFC;
73
74
// Output types
75
static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00;
76
static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01;
77
static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02;
78
static constexpr uint8_t PSBT_OUT_AMOUNT = 0x03;
79
static constexpr uint8_t PSBT_OUT_SCRIPT = 0x04;
80
static constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
81
static constexpr uint8_t PSBT_OUT_TAP_TREE = 0x06;
82
static constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
83
static constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS = 0x08;
84
static constexpr uint8_t PSBT_OUT_PROPRIETARY = 0xFC;
85
86
// The separator is 0x00. Reading this in means that the unserializer can interpret it
87
// as a 0 length key which indicates that this is the separator. The separator has no value.
88
static constexpr uint8_t PSBT_SEPARATOR = 0x00;
89
90
// BIP 174 does not specify a maximum file size, but we set a limit anyway
91
// to prevent reading a stream indefinitely and running out of memory.
92
const std::streamsize MAX_FILE_SIZE_PSBT = 100000000; // 100 MB
93
94
// PSBT version number
95
static constexpr uint32_t PSBT_HIGHEST_VERSION = 2;
96
97
/** A structure for PSBT proprietary types */
98
struct PSBTProprietary
99
{
100
    uint64_t subtype;
101
    std::vector<unsigned char> identifier;
102
    std::vector<unsigned char> key;
103
    std::vector<unsigned char> value;
104
105
3
    bool operator<(const PSBTProprietary &b) const {
106
3
        return key < b.key;
107
3
    }
108
0
    bool operator==(const PSBTProprietary &b) const {
109
0
        return key == b.key;
110
0
    }
111
};
112
113
// Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
114
// The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
115
template<typename Stream, typename... X>
116
void SerializeToVector(Stream& s, const X&... args)
117
34.9k
{
118
34.9k
    SizeComputer sizecomp;
119
34.9k
    SerializeMany(sizecomp, args...);
120
34.9k
    WriteCompactSize(s, sizecomp.size());
121
34.9k
    SerializeMany(s, args...);
122
34.9k
}
void SerializeToVector<DataStream, CompactSizeWriter>(DataStream&, CompactSizeWriter const&)
Line
Count
Source
117
15.5k
{
118
15.5k
    SizeComputer sizecomp;
119
15.5k
    SerializeMany(sizecomp, args...);
120
15.5k
    WriteCompactSize(s, sizecomp.size());
121
15.5k
    SerializeMany(s, args...);
122
15.5k
}
void SerializeToVector<DataStream, ParamsWrapper<TransactionSerParams, CMutableTransaction>>(DataStream&, ParamsWrapper<TransactionSerParams, CMutableTransaction> const&)
Line
Count
Source
117
36
{
118
36
    SizeComputer sizecomp;
119
36
    SerializeMany(sizecomp, args...);
120
36
    WriteCompactSize(s, sizecomp.size());
121
36
    SerializeMany(s, args...);
122
36
}
Unexecuted instantiation: void SerializeToVector<DataStream, unsigned char, unsigned char [78]>(DataStream&, unsigned char const&, unsigned char const (&) [78])
void SerializeToVector<DataStream, unsigned int>(DataStream&, unsigned int const&)
Line
Count
Source
117
5.01k
{
118
5.01k
    SizeComputer sizecomp;
119
5.01k
    SerializeMany(sizecomp, args...);
120
5.01k
    WriteCompactSize(s, sizecomp.size());
121
5.01k
    SerializeMany(s, args...);
122
5.01k
}
void SerializeToVector<DataStream, unsigned char>(DataStream&, unsigned char const&)
Line
Count
Source
117
1.81k
{
118
1.81k
    SizeComputer sizecomp;
119
1.81k
    SerializeMany(sizecomp, args...);
120
1.81k
    WriteCompactSize(s, sizecomp.size());
121
1.81k
    SerializeMany(s, args...);
122
1.81k
}
void SerializeToVector<DataStream, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const> const>>(DataStream&, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const> const> const&)
Line
Count
Source
117
550
{
118
550
    SizeComputer sizecomp;
119
550
    SerializeMany(sizecomp, args...);
120
550
    WriteCompactSize(s, sizecomp.size());
121
550
    SerializeMany(s, args...);
122
550
}
void SerializeToVector<DataStream, CTxOut>(DataStream&, CTxOut const&)
Line
Count
Source
117
1.07k
{
118
1.07k
    SizeComputer sizecomp;
119
1.07k
    SerializeMany(sizecomp, args...);
120
1.07k
    WriteCompactSize(s, sizecomp.size());
121
1.07k
    SerializeMany(s, args...);
122
1.07k
}
void SerializeToVector<DataStream, CompactSizeWriter, std::span<unsigned char const, 18446744073709551615ul>>(DataStream&, CompactSizeWriter const&, std::span<unsigned char const, 18446744073709551615ul> const&)
Line
Count
Source
117
1.42k
{
118
1.42k
    SizeComputer sizecomp;
119
1.42k
    SerializeMany(sizecomp, args...);
120
1.42k
    WriteCompactSize(s, sizecomp.size());
121
1.42k
    SerializeMany(s, args...);
122
1.42k
}
void SerializeToVector<DataStream, int>(DataStream&, int const&)
Line
Count
Source
117
28
{
118
28
    SizeComputer sizecomp;
119
28
    SerializeMany(sizecomp, args...);
120
28
    WriteCompactSize(s, sizecomp.size());
121
28
    SerializeMany(s, args...);
122
28
}
void SerializeToVector<DataStream, unsigned char, XOnlyPubKey, uint256>(DataStream&, unsigned char const&, XOnlyPubKey const&, uint256 const&)
Line
Count
Source
117
242
{
118
242
    SizeComputer sizecomp;
119
242
    SerializeMany(sizecomp, args...);
120
242
    WriteCompactSize(s, sizecomp.size());
121
242
    SerializeMany(s, args...);
122
242
}
void SerializeToVector<DataStream, unsigned char, std::span<unsigned char const, 18446744073709551615ul>>(DataStream&, unsigned char const&, std::span<unsigned char const, 18446744073709551615ul> const&)
Line
Count
Source
117
855
{
118
855
    SizeComputer sizecomp;
119
855
    SerializeMany(sizecomp, args...);
120
855
    WriteCompactSize(s, sizecomp.size());
121
855
    SerializeMany(s, args...);
122
855
}
void SerializeToVector<DataStream, unsigned char, XOnlyPubKey>(DataStream&, unsigned char const&, XOnlyPubKey const&)
Line
Count
Source
117
3.76k
{
118
3.76k
    SizeComputer sizecomp;
119
3.76k
    SerializeMany(sizecomp, args...);
120
3.76k
    WriteCompactSize(s, sizecomp.size());
121
3.76k
    SerializeMany(s, args...);
122
3.76k
}
void SerializeToVector<DataStream, uint256>(DataStream&, uint256 const&)
Line
Count
Source
117
586
{
118
586
    SizeComputer sizecomp;
119
586
    SerializeMany(sizecomp, args...);
120
586
    WriteCompactSize(s, sizecomp.size());
121
586
    SerializeMany(s, args...);
122
586
}
void SerializeToVector<DataStream, CompactSizeWriter, std::span<unsigned char const, 18446744073709551615ul>, std::span<unsigned char const, 18446744073709551615ul>>(DataStream&, CompactSizeWriter const&, std::span<unsigned char const, 18446744073709551615ul> const&, std::span<unsigned char const, 18446744073709551615ul> const&)
Line
Count
Source
117
288
{
118
288
    SizeComputer sizecomp;
119
288
    SerializeMany(sizecomp, args...);
120
288
    WriteCompactSize(s, sizecomp.size());
121
288
    SerializeMany(s, args...);
122
288
}
void SerializeToVector<DataStream, CompactSizeWriter, std::span<unsigned char const, 18446744073709551615ul>, std::span<unsigned char const, 18446744073709551615ul>, uint256>(DataStream&, CompactSizeWriter const&, std::span<unsigned char const, 18446744073709551615ul> const&, std::span<unsigned char const, 18446744073709551615ul> const&, uint256 const&)
Line
Count
Source
117
333
{
118
333
    SizeComputer sizecomp;
119
333
    SerializeMany(sizecomp, args...);
120
333
    WriteCompactSize(s, sizecomp.size());
121
333
    SerializeMany(s, args...);
122
333
}
void SerializeToVector<DataStream, std::vector<std::vector<unsigned char, std::allocator<unsigned char>>, std::allocator<std::vector<unsigned char, std::allocator<unsigned char>>>>>(DataStream&, std::vector<std::vector<unsigned char, std::allocator<unsigned char>>, std::allocator<std::vector<unsigned char, std::allocator<unsigned char>>>> const&)
Line
Count
Source
117
233
{
118
233
    SizeComputer sizecomp;
119
233
    SerializeMany(sizecomp, args...);
120
233
    WriteCompactSize(s, sizecomp.size());
121
233
    SerializeMany(s, args...);
122
233
}
void SerializeToVector<DataStream, transaction_identifier<false>>(DataStream&, transaction_identifier<false> const&)
Line
Count
Source
117
1.22k
{
118
1.22k
    SizeComputer sizecomp;
119
1.22k
    SerializeMany(sizecomp, args...);
120
1.22k
    WriteCompactSize(s, sizecomp.size());
121
1.22k
    SerializeMany(s, args...);
122
1.22k
}
void SerializeToVector<DataStream, long>(DataStream&, long const&)
Line
Count
Source
117
1.87k
{
118
1.87k
    SizeComputer sizecomp;
119
1.87k
    SerializeMany(sizecomp, args...);
120
1.87k
    WriteCompactSize(s, sizecomp.size());
121
1.87k
    SerializeMany(s, args...);
122
1.87k
}
123
124
// Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
125
template<typename Stream, typename... X>
126
void UnserializeFromVector(Stream& s, X&&... args)
127
17.5k
{
128
17.5k
    size_t expected_size = ReadCompactSize(s);
129
17.5k
    size_t remaining_before = s.size();
130
17.5k
    UnserializeMany(s, args...);
131
17.5k
    size_t remaining_after = s.size();
132
17.5k
    if (remaining_after + expected_size != remaining_before) {
133
3
        throw std::ios_base::failure("Size of value was not the stated size");
134
3
    }
135
17.5k
}
void UnserializeFromVector<DataStream, ParamsWrapper<TransactionSerParams, CMutableTransaction>>(DataStream&, ParamsWrapper<TransactionSerParams, CMutableTransaction>&&)
Line
Count
Source
127
1
{
128
1
    size_t expected_size = ReadCompactSize(s);
129
1
    size_t remaining_before = s.size();
130
1
    UnserializeMany(s, args...);
131
1
    size_t remaining_after = s.size();
132
1
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
1
}
Unexecuted instantiation: void UnserializeFromVector<DataStream, unsigned int&>(DataStream&, unsigned int&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, CompactSizeReader&>(DataStream&, CompactSizeReader&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, unsigned char&>(DataStream&, unsigned char&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const>>>(DataStream&, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const>>&&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, CTxOut&>(DataStream&, CTxOut&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, int&>(DataStream&, int&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, std::vector<std::vector<unsigned char, std::allocator<unsigned char>>, std::allocator<std::vector<unsigned char, std::allocator<unsigned char>>>>&>(DataStream&, std::vector<std::vector<unsigned char, std::allocator<unsigned char>>, std::allocator<std::vector<unsigned char, std::allocator<unsigned char>>>>&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, transaction_identifier<false>&>(DataStream&, transaction_identifier<false>&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, XOnlyPubKey&>(DataStream&, XOnlyPubKey&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, uint256&>(DataStream&, uint256&)
Unexecuted instantiation: void UnserializeFromVector<DataStream, long&>(DataStream&, long&)
void UnserializeFromVector<SpanReader, ParamsWrapper<TransactionSerParams, CMutableTransaction>>(SpanReader&, ParamsWrapper<TransactionSerParams, CMutableTransaction>&&)
Line
Count
Source
127
161
{
128
161
    size_t expected_size = ReadCompactSize(s);
129
161
    size_t remaining_before = s.size();
130
161
    UnserializeMany(s, args...);
131
161
    size_t remaining_after = s.size();
132
161
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
161
}
void UnserializeFromVector<SpanReader, unsigned int&>(SpanReader&, unsigned int&)
Line
Count
Source
127
6.64k
{
128
6.64k
    size_t expected_size = ReadCompactSize(s);
129
6.64k
    size_t remaining_before = s.size();
130
6.64k
    UnserializeMany(s, args...);
131
6.64k
    size_t remaining_after = s.size();
132
6.64k
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
6.64k
}
void UnserializeFromVector<SpanReader, CompactSizeReader&>(SpanReader&, CompactSizeReader&)
Line
Count
Source
127
2.47k
{
128
2.47k
    size_t expected_size = ReadCompactSize(s);
129
2.47k
    size_t remaining_before = s.size();
130
2.47k
    UnserializeMany(s, args...);
131
2.47k
    size_t remaining_after = s.size();
132
2.47k
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
2.47k
}
void UnserializeFromVector<SpanReader, unsigned char&>(SpanReader&, unsigned char&)
Line
Count
Source
127
13
{
128
13
    size_t expected_size = ReadCompactSize(s);
129
13
    size_t remaining_before = s.size();
130
13
    UnserializeMany(s, args...);
131
13
    size_t remaining_after = s.size();
132
13
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
13
}
void UnserializeFromVector<SpanReader, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const>>>(SpanReader&, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const>>&&)
Line
Count
Source
127
421
{
128
421
    size_t expected_size = ReadCompactSize(s);
129
421
    size_t remaining_before = s.size();
130
421
    UnserializeMany(s, args...);
131
421
    size_t remaining_after = s.size();
132
421
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
421
}
void UnserializeFromVector<SpanReader, CTxOut&>(SpanReader&, CTxOut&)
Line
Count
Source
127
1.39k
{
128
1.39k
    size_t expected_size = ReadCompactSize(s);
129
1.39k
    size_t remaining_before = s.size();
130
1.39k
    UnserializeMany(s, args...);
131
1.39k
    size_t remaining_after = s.size();
132
1.39k
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
1.39k
}
void UnserializeFromVector<SpanReader, int&>(SpanReader&, int&)
Line
Count
Source
127
62
{
128
62
    size_t expected_size = ReadCompactSize(s);
129
62
    size_t remaining_before = s.size();
130
62
    UnserializeMany(s, args...);
131
62
    size_t remaining_after = s.size();
132
62
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
62
}
void UnserializeFromVector<SpanReader, std::vector<std::vector<unsigned char, std::allocator<unsigned char>>, std::allocator<std::vector<unsigned char, std::allocator<unsigned char>>>>&>(SpanReader&, std::vector<std::vector<unsigned char, std::allocator<unsigned char>>, std::allocator<std::vector<unsigned char, std::allocator<unsigned char>>>>&)
Line
Count
Source
127
70
{
128
70
    size_t expected_size = ReadCompactSize(s);
129
70
    size_t remaining_before = s.size();
130
70
    UnserializeMany(s, args...);
131
70
    size_t remaining_after = s.size();
132
70
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
70
}
void UnserializeFromVector<SpanReader, transaction_identifier<false>&>(SpanReader&, transaction_identifier<false>&)
Line
Count
Source
127
1.48k
{
128
1.48k
    size_t expected_size = ReadCompactSize(s);
129
1.48k
    size_t remaining_before = s.size();
130
1.48k
    UnserializeMany(s, args...);
131
1.48k
    size_t remaining_after = s.size();
132
1.48k
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
1.48k
}
void UnserializeFromVector<SpanReader, XOnlyPubKey&>(SpanReader&, XOnlyPubKey&)
Line
Count
Source
127
1.60k
{
128
1.60k
    size_t expected_size = ReadCompactSize(s);
129
1.60k
    size_t remaining_before = s.size();
130
1.60k
    UnserializeMany(s, args...);
131
1.60k
    size_t remaining_after = s.size();
132
1.60k
    if (remaining_after + expected_size != remaining_before) {
133
2
        throw std::ios_base::failure("Size of value was not the stated size");
134
2
    }
135
1.60k
}
void UnserializeFromVector<SpanReader, uint256&>(SpanReader&, uint256&)
Line
Count
Source
127
1.02k
{
128
1.02k
    size_t expected_size = ReadCompactSize(s);
129
1.02k
    size_t remaining_before = s.size();
130
1.02k
    UnserializeMany(s, args...);
131
1.02k
    size_t remaining_after = s.size();
132
1.02k
    if (remaining_after + expected_size != remaining_before) {
133
1
        throw std::ios_base::failure("Size of value was not the stated size");
134
1
    }
135
1.02k
}
void UnserializeFromVector<SpanReader, long&>(SpanReader&, long&)
Line
Count
Source
127
2.24k
{
128
2.24k
    size_t expected_size = ReadCompactSize(s);
129
2.24k
    size_t remaining_before = s.size();
130
2.24k
    UnserializeMany(s, args...);
131
2.24k
    size_t remaining_after = s.size();
132
2.24k
    if (remaining_after + expected_size != remaining_before) {
133
0
        throw std::ios_base::failure("Size of value was not the stated size");
134
0
    }
135
2.24k
}
136
137
// Deserialize bytes of given length from the stream as a KeyOriginInfo
138
template<typename Stream>
139
KeyOriginInfo DeserializeKeyOrigin(Stream& s, uint64_t length)
140
7.47k
{
141
    // Read in key path
142
7.47k
    if (length % 4 || length == 0) {
143
0
        throw std::ios_base::failure("Invalid length for HD key path");
144
0
    }
145
146
7.47k
    KeyOriginInfo hd_keypath;
147
7.47k
    s >> hd_keypath.fingerprint;
148
22.6k
    for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
149
15.2k
        uint32_t index;
150
15.2k
        s >> index;
151
15.2k
        hd_keypath.path.push_back(index);
152
15.2k
    }
153
7.47k
    return hd_keypath;
154
7.47k
}
Unexecuted instantiation: KeyOriginInfo DeserializeKeyOrigin<DataStream>(DataStream&, unsigned long)
KeyOriginInfo DeserializeKeyOrigin<SpanReader>(SpanReader&, unsigned long)
Line
Count
Source
140
7.47k
{
141
    // Read in key path
142
7.47k
    if (length % 4 || length == 0) {
143
0
        throw std::ios_base::failure("Invalid length for HD key path");
144
0
    }
145
146
7.47k
    KeyOriginInfo hd_keypath;
147
7.47k
    s >> hd_keypath.fingerprint;
148
22.6k
    for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
149
15.2k
        uint32_t index;
150
15.2k
        s >> index;
151
15.2k
        hd_keypath.path.push_back(index);
152
15.2k
    }
153
7.47k
    return hd_keypath;
154
7.47k
}
155
156
// Deserialize a length prefixed KeyOriginInfo from a stream
157
template<typename Stream>
158
void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
159
850
{
160
850
    hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
161
850
}
Unexecuted instantiation: void DeserializeHDKeypath<DataStream>(DataStream&, KeyOriginInfo&)
void DeserializeHDKeypath<SpanReader>(SpanReader&, KeyOriginInfo&)
Line
Count
Source
159
850
{
160
850
    hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
161
850
}
162
163
// Deserialize HD keypaths into a map
164
template<typename Stream>
165
void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
166
849
{
167
    // Make sure that the key is the size of pubkey + 1
168
849
    if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
169
2
        throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
170
2
    }
171
    // Read in the pubkey from key
172
847
    CPubKey pubkey(key.begin() + 1, key.end());
173
847
    if (!pubkey.IsFullyValid()) {
174
0
       throw std::ios_base::failure("Invalid pubkey");
175
0
    }
176
177
847
    KeyOriginInfo keypath;
178
847
    DeserializeHDKeypath(s, keypath);
179
180
    // Add to map
181
847
    hd_keypaths.emplace(pubkey, std::move(keypath));
182
847
}
Unexecuted instantiation: void DeserializeHDKeypaths<DataStream>(DataStream&, std::vector<unsigned char, std::allocator<unsigned char>> const&, std::map<CPubKey, KeyOriginInfo, std::less<CPubKey>, std::allocator<std::pair<CPubKey const, KeyOriginInfo>>>&)
void DeserializeHDKeypaths<SpanReader>(SpanReader&, std::vector<unsigned char, std::allocator<unsigned char>> const&, std::map<CPubKey, KeyOriginInfo, std::less<CPubKey>, std::allocator<std::pair<CPubKey const, KeyOriginInfo>>>&)
Line
Count
Source
166
849
{
167
    // Make sure that the key is the size of pubkey + 1
168
849
    if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
169
2
        throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
170
2
    }
171
    // Read in the pubkey from key
172
847
    CPubKey pubkey(key.begin() + 1, key.end());
173
847
    if (!pubkey.IsFullyValid()) {
174
0
       throw std::ios_base::failure("Invalid pubkey");
175
0
    }
176
177
847
    KeyOriginInfo keypath;
178
847
    DeserializeHDKeypath(s, keypath);
179
180
    // Add to map
181
847
    hd_keypaths.emplace(pubkey, std::move(keypath));
182
847
}
183
184
// Serialize a KeyOriginInfo to a stream
185
template<typename Stream>
186
void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
187
4.56k
{
188
4.56k
    s << hd_keypath.fingerprint;
189
9.94k
    for (const auto& path : hd_keypath.path) {
190
9.94k
        s << path;
191
9.94k
    }
192
4.56k
}
void SerializeKeyOrigin<DataStream>(DataStream&, KeyOriginInfo)
Line
Count
Source
187
793
{
188
793
    s << hd_keypath.fingerprint;
189
2.89k
    for (const auto& path : hd_keypath.path) {
190
2.89k
        s << path;
191
2.89k
    }
192
793
}
void SerializeKeyOrigin<VectorWriter>(VectorWriter&, KeyOriginInfo)
Line
Count
Source
187
3.76k
{
188
3.76k
    s << hd_keypath.fingerprint;
189
7.04k
    for (const auto& path : hd_keypath.path) {
190
7.04k
        s << path;
191
7.04k
    }
192
3.76k
}
193
194
// Serialize a length prefixed KeyOriginInfo to a stream
195
template<typename Stream>
196
void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
197
793
{
198
793
    WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
199
793
    SerializeKeyOrigin(s, hd_keypath);
200
793
}
201
202
// Serialize HD keypaths to a stream from a map
203
template<typename Stream>
204
void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
205
2.95k
{
206
2.95k
    for (const auto& keypath_pair : hd_keypaths) {
207
793
        if (!keypath_pair.first.IsValid()) {
208
0
            throw std::ios_base::failure("Invalid CPubKey being serialized");
209
0
        }
210
793
        SerializeToVector(s, type, std::span{keypath_pair.first});
211
793
        SerializeHDKeypath(s, keypath_pair.second);
212
793
    }
213
2.95k
}
214
215
// Deserialize a PSBT_{IN/OUT}_MUSIG2_PARTICIPANT_PUBKEYS field
216
template<typename Stream>
217
void DeserializeMuSig2ParticipantPubkeys(Stream& s, SpanReader& skey, std::map<CPubKey, std::vector<CPubKey>>& out, std::string context)
218
981
{
219
981
    std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
220
981
    skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
221
981
    CPubKey agg_pubkey(agg_pubkey_bytes);
222
981
    if (!agg_pubkey.IsFullyValid()) {
223
3
        throw std::ios_base::failure(context + " musig2 aggregate pubkey is invalid");
224
3
    }
225
226
978
    std::vector<CPubKey> participants;
227
978
    std::vector<unsigned char> val;
228
978
    s >> val;
229
978
    SpanReader s_val{val};
230
3.69k
    while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
231
2.72k
        std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
232
2.72k
        s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
233
2.72k
        CPubKey participant(part_pubkey_bytes);
234
2.72k
        if (!participant.IsFullyValid()) {
235
2
            throw std::ios_base::failure(context + " musig2 participant pubkey is invalid");
236
2
        }
237
2.71k
        participants.push_back(participant);
238
2.71k
    }
239
976
    if (!s_val.empty()) {
240
1
        throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
241
1
    }
242
243
975
    out.emplace(agg_pubkey, participants);
244
975
}
Unexecuted instantiation: void DeserializeMuSig2ParticipantPubkeys<DataStream>(DataStream&, SpanReader&, std::map<CPubKey, std::vector<CPubKey, std::allocator<CPubKey>>, std::less<CPubKey>, std::allocator<std::pair<CPubKey const, std::vector<CPubKey, std::allocator<CPubKey>>>>>&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)
void DeserializeMuSig2ParticipantPubkeys<SpanReader>(SpanReader&, SpanReader&, std::map<CPubKey, std::vector<CPubKey, std::allocator<CPubKey>>, std::less<CPubKey>, std::allocator<std::pair<CPubKey const, std::vector<CPubKey, std::allocator<CPubKey>>>>>&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>>)
Line
Count
Source
218
981
{
219
981
    std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
220
981
    skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
221
981
    CPubKey agg_pubkey(agg_pubkey_bytes);
222
981
    if (!agg_pubkey.IsFullyValid()) {
223
3
        throw std::ios_base::failure(context + " musig2 aggregate pubkey is invalid");
224
3
    }
225
226
978
    std::vector<CPubKey> participants;
227
978
    std::vector<unsigned char> val;
228
978
    s >> val;
229
978
    SpanReader s_val{val};
230
3.69k
    while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
231
2.72k
        std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
232
2.72k
        s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
233
2.72k
        CPubKey participant(part_pubkey_bytes);
234
2.72k
        if (!participant.IsFullyValid()) {
235
2
            throw std::ios_base::failure(context + " musig2 participant pubkey is invalid");
236
2
        }
237
2.71k
        participants.push_back(participant);
238
2.71k
    }
239
976
    if (!s_val.empty()) {
240
1
        throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
241
1
    }
242
243
975
    out.emplace(agg_pubkey, participants);
244
975
}
245
246
// Deserialize the MuSig2 participant identifiers from PSBT_MUSIG2_{PUBNONCE/PARTIAL_SIG} fields
247
// Both fields contain the same data after the type byte - aggregate pubkey | participant pubkey | leaf script hash
248
template<typename Stream>
249
void DeserializeMuSig2ParticipantDataIdentifier(Stream& skey, CPubKey& agg_pub, CPubKey& part_pub, uint256& leaf_hash)
250
1.20k
{
251
1.20k
    leaf_hash.SetNull();
252
253
1.20k
    std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
254
1.20k
    std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
255
256
1.20k
    skey >> std::as_writable_bytes(std::span{part_pubkey_bytes}) >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
257
1.20k
    agg_pub.Set(agg_pubkey_bytes.begin(), agg_pubkey_bytes.end());
258
1.20k
    if (!agg_pub.IsFullyValid()) {
259
2
        throw std::ios_base::failure("musig2 aggregate pubkey is invalid");
260
2
    }
261
262
1.20k
    part_pub.Set(part_pubkey_bytes.begin(), part_pubkey_bytes.end());
263
1.20k
    if (!part_pub.IsFullyValid()) {
264
2
        throw std::ios_base::failure("musig2 participant pubkey is invalid");
265
2
    }
266
267
1.20k
    if (!skey.empty()) {
268
647
        skey >> leaf_hash;
269
647
    }
270
1.20k
}
271
272
28.5k
static inline void ExpectedKeySize(const std::string& key_name, const std::vector<unsigned char>& key, uint64_t expected_size) {
273
28.5k
    if (key.size() != expected_size) {
274
15
        throw std::ios_base::failure(tfm::format("Size of key was not %d for the type %s", expected_size, key_name));
275
15
    }
276
28.5k
}
Unexecuted instantiation: psbt_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: wallet_test_fixture.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: db_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: coinselector_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: coinselection_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: feebumper_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: group_outputs_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: ismine_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
psbt_wallet_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Line
Count
Source
272
1
static inline void ExpectedKeySize(const std::string& key_name, const std::vector<unsigned char>& key, uint64_t expected_size) {
273
1
    if (key.size() != expected_size) {
274
0
        throw std::ios_base::failure(tfm::format("Size of key was not %d for the type %s", expected_size, key_name));
275
0
    }
276
1
}
Unexecuted instantiation: scriptpubkeyman_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: spend_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: wallet_rpc_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: wallet_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: wallet_transaction_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: walletdb_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: walletload_tests.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: util.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: rawtransaction.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: init.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
psbt.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Line
Count
Source
272
28.5k
static inline void ExpectedKeySize(const std::string& key_name, const std::vector<unsigned char>& key, uint64_t expected_size) {
273
28.5k
    if (key.size() != expected_size) {
274
15
        throw std::ios_base::failure(tfm::format("Size of key was not %d for the type %s", expected_size, key_name));
275
15
    }
276
28.5k
}
Unexecuted instantiation: interfaces.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: load.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: receive.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: wallet.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: scriptpubkeyman.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: spend.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: walletdb.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: external_signer_scriptpubkeyman.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: feebumper.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: fees.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: addresses.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: backup.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: coins.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: encrypt.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: signmessage.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: transactions.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
Unexecuted instantiation: external_signer.cpp:ExpectedKeySize(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char>> const&, std::vector<unsigned char, std::allocator<unsigned char>> const&, unsigned long)
277
278
/** A structure for PSBTs which contain per-input information */
279
class PSBTInput
280
{
281
private:
282
    uint32_t m_psbt_version;
283
284
public:
285
    CTransactionRef non_witness_utxo;
286
    CTxOut witness_utxo;
287
    CScript redeem_script;
288
    CScript witness_script;
289
    CScript final_script_sig;
290
    CScriptWitness final_script_witness;
291
    std::map<CPubKey, KeyOriginInfo> hd_keypaths;
292
    std::map<CKeyID, SigPair> partial_sigs;
293
    std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
294
    std::map<uint256, std::vector<unsigned char>> sha256_preimages;
295
    std::map<uint160, std::vector<unsigned char>> hash160_preimages;
296
    std::map<uint256, std::vector<unsigned char>> hash256_preimages;
297
298
    Txid prev_txid;
299
    uint32_t prev_out;
300
    std::optional<uint32_t> sequence;
301
    std::optional<uint32_t> time_locktime;
302
    std::optional<uint32_t> height_locktime;
303
304
    // Taproot fields
305
    std::vector<unsigned char> m_tap_key_sig;
306
    std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
307
    std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
308
    std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
309
    XOnlyPubKey m_tap_internal_key;
310
    uint256 m_tap_merkle_root;
311
312
    // MuSig2 fields
313
    std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
314
    // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to pubnonce
315
    std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, std::vector<uint8_t>>> m_musig2_pubnonces;
316
    // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to partial_sig
317
    std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, uint256>> m_musig2_partial_sigs;
318
319
    std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
320
    std::set<PSBTProprietary> m_proprietary;
321
    std::optional<int> sighash_type;
322
323
    bool IsNull() const;
324
    void FillSignatureData(SignatureData& sigdata) const;
325
    void FromSignatureData(const SignatureData& sigdata);
326
    [[nodiscard]] bool Merge(const PSBTInput& input);
327
33
    uint32_t GetVersion() const { return m_psbt_version; }
328
    COutPoint GetOutPoint() const;
329
    /**
330
     * Retrieves the UTXO for this input
331
     *
332
     * @param[out] utxo The UTXO of this input
333
     * @return Whether the UTXO could be retrieved
334
     */
335
    bool GetUTXO(CTxOut& utxo) const;
336
    bool HasSignatures() const;
337
338
    explicit PSBTInput(uint32_t psbt_version, const Txid& prev_txid, uint32_t prev_out, std::optional<uint32_t> sequence = std::nullopt)
339
1.93k
        : m_psbt_version(psbt_version),
340
1.93k
        prev_txid(prev_txid),
341
1.93k
        prev_out(prev_out),
342
1.93k
        sequence(sequence)
343
1.93k
    {
344
1.93k
        assert(m_psbt_version == 0 || m_psbt_version == 2);
345
1.93k
    }
346
347
    // Construct a PSBTInput when the previous txid and output index are expected to be serialized
348
    template <typename Stream>
349
    explicit PSBTInput(deserialize_type, Stream& s, uint32_t psbt_version)
350
1.48k
        : m_psbt_version(psbt_version)
351
1.48k
    {
352
1.48k
        assert(m_psbt_version == 2);
353
1.48k
        Unserialize(s);
354
1.48k
    }
Unexecuted instantiation: PSBTInput::PSBTInput<DataStream>(deserialize_type, DataStream&, unsigned int)
PSBTInput::PSBTInput<SpanReader>(deserialize_type, SpanReader&, unsigned int)
Line
Count
Source
350
1.48k
        : m_psbt_version(psbt_version)
351
1.48k
    {
352
1.48k
        assert(m_psbt_version == 2);
353
1.48k
        Unserialize(s);
354
1.48k
    }
355
356
    bool operator==(const PSBTInput&) const = default;
357
358
    template <typename Stream>
359
1.28k
    inline void Serialize(Stream& s) const {
360
        // Write the utxo
361
1.28k
        if (non_witness_utxo) {
362
550
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_NON_WITNESS_UTXO));
363
550
            SerializeToVector(s, TX_NO_WITNESS(non_witness_utxo));
364
550
        }
365
1.28k
        if (!witness_utxo.IsNull()) {
366
1.07k
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESS_UTXO));
367
1.07k
            SerializeToVector(s, witness_utxo);
368
1.07k
        }
369
370
1.28k
        if (final_script_sig.empty() && final_script_witness.IsNull()) {
371
            // Write any partial signatures
372
1.02k
            for (const auto& sig_pair : partial_sigs) {
373
105
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
374
105
                s << sig_pair.second.second;
375
105
            }
376
377
            // Write the sighash type
378
1.02k
            if (sighash_type != std::nullopt) {
379
28
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_SIGHASH));
380
28
                SerializeToVector(s, *sighash_type);
381
28
            }
382
383
            // Write the redeem script
384
1.02k
            if (!redeem_script.empty()) {
385
55
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_REDEEMSCRIPT));
386
55
                s << redeem_script;
387
55
            }
388
389
            // Write the witness script
390
1.02k
            if (!witness_script.empty()) {
391
67
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESSSCRIPT));
392
67
                s << witness_script;
393
67
            }
394
395
            // Write any hd keypaths
396
1.02k
            SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_IN_BIP32_DERIVATION));
397
398
            // Write any ripemd160 preimage
399
1.02k
            for (const auto& [hash, preimage] : ripemd160_preimages) {
400
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_RIPEMD160), std::span{hash});
401
0
                s << preimage;
402
0
            }
403
404
            // Write any sha256 preimage
405
1.02k
            for (const auto& [hash, preimage] : sha256_preimages) {
406
1
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_SHA256), std::span{hash});
407
1
                s << preimage;
408
1
            }
409
410
            // Write any hash160 preimage
411
1.02k
            for (const auto& [hash, preimage] : hash160_preimages) {
412
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH160), std::span{hash});
413
0
                s << preimage;
414
0
            }
415
416
            // Write any hash256 preimage
417
1.02k
            for (const auto& [hash, preimage] : hash256_preimages) {
418
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH256), std::span{hash});
419
0
                s << preimage;
420
0
            }
421
422
            // Write taproot key sig
423
1.02k
            if (!m_tap_key_sig.empty()) {
424
122
                SerializeToVector(s, PSBT_IN_TAP_KEY_SIG);
425
122
                s << m_tap_key_sig;
426
122
            }
427
428
            // Write taproot script sigs
429
1.02k
            for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
430
242
                const auto& [xonly, leaf_hash] = pubkey_leaf;
431
242
                SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
432
242
                s << sig;
433
242
            }
434
435
            // Write taproot leaf scripts
436
1.02k
            for (const auto& [leaf, control_blocks] : m_tap_scripts) {
437
677
                const auto& [script, leaf_ver] = leaf;
438
855
                for (const auto& control_block : control_blocks) {
439
855
                    SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, std::span{control_block});
440
855
                    std::vector<unsigned char> value_v(script.begin(), script.end());
441
855
                    value_v.push_back((uint8_t)leaf_ver);
442
855
                    s << value_v;
443
855
                }
444
677
            }
445
446
            // Write taproot bip32 keypaths
447
2.10k
            for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
448
2.10k
                const auto& [leaf_hashes, origin] = leaf_origin;
449
2.10k
                SerializeToVector(s, PSBT_IN_TAP_BIP32_DERIVATION, xonly);
450
2.10k
                std::vector<unsigned char> value;
451
2.10k
                VectorWriter s_value{value, 0};
452
2.10k
                s_value << leaf_hashes;
453
2.10k
                SerializeKeyOrigin(s_value, origin);
454
2.10k
                s << value;
455
2.10k
            }
456
457
            // Write taproot internal key
458
1.02k
            if (!m_tap_internal_key.IsNull()) {
459
530
                SerializeToVector(s, PSBT_IN_TAP_INTERNAL_KEY);
460
530
                s << ToByteVector(m_tap_internal_key);
461
530
            }
462
463
            // Write taproot merkle root
464
1.02k
            if (!m_tap_merkle_root.IsNull()) {
465
442
                SerializeToVector(s, PSBT_IN_TAP_MERKLE_ROOT);
466
442
                SerializeToVector(s, m_tap_merkle_root);
467
442
            }
468
469
            // Write MuSig2 Participants
470
1.02k
            for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
471
269
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
472
269
                std::vector<unsigned char> value;
473
269
                VectorWriter s_value{value, 0};
474
743
                for (auto& pk : part_pubs) {
475
743
                    s_value << std::span{pk};
476
743
                }
477
269
                s << value;
478
269
            }
479
480
            // Write MuSig2 pubnonces
481
1.02k
            for (const auto& [agg_pubkey_leaf_hash, pubnonces] : m_musig2_pubnonces) {
482
269
                const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
483
477
                for (const auto& [part_pubkey, pubnonce] : pubnonces) {
484
477
                    if (leaf_hash.IsNull()) {
485
222
                        SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey});
486
255
                    } else {
487
255
                        SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey}, leaf_hash);
488
255
                    }
489
477
                    s << pubnonce;
490
477
                }
491
269
            }
492
493
            // Write MuSig2 partial signatures
494
1.02k
            for (const auto& [agg_pubkey_leaf_hash, psigs] : m_musig2_partial_sigs) {
495
98
                const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
496
144
                for (const auto& [pubkey, psig] : psigs) {
497
144
                    if (leaf_hash.IsNull()) {
498
66
                        SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey});
499
78
                    } else {
500
78
                        SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey}, leaf_hash);
501
78
                    }
502
144
                    SerializeToVector(s, psig);
503
144
                }
504
98
            }
505
1.02k
        }
506
507
        // Write script sig
508
1.28k
        if (!final_script_sig.empty()) {
509
40
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTSIG));
510
40
            s << final_script_sig;
511
40
        }
512
        // write script witness
513
1.28k
        if (!final_script_witness.IsNull()) {
514
233
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTWITNESS));
515
233
            SerializeToVector(s, final_script_witness.stack);
516
233
        }
517
518
        // Write PSBTv2 fields
519
1.28k
        if (m_psbt_version >= 2) {
520
            // Write prev txid, vout, sequence, and lock times
521
1.22k
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_PREVIOUS_TXID));
522
1.22k
            SerializeToVector(s, prev_txid);
523
524
1.22k
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_OUTPUT_INDEX));
525
1.22k
            SerializeToVector(s, prev_out);
526
527
1.22k
            if (sequence != std::nullopt) {
528
1.22k
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_SEQUENCE));
529
1.22k
                SerializeToVector(s, *sequence);
530
1.22k
            }
531
1.22k
            if (time_locktime != std::nullopt) {
532
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_REQUIRED_TIME_LOCKTIME));
533
0
                SerializeToVector(s, *time_locktime);
534
0
            }
535
1.22k
            if (height_locktime != std::nullopt) {
536
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_REQUIRED_HEIGHT_LOCKTIME));
537
0
                SerializeToVector(s, *height_locktime);
538
0
            }
539
1.22k
        }
540
541
        // Write proprietary things
542
1.28k
        for (const auto& entry : m_proprietary) {
543
0
            s << entry.key;
544
0
            s << entry.value;
545
0
        }
546
547
        // Write unknown things
548
1.28k
        for (auto& entry : unknown) {
549
5
            s << entry.first;
550
5
            s << entry.second;
551
5
        }
552
553
1.28k
        s << PSBT_SEPARATOR;
554
1.28k
    }
555
556
557
    template <typename Stream>
558
1.67k
    inline void Unserialize(Stream& s) {
559
        // Used for duplicate key detection
560
1.67k
        std::set<std::vector<unsigned char>> key_lookup;
561
        // Cache whether PSBTv2 required fields were seen
562
1.67k
        bool found_prev_txid = false;
563
1.67k
        bool found_prev_out = false;
564
565
        // Read loop
566
1.67k
        bool found_sep = false;
567
17.7k
        while(!s.empty()) {
568
            // Read the key of format "<keylen><keytype><keydata>" after which
569
            // "key" will contain "<keytype><keydata>"
570
17.7k
            std::vector<unsigned char> key;
571
17.7k
            s >> key;
572
573
            // the key is empty if that was actually a separator byte
574
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
575
17.7k
            if (key.empty()) {
576
1.61k
                found_sep = true;
577
1.61k
                break;
578
1.61k
            }
579
580
            // Duplicate keys are not permitted
581
16.1k
            if (!key_lookup.emplace(key).second) {
582
7
                throw std::ios_base::failure(tfm::format("Duplicate Key, input key \"%s\" already provided", HexStr(key)));
583
7
            }
584
585
            // "skey" is used so that "key" is unchanged after reading keytype below
586
16.1k
            SpanReader skey{key};
587
            // keytype is of the format compact size uint at the beginning of "key"
588
16.1k
            uint64_t type = ReadCompactSize(skey);
589
590
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
591
            // format "<valuelen><valuedata>" from the stream "s", and value checks
592
16.1k
            switch(type) {
593
422
                case PSBT_IN_NON_WITNESS_UTXO:
594
422
                {
595
422
                    ExpectedKeySize("Input Non-witness UTXO", key, 1);
596
                    // Set the stream to unserialize with witness since this is always a valid network transaction
597
422
                    UnserializeFromVector(s, TX_WITH_WITNESS(non_witness_utxo));
598
422
                    break;
599
0
                }
600
1.39k
                case PSBT_IN_WITNESS_UTXO:
601
1.39k
                    ExpectedKeySize("Input Witness UTXO", key, 1);
602
1.39k
                    UnserializeFromVector(s, witness_utxo);
603
1.39k
                    break;
604
150
                case PSBT_IN_PARTIAL_SIG:
605
150
                {
606
                    // Make sure that the key is the size of pubkey + 1
607
150
                    if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
608
1
                        throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
609
1
                    }
610
                    // Read in the pubkey from key
611
149
                    CPubKey pubkey(key.begin() + 1, key.end());
612
149
                    if (!pubkey.IsFullyValid()) {
613
0
                       throw std::ios_base::failure("Invalid pubkey");
614
0
                    }
615
616
                    // Read in the signature from value
617
149
                    std::vector<unsigned char> sig;
618
149
                    s >> sig;
619
620
                    // Check that the signature is validly encoded
621
149
                    if (sig.empty() || !CheckSignatureEncoding(sig, SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC, nullptr)) {
622
0
                        throw std::ios_base::failure("Signature is not a valid encoding");
623
0
                    }
624
625
                    // Add to list
626
149
                    partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
627
149
                    break;
628
149
                }
629
63
                case PSBT_IN_SIGHASH:
630
63
                    ExpectedKeySize("Input Sighash Type", key, 1);
631
63
                    int sighash;
632
63
                    UnserializeFromVector(s, sighash);
633
63
                    sighash_type = sighash;
634
63
                    break;
635
48
                case PSBT_IN_REDEEMSCRIPT:
636
48
                {
637
48
                    ExpectedKeySize("Input redeemScript", key, 1);
638
48
                    s >> redeem_script;
639
48
                    break;
640
149
                }
641
102
                case PSBT_IN_WITNESSSCRIPT:
642
102
                {
643
102
                    ExpectedKeySize("Input witnessScript", key, 1);
644
102
                    s >> witness_script;
645
102
                    break;
646
149
                }
647
464
                case PSBT_IN_BIP32_DERIVATION:
648
464
                {
649
464
                    DeserializeHDKeypaths(s, key, hd_keypaths);
650
464
                    break;
651
149
                }
652
32
                case PSBT_IN_SCRIPTSIG:
653
32
                {
654
32
                    ExpectedKeySize("Input Final scriptSig", key, 1);
655
32
                    s >> final_script_sig;
656
32
                    break;
657
149
                }
658
71
                case PSBT_IN_SCRIPTWITNESS:
659
71
                {
660
71
                    ExpectedKeySize("Input Final scriptWitness", key, 1);
661
71
                    UnserializeFromVector(s, final_script_witness.stack);
662
71
                    break;
663
149
                }
664
3
                case PSBT_IN_RIPEMD160:
665
3
                {
666
3
                    ExpectedKeySize("Input RIPEMD160 Preimage", key, CRIPEMD160::OUTPUT_SIZE + 1);
667
                    // Read in the hash from key
668
3
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
669
3
                    uint160 hash(hash_vec);
670
671
                    // Read in the preimage from value
672
3
                    std::vector<unsigned char> preimage;
673
3
                    s >> preimage;
674
675
                    // Add to preimages list
676
3
                    ripemd160_preimages.emplace(hash, std::move(preimage));
677
3
                    break;
678
149
                }
679
6
                case PSBT_IN_SHA256:
680
6
                {
681
6
                    ExpectedKeySize("Input SHA256 Preimage", key, CSHA256::OUTPUT_SIZE + 1);
682
                    // Read in the hash from key
683
6
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
684
6
                    uint256 hash(hash_vec);
685
686
                    // Read in the preimage from value
687
6
                    std::vector<unsigned char> preimage;
688
6
                    s >> preimage;
689
690
                    // Add to preimages list
691
6
                    sha256_preimages.emplace(hash, std::move(preimage));
692
6
                    break;
693
149
                }
694
3
                case PSBT_IN_HASH160:
695
3
                {
696
3
                    ExpectedKeySize("Input Hash160 Preimage", key, CHash160::OUTPUT_SIZE + 1);
697
                    // Read in the hash from key
698
3
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
699
3
                    uint160 hash(hash_vec);
700
701
                    // Read in the preimage from value
702
3
                    std::vector<unsigned char> preimage;
703
3
                    s >> preimage;
704
705
                    // Add to preimages list
706
3
                    hash160_preimages.emplace(hash, std::move(preimage));
707
3
                    break;
708
149
                }
709
3
                case PSBT_IN_HASH256:
710
3
                {
711
3
                    ExpectedKeySize("Input Hash256 Preimage", key, CHash256::OUTPUT_SIZE + 1);
712
                    // Read in the hash from key
713
3
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
714
3
                    uint256 hash(hash_vec);
715
716
                    // Read in the preimage from value
717
3
                    std::vector<unsigned char> preimage;
718
3
                    s >> preimage;
719
720
                    // Add to preimages list
721
3
                    hash256_preimages.emplace(hash, std::move(preimage));
722
3
                    break;
723
149
                }
724
1.48k
                case PSBT_IN_PREVIOUS_TXID:
725
1.48k
                {
726
1.48k
                    ExpectedKeySize("Input Previous TXID", key, 1);
727
1.48k
                    if (m_psbt_version < 2) {
728
1
                        throw std::ios_base::failure("Previous txid is not allowed in PSBTv0");
729
1
                    }
730
1.48k
                    UnserializeFromVector(s, prev_txid);
731
1.48k
                    found_prev_txid = true;
732
1.48k
                    break;
733
1.48k
                }
734
1.48k
                case PSBT_IN_OUTPUT_INDEX:
735
1.48k
                {
736
1.48k
                    ExpectedKeySize("Input Previous Output's Index", key, 1);
737
1.48k
                    if (m_psbt_version < 2) {
738
1
                        throw std::ios_base::failure("Previous output's index is not allowed in PSBTv0");
739
1
                    }
740
1.48k
                    UnserializeFromVector(s, prev_out);
741
1.48k
                    found_prev_out = true;
742
1.48k
                    break;
743
1.48k
                }
744
1.44k
                case PSBT_IN_SEQUENCE:
745
1.44k
                {
746
1.44k
                    ExpectedKeySize("Input Sequence", key, 1);
747
1.44k
                    if (m_psbt_version < 2) {
748
1
                        throw std::ios_base::failure("Sequence is not allowed in PSBTv0");
749
1
                    }
750
1.44k
                    sequence.emplace();
751
1.44k
                    UnserializeFromVector(s, *sequence);
752
1.44k
                    break;
753
1.44k
                }
754
14
                case PSBT_IN_REQUIRED_TIME_LOCKTIME:
755
14
                {
756
14
                    ExpectedKeySize("Input Required Time Based Locktime", key, 1);
757
14
                    if (m_psbt_version < 2) {
758
1
                        throw std::ios_base::failure("Required time based locktime is not allowed in PSBTv0");
759
1
                    }
760
13
                    time_locktime.emplace();
761
13
                    UnserializeFromVector(s, *time_locktime);
762
13
                    if (*time_locktime < LOCKTIME_THRESHOLD) {
763
1
                        throw std::ios_base::failure("Required time based locktime is invalid (less than 500000000)");
764
1
                    }
765
12
                    break;
766
13
                }
767
15
                case PSBT_IN_REQUIRED_HEIGHT_LOCKTIME:
768
15
                {
769
15
                    ExpectedKeySize("Input Required Height Based Locktime", key, 1);
770
15
                    if (m_psbt_version < 2) {
771
1
                        throw std::ios_base::failure("Required height based locktime is not allowed in PSBTv0");
772
1
                    }
773
14
                    height_locktime.emplace();
774
14
                    UnserializeFromVector(s, *height_locktime);
775
14
                    if (*height_locktime >= LOCKTIME_THRESHOLD) {
776
1
                        throw std::ios_base::failure("Required height based locktime is invalid (greater than or equal to 500000000)");
777
13
                    } else if (*height_locktime == 0) {
778
1
                        throw std::ios_base::failure("Required height based locktime is invalid (0)");
779
1
                    }
780
12
                    break;
781
14
                }
782
174
                case PSBT_IN_TAP_KEY_SIG:
783
174
                {
784
174
                    ExpectedKeySize("Input Taproot Key Path Signature", key, 1);
785
174
                    s >> m_tap_key_sig;
786
174
                    if (m_tap_key_sig.size() < 64) {
787
1
                        throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
788
173
                    } else if (m_tap_key_sig.size() > 65) {
789
1
                        throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
790
1
                    }
791
172
                    break;
792
174
                }
793
336
                case PSBT_IN_TAP_SCRIPT_SIG:
794
336
                {
795
336
                    ExpectedKeySize("Input Taproot Script Path Signature", key, 65);
796
336
                    SpanReader s_key{std::span{key}.subspan(1)};
797
336
                    XOnlyPubKey xonly;
798
336
                    uint256 hash;
799
336
                    s_key >> xonly;
800
336
                    s_key >> hash;
801
336
                    std::vector<unsigned char> sig;
802
336
                    s >> sig;
803
336
                    if (sig.size() < 64) {
804
1
                        throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
805
335
                    } else if (sig.size() > 65) {
806
1
                        throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
807
1
                    }
808
334
                    m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
809
334
                    break;
810
336
                }
811
1.39k
                case PSBT_IN_TAP_LEAF_SCRIPT:
812
1.39k
                {
813
1.39k
                    if (key.size() < 34) {
814
0
                        throw std::ios_base::failure("Input Taproot leaf script key is not at least 34 bytes");
815
1.39k
                    } else if ((key.size() - 2) % 32 != 0) {
816
3
                        throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
817
3
                    }
818
1.39k
                    std::vector<unsigned char> script_v;
819
1.39k
                    s >> script_v;
820
1.39k
                    if (script_v.empty()) {
821
0
                        throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
822
0
                    }
823
1.39k
                    uint8_t leaf_ver = script_v.back();
824
1.39k
                    script_v.pop_back();
825
1.39k
                    const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
826
1.39k
                    m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
827
1.39k
                    break;
828
1.39k
                }
829
3.68k
                case PSBT_IN_TAP_BIP32_DERIVATION:
830
3.68k
                {
831
3.68k
                    ExpectedKeySize("Input Taproot BIP32 Keypath", key, 33);
832
3.68k
                    SpanReader s_key{std::span{key}.subspan(1)};
833
3.68k
                    XOnlyPubKey xonly;
834
3.68k
                    s_key >> xonly;
835
3.68k
                    std::set<uint256> leaf_hashes;
836
3.68k
                    uint64_t value_len = ReadCompactSize(s);
837
3.68k
                    size_t before_hashes = s.size();
838
3.68k
                    s >> leaf_hashes;
839
3.68k
                    size_t after_hashes = s.size();
840
3.68k
                    size_t hashes_len = before_hashes - after_hashes;
841
3.68k
                    if (hashes_len > value_len) {
842
1
                        throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
843
1
                    }
844
3.67k
                    size_t origin_len = value_len - hashes_len;
845
3.67k
                    m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
846
3.67k
                    break;
847
3.68k
                }
848
892
                case PSBT_IN_TAP_INTERNAL_KEY:
849
892
                {
850
892
                    ExpectedKeySize("Input Taproot Internal Key", key, 1);
851
892
                    UnserializeFromVector(s, m_tap_internal_key);
852
892
                    break;
853
3.68k
                }
854
728
                case PSBT_IN_TAP_MERKLE_ROOT:
855
728
                {
856
728
                    ExpectedKeySize("Input Taproot Merkle Root", key, 1);
857
728
                    UnserializeFromVector(s, m_tap_merkle_root);
858
728
                    break;
859
3.68k
                }
860
526
                case PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS:
861
526
                {
862
526
                    ExpectedKeySize("Input MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
863
526
                    DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
864
526
                    break;
865
3.68k
                }
866
904
                case PSBT_IN_MUSIG2_PUB_NONCE:
867
904
                {
868
904
                    if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
869
2
                        throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
870
2
                    }
871
902
                    CPubKey agg_pub, part_pub;
872
902
                    uint256 leaf_hash;
873
902
                    DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
874
875
902
                    std::vector<uint8_t> pubnonce;
876
902
                    s >> pubnonce;
877
902
                    if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) {
878
1
                        throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
879
1
                    }
880
881
901
                    m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
882
901
                    break;
883
902
                }
884
304
                case PSBT_IN_MUSIG2_PARTIAL_SIG:
885
304
                {
886
304
                    if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
887
2
                        throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
888
2
                    }
889
302
                    CPubKey agg_pub, part_pub;
890
302
                    uint256 leaf_hash;
891
302
                    DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
892
893
302
                    uint256 partial_sig;
894
302
                    UnserializeFromVector(s, partial_sig);
895
896
302
                    m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
897
302
                    break;
898
304
                }
899
1
                case PSBT_IN_PROPRIETARY:
900
1
                {
901
1
                    PSBTProprietary this_prop;
902
1
                    skey >> this_prop.identifier;
903
1
                    this_prop.subtype = ReadCompactSize(skey);
904
1
                    this_prop.key = key;
905
906
1
                    s >> this_prop.value;
907
1
                    m_proprietary.insert(this_prop);
908
1
                    break;
909
304
                }
910
                // Unknown stuff
911
5
                default:
912
                    // Read in the value
913
5
                    std::vector<unsigned char> val_bytes;
914
5
                    s >> val_bytes;
915
5
                    unknown.emplace(std::move(key), std::move(val_bytes));
916
5
                    break;
917
16.1k
            }
918
16.1k
        }
919
920
1.61k
        if (!found_sep) {
921
0
            throw std::ios_base::failure("Separator is missing at the end of an input map");
922
0
        }
923
924
        // Make sure required PSBTv2 fields are present
925
1.61k
        if (m_psbt_version >= 2) {
926
1.47k
            if (!found_prev_txid) {
927
1
                throw std::ios_base::failure("Previous TXID is required in PSBTv2");
928
1
            }
929
1.47k
            if (!found_prev_out) {
930
1
                throw std::ios_base::failure("Previous output's index is required in PSBTv2");
931
1
            }
932
1.47k
        }
933
1.61k
    }
void PSBTInput::Unserialize<DataStream>(DataStream&)
Line
Count
Source
558
2
    inline void Unserialize(Stream& s) {
559
        // Used for duplicate key detection
560
2
        std::set<std::vector<unsigned char>> key_lookup;
561
        // Cache whether PSBTv2 required fields were seen
562
2
        bool found_prev_txid = false;
563
2
        bool found_prev_out = false;
564
565
        // Read loop
566
2
        bool found_sep = false;
567
2
        while(!s.empty()) {
568
            // Read the key of format "<keylen><keytype><keydata>" after which
569
            // "key" will contain "<keytype><keydata>"
570
2
            std::vector<unsigned char> key;
571
2
            s >> key;
572
573
            // the key is empty if that was actually a separator byte
574
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
575
2
            if (key.empty()) {
576
2
                found_sep = true;
577
2
                break;
578
2
            }
579
580
            // Duplicate keys are not permitted
581
0
            if (!key_lookup.emplace(key).second) {
582
0
                throw std::ios_base::failure(tfm::format("Duplicate Key, input key \"%s\" already provided", HexStr(key)));
583
0
            }
584
585
            // "skey" is used so that "key" is unchanged after reading keytype below
586
0
            SpanReader skey{key};
587
            // keytype is of the format compact size uint at the beginning of "key"
588
0
            uint64_t type = ReadCompactSize(skey);
589
590
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
591
            // format "<valuelen><valuedata>" from the stream "s", and value checks
592
0
            switch(type) {
593
0
                case PSBT_IN_NON_WITNESS_UTXO:
594
0
                {
595
0
                    ExpectedKeySize("Input Non-witness UTXO", key, 1);
596
                    // Set the stream to unserialize with witness since this is always a valid network transaction
597
0
                    UnserializeFromVector(s, TX_WITH_WITNESS(non_witness_utxo));
598
0
                    break;
599
0
                }
600
0
                case PSBT_IN_WITNESS_UTXO:
601
0
                    ExpectedKeySize("Input Witness UTXO", key, 1);
602
0
                    UnserializeFromVector(s, witness_utxo);
603
0
                    break;
604
0
                case PSBT_IN_PARTIAL_SIG:
605
0
                {
606
                    // Make sure that the key is the size of pubkey + 1
607
0
                    if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
608
0
                        throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
609
0
                    }
610
                    // Read in the pubkey from key
611
0
                    CPubKey pubkey(key.begin() + 1, key.end());
612
0
                    if (!pubkey.IsFullyValid()) {
613
0
                       throw std::ios_base::failure("Invalid pubkey");
614
0
                    }
615
616
                    // Read in the signature from value
617
0
                    std::vector<unsigned char> sig;
618
0
                    s >> sig;
619
620
                    // Check that the signature is validly encoded
621
0
                    if (sig.empty() || !CheckSignatureEncoding(sig, SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC, nullptr)) {
622
0
                        throw std::ios_base::failure("Signature is not a valid encoding");
623
0
                    }
624
625
                    // Add to list
626
0
                    partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
627
0
                    break;
628
0
                }
629
0
                case PSBT_IN_SIGHASH:
630
0
                    ExpectedKeySize("Input Sighash Type", key, 1);
631
0
                    int sighash;
632
0
                    UnserializeFromVector(s, sighash);
633
0
                    sighash_type = sighash;
634
0
                    break;
635
0
                case PSBT_IN_REDEEMSCRIPT:
636
0
                {
637
0
                    ExpectedKeySize("Input redeemScript", key, 1);
638
0
                    s >> redeem_script;
639
0
                    break;
640
0
                }
641
0
                case PSBT_IN_WITNESSSCRIPT:
642
0
                {
643
0
                    ExpectedKeySize("Input witnessScript", key, 1);
644
0
                    s >> witness_script;
645
0
                    break;
646
0
                }
647
0
                case PSBT_IN_BIP32_DERIVATION:
648
0
                {
649
0
                    DeserializeHDKeypaths(s, key, hd_keypaths);
650
0
                    break;
651
0
                }
652
0
                case PSBT_IN_SCRIPTSIG:
653
0
                {
654
0
                    ExpectedKeySize("Input Final scriptSig", key, 1);
655
0
                    s >> final_script_sig;
656
0
                    break;
657
0
                }
658
0
                case PSBT_IN_SCRIPTWITNESS:
659
0
                {
660
0
                    ExpectedKeySize("Input Final scriptWitness", key, 1);
661
0
                    UnserializeFromVector(s, final_script_witness.stack);
662
0
                    break;
663
0
                }
664
0
                case PSBT_IN_RIPEMD160:
665
0
                {
666
0
                    ExpectedKeySize("Input RIPEMD160 Preimage", key, CRIPEMD160::OUTPUT_SIZE + 1);
667
                    // Read in the hash from key
668
0
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
669
0
                    uint160 hash(hash_vec);
670
671
                    // Read in the preimage from value
672
0
                    std::vector<unsigned char> preimage;
673
0
                    s >> preimage;
674
675
                    // Add to preimages list
676
0
                    ripemd160_preimages.emplace(hash, std::move(preimage));
677
0
                    break;
678
0
                }
679
0
                case PSBT_IN_SHA256:
680
0
                {
681
0
                    ExpectedKeySize("Input SHA256 Preimage", key, CSHA256::OUTPUT_SIZE + 1);
682
                    // Read in the hash from key
683
0
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
684
0
                    uint256 hash(hash_vec);
685
686
                    // Read in the preimage from value
687
0
                    std::vector<unsigned char> preimage;
688
0
                    s >> preimage;
689
690
                    // Add to preimages list
691
0
                    sha256_preimages.emplace(hash, std::move(preimage));
692
0
                    break;
693
0
                }
694
0
                case PSBT_IN_HASH160:
695
0
                {
696
0
                    ExpectedKeySize("Input Hash160 Preimage", key, CHash160::OUTPUT_SIZE + 1);
697
                    // Read in the hash from key
698
0
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
699
0
                    uint160 hash(hash_vec);
700
701
                    // Read in the preimage from value
702
0
                    std::vector<unsigned char> preimage;
703
0
                    s >> preimage;
704
705
                    // Add to preimages list
706
0
                    hash160_preimages.emplace(hash, std::move(preimage));
707
0
                    break;
708
0
                }
709
0
                case PSBT_IN_HASH256:
710
0
                {
711
0
                    ExpectedKeySize("Input Hash256 Preimage", key, CHash256::OUTPUT_SIZE + 1);
712
                    // Read in the hash from key
713
0
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
714
0
                    uint256 hash(hash_vec);
715
716
                    // Read in the preimage from value
717
0
                    std::vector<unsigned char> preimage;
718
0
                    s >> preimage;
719
720
                    // Add to preimages list
721
0
                    hash256_preimages.emplace(hash, std::move(preimage));
722
0
                    break;
723
0
                }
724
0
                case PSBT_IN_PREVIOUS_TXID:
725
0
                {
726
0
                    ExpectedKeySize("Input Previous TXID", key, 1);
727
0
                    if (m_psbt_version < 2) {
728
0
                        throw std::ios_base::failure("Previous txid is not allowed in PSBTv0");
729
0
                    }
730
0
                    UnserializeFromVector(s, prev_txid);
731
0
                    found_prev_txid = true;
732
0
                    break;
733
0
                }
734
0
                case PSBT_IN_OUTPUT_INDEX:
735
0
                {
736
0
                    ExpectedKeySize("Input Previous Output's Index", key, 1);
737
0
                    if (m_psbt_version < 2) {
738
0
                        throw std::ios_base::failure("Previous output's index is not allowed in PSBTv0");
739
0
                    }
740
0
                    UnserializeFromVector(s, prev_out);
741
0
                    found_prev_out = true;
742
0
                    break;
743
0
                }
744
0
                case PSBT_IN_SEQUENCE:
745
0
                {
746
0
                    ExpectedKeySize("Input Sequence", key, 1);
747
0
                    if (m_psbt_version < 2) {
748
0
                        throw std::ios_base::failure("Sequence is not allowed in PSBTv0");
749
0
                    }
750
0
                    sequence.emplace();
751
0
                    UnserializeFromVector(s, *sequence);
752
0
                    break;
753
0
                }
754
0
                case PSBT_IN_REQUIRED_TIME_LOCKTIME:
755
0
                {
756
0
                    ExpectedKeySize("Input Required Time Based Locktime", key, 1);
757
0
                    if (m_psbt_version < 2) {
758
0
                        throw std::ios_base::failure("Required time based locktime is not allowed in PSBTv0");
759
0
                    }
760
0
                    time_locktime.emplace();
761
0
                    UnserializeFromVector(s, *time_locktime);
762
0
                    if (*time_locktime < LOCKTIME_THRESHOLD) {
763
0
                        throw std::ios_base::failure("Required time based locktime is invalid (less than 500000000)");
764
0
                    }
765
0
                    break;
766
0
                }
767
0
                case PSBT_IN_REQUIRED_HEIGHT_LOCKTIME:
768
0
                {
769
0
                    ExpectedKeySize("Input Required Height Based Locktime", key, 1);
770
0
                    if (m_psbt_version < 2) {
771
0
                        throw std::ios_base::failure("Required height based locktime is not allowed in PSBTv0");
772
0
                    }
773
0
                    height_locktime.emplace();
774
0
                    UnserializeFromVector(s, *height_locktime);
775
0
                    if (*height_locktime >= LOCKTIME_THRESHOLD) {
776
0
                        throw std::ios_base::failure("Required height based locktime is invalid (greater than or equal to 500000000)");
777
0
                    } else if (*height_locktime == 0) {
778
0
                        throw std::ios_base::failure("Required height based locktime is invalid (0)");
779
0
                    }
780
0
                    break;
781
0
                }
782
0
                case PSBT_IN_TAP_KEY_SIG:
783
0
                {
784
0
                    ExpectedKeySize("Input Taproot Key Path Signature", key, 1);
785
0
                    s >> m_tap_key_sig;
786
0
                    if (m_tap_key_sig.size() < 64) {
787
0
                        throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
788
0
                    } else if (m_tap_key_sig.size() > 65) {
789
0
                        throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
790
0
                    }
791
0
                    break;
792
0
                }
793
0
                case PSBT_IN_TAP_SCRIPT_SIG:
794
0
                {
795
0
                    ExpectedKeySize("Input Taproot Script Path Signature", key, 65);
796
0
                    SpanReader s_key{std::span{key}.subspan(1)};
797
0
                    XOnlyPubKey xonly;
798
0
                    uint256 hash;
799
0
                    s_key >> xonly;
800
0
                    s_key >> hash;
801
0
                    std::vector<unsigned char> sig;
802
0
                    s >> sig;
803
0
                    if (sig.size() < 64) {
804
0
                        throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
805
0
                    } else if (sig.size() > 65) {
806
0
                        throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
807
0
                    }
808
0
                    m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
809
0
                    break;
810
0
                }
811
0
                case PSBT_IN_TAP_LEAF_SCRIPT:
812
0
                {
813
0
                    if (key.size() < 34) {
814
0
                        throw std::ios_base::failure("Input Taproot leaf script key is not at least 34 bytes");
815
0
                    } else if ((key.size() - 2) % 32 != 0) {
816
0
                        throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
817
0
                    }
818
0
                    std::vector<unsigned char> script_v;
819
0
                    s >> script_v;
820
0
                    if (script_v.empty()) {
821
0
                        throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
822
0
                    }
823
0
                    uint8_t leaf_ver = script_v.back();
824
0
                    script_v.pop_back();
825
0
                    const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
826
0
                    m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
827
0
                    break;
828
0
                }
829
0
                case PSBT_IN_TAP_BIP32_DERIVATION:
830
0
                {
831
0
                    ExpectedKeySize("Input Taproot BIP32 Keypath", key, 33);
832
0
                    SpanReader s_key{std::span{key}.subspan(1)};
833
0
                    XOnlyPubKey xonly;
834
0
                    s_key >> xonly;
835
0
                    std::set<uint256> leaf_hashes;
836
0
                    uint64_t value_len = ReadCompactSize(s);
837
0
                    size_t before_hashes = s.size();
838
0
                    s >> leaf_hashes;
839
0
                    size_t after_hashes = s.size();
840
0
                    size_t hashes_len = before_hashes - after_hashes;
841
0
                    if (hashes_len > value_len) {
842
0
                        throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
843
0
                    }
844
0
                    size_t origin_len = value_len - hashes_len;
845
0
                    m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
846
0
                    break;
847
0
                }
848
0
                case PSBT_IN_TAP_INTERNAL_KEY:
849
0
                {
850
0
                    ExpectedKeySize("Input Taproot Internal Key", key, 1);
851
0
                    UnserializeFromVector(s, m_tap_internal_key);
852
0
                    break;
853
0
                }
854
0
                case PSBT_IN_TAP_MERKLE_ROOT:
855
0
                {
856
0
                    ExpectedKeySize("Input Taproot Merkle Root", key, 1);
857
0
                    UnserializeFromVector(s, m_tap_merkle_root);
858
0
                    break;
859
0
                }
860
0
                case PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS:
861
0
                {
862
0
                    ExpectedKeySize("Input MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
863
0
                    DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
864
0
                    break;
865
0
                }
866
0
                case PSBT_IN_MUSIG2_PUB_NONCE:
867
0
                {
868
0
                    if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
869
0
                        throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
870
0
                    }
871
0
                    CPubKey agg_pub, part_pub;
872
0
                    uint256 leaf_hash;
873
0
                    DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
874
875
0
                    std::vector<uint8_t> pubnonce;
876
0
                    s >> pubnonce;
877
0
                    if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) {
878
0
                        throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
879
0
                    }
880
881
0
                    m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
882
0
                    break;
883
0
                }
884
0
                case PSBT_IN_MUSIG2_PARTIAL_SIG:
885
0
                {
886
0
                    if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
887
0
                        throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
888
0
                    }
889
0
                    CPubKey agg_pub, part_pub;
890
0
                    uint256 leaf_hash;
891
0
                    DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
892
893
0
                    uint256 partial_sig;
894
0
                    UnserializeFromVector(s, partial_sig);
895
896
0
                    m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
897
0
                    break;
898
0
                }
899
0
                case PSBT_IN_PROPRIETARY:
900
0
                {
901
0
                    PSBTProprietary this_prop;
902
0
                    skey >> this_prop.identifier;
903
0
                    this_prop.subtype = ReadCompactSize(skey);
904
0
                    this_prop.key = key;
905
906
0
                    s >> this_prop.value;
907
0
                    m_proprietary.insert(this_prop);
908
0
                    break;
909
0
                }
910
                // Unknown stuff
911
0
                default:
912
                    // Read in the value
913
0
                    std::vector<unsigned char> val_bytes;
914
0
                    s >> val_bytes;
915
0
                    unknown.emplace(std::move(key), std::move(val_bytes));
916
0
                    break;
917
0
            }
918
0
        }
919
920
2
        if (!found_sep) {
921
0
            throw std::ios_base::failure("Separator is missing at the end of an input map");
922
0
        }
923
924
        // Make sure required PSBTv2 fields are present
925
2
        if (m_psbt_version >= 2) {
926
0
            if (!found_prev_txid) {
927
0
                throw std::ios_base::failure("Previous TXID is required in PSBTv2");
928
0
            }
929
0
            if (!found_prev_out) {
930
0
                throw std::ios_base::failure("Previous output's index is required in PSBTv2");
931
0
            }
932
0
        }
933
2
    }
void PSBTInput::Unserialize<SpanReader>(SpanReader&)
Line
Count
Source
558
1.66k
    inline void Unserialize(Stream& s) {
559
        // Used for duplicate key detection
560
1.66k
        std::set<std::vector<unsigned char>> key_lookup;
561
        // Cache whether PSBTv2 required fields were seen
562
1.66k
        bool found_prev_txid = false;
563
1.66k
        bool found_prev_out = false;
564
565
        // Read loop
566
1.66k
        bool found_sep = false;
567
17.7k
        while(!s.empty()) {
568
            // Read the key of format "<keylen><keytype><keydata>" after which
569
            // "key" will contain "<keytype><keydata>"
570
17.7k
            std::vector<unsigned char> key;
571
17.7k
            s >> key;
572
573
            // the key is empty if that was actually a separator byte
574
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
575
17.7k
            if (key.empty()) {
576
1.61k
                found_sep = true;
577
1.61k
                break;
578
1.61k
            }
579
580
            // Duplicate keys are not permitted
581
16.1k
            if (!key_lookup.emplace(key).second) {
582
7
                throw std::ios_base::failure(tfm::format("Duplicate Key, input key \"%s\" already provided", HexStr(key)));
583
7
            }
584
585
            // "skey" is used so that "key" is unchanged after reading keytype below
586
16.1k
            SpanReader skey{key};
587
            // keytype is of the format compact size uint at the beginning of "key"
588
16.1k
            uint64_t type = ReadCompactSize(skey);
589
590
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
591
            // format "<valuelen><valuedata>" from the stream "s", and value checks
592
16.1k
            switch(type) {
593
422
                case PSBT_IN_NON_WITNESS_UTXO:
594
422
                {
595
422
                    ExpectedKeySize("Input Non-witness UTXO", key, 1);
596
                    // Set the stream to unserialize with witness since this is always a valid network transaction
597
422
                    UnserializeFromVector(s, TX_WITH_WITNESS(non_witness_utxo));
598
422
                    break;
599
0
                }
600
1.39k
                case PSBT_IN_WITNESS_UTXO:
601
1.39k
                    ExpectedKeySize("Input Witness UTXO", key, 1);
602
1.39k
                    UnserializeFromVector(s, witness_utxo);
603
1.39k
                    break;
604
150
                case PSBT_IN_PARTIAL_SIG:
605
150
                {
606
                    // Make sure that the key is the size of pubkey + 1
607
150
                    if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
608
1
                        throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
609
1
                    }
610
                    // Read in the pubkey from key
611
149
                    CPubKey pubkey(key.begin() + 1, key.end());
612
149
                    if (!pubkey.IsFullyValid()) {
613
0
                       throw std::ios_base::failure("Invalid pubkey");
614
0
                    }
615
616
                    // Read in the signature from value
617
149
                    std::vector<unsigned char> sig;
618
149
                    s >> sig;
619
620
                    // Check that the signature is validly encoded
621
149
                    if (sig.empty() || !CheckSignatureEncoding(sig, SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC, nullptr)) {
622
0
                        throw std::ios_base::failure("Signature is not a valid encoding");
623
0
                    }
624
625
                    // Add to list
626
149
                    partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
627
149
                    break;
628
149
                }
629
63
                case PSBT_IN_SIGHASH:
630
63
                    ExpectedKeySize("Input Sighash Type", key, 1);
631
63
                    int sighash;
632
63
                    UnserializeFromVector(s, sighash);
633
63
                    sighash_type = sighash;
634
63
                    break;
635
48
                case PSBT_IN_REDEEMSCRIPT:
636
48
                {
637
48
                    ExpectedKeySize("Input redeemScript", key, 1);
638
48
                    s >> redeem_script;
639
48
                    break;
640
149
                }
641
102
                case PSBT_IN_WITNESSSCRIPT:
642
102
                {
643
102
                    ExpectedKeySize("Input witnessScript", key, 1);
644
102
                    s >> witness_script;
645
102
                    break;
646
149
                }
647
464
                case PSBT_IN_BIP32_DERIVATION:
648
464
                {
649
464
                    DeserializeHDKeypaths(s, key, hd_keypaths);
650
464
                    break;
651
149
                }
652
32
                case PSBT_IN_SCRIPTSIG:
653
32
                {
654
32
                    ExpectedKeySize("Input Final scriptSig", key, 1);
655
32
                    s >> final_script_sig;
656
32
                    break;
657
149
                }
658
71
                case PSBT_IN_SCRIPTWITNESS:
659
71
                {
660
71
                    ExpectedKeySize("Input Final scriptWitness", key, 1);
661
71
                    UnserializeFromVector(s, final_script_witness.stack);
662
71
                    break;
663
149
                }
664
3
                case PSBT_IN_RIPEMD160:
665
3
                {
666
3
                    ExpectedKeySize("Input RIPEMD160 Preimage", key, CRIPEMD160::OUTPUT_SIZE + 1);
667
                    // Read in the hash from key
668
3
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
669
3
                    uint160 hash(hash_vec);
670
671
                    // Read in the preimage from value
672
3
                    std::vector<unsigned char> preimage;
673
3
                    s >> preimage;
674
675
                    // Add to preimages list
676
3
                    ripemd160_preimages.emplace(hash, std::move(preimage));
677
3
                    break;
678
149
                }
679
6
                case PSBT_IN_SHA256:
680
6
                {
681
6
                    ExpectedKeySize("Input SHA256 Preimage", key, CSHA256::OUTPUT_SIZE + 1);
682
                    // Read in the hash from key
683
6
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
684
6
                    uint256 hash(hash_vec);
685
686
                    // Read in the preimage from value
687
6
                    std::vector<unsigned char> preimage;
688
6
                    s >> preimage;
689
690
                    // Add to preimages list
691
6
                    sha256_preimages.emplace(hash, std::move(preimage));
692
6
                    break;
693
149
                }
694
3
                case PSBT_IN_HASH160:
695
3
                {
696
3
                    ExpectedKeySize("Input Hash160 Preimage", key, CHash160::OUTPUT_SIZE + 1);
697
                    // Read in the hash from key
698
3
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
699
3
                    uint160 hash(hash_vec);
700
701
                    // Read in the preimage from value
702
3
                    std::vector<unsigned char> preimage;
703
3
                    s >> preimage;
704
705
                    // Add to preimages list
706
3
                    hash160_preimages.emplace(hash, std::move(preimage));
707
3
                    break;
708
149
                }
709
3
                case PSBT_IN_HASH256:
710
3
                {
711
3
                    ExpectedKeySize("Input Hash256 Preimage", key, CHash256::OUTPUT_SIZE + 1);
712
                    // Read in the hash from key
713
3
                    std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
714
3
                    uint256 hash(hash_vec);
715
716
                    // Read in the preimage from value
717
3
                    std::vector<unsigned char> preimage;
718
3
                    s >> preimage;
719
720
                    // Add to preimages list
721
3
                    hash256_preimages.emplace(hash, std::move(preimage));
722
3
                    break;
723
149
                }
724
1.48k
                case PSBT_IN_PREVIOUS_TXID:
725
1.48k
                {
726
1.48k
                    ExpectedKeySize("Input Previous TXID", key, 1);
727
1.48k
                    if (m_psbt_version < 2) {
728
1
                        throw std::ios_base::failure("Previous txid is not allowed in PSBTv0");
729
1
                    }
730
1.48k
                    UnserializeFromVector(s, prev_txid);
731
1.48k
                    found_prev_txid = true;
732
1.48k
                    break;
733
1.48k
                }
734
1.48k
                case PSBT_IN_OUTPUT_INDEX:
735
1.48k
                {
736
1.48k
                    ExpectedKeySize("Input Previous Output's Index", key, 1);
737
1.48k
                    if (m_psbt_version < 2) {
738
1
                        throw std::ios_base::failure("Previous output's index is not allowed in PSBTv0");
739
1
                    }
740
1.48k
                    UnserializeFromVector(s, prev_out);
741
1.48k
                    found_prev_out = true;
742
1.48k
                    break;
743
1.48k
                }
744
1.44k
                case PSBT_IN_SEQUENCE:
745
1.44k
                {
746
1.44k
                    ExpectedKeySize("Input Sequence", key, 1);
747
1.44k
                    if (m_psbt_version < 2) {
748
1
                        throw std::ios_base::failure("Sequence is not allowed in PSBTv0");
749
1
                    }
750
1.44k
                    sequence.emplace();
751
1.44k
                    UnserializeFromVector(s, *sequence);
752
1.44k
                    break;
753
1.44k
                }
754
14
                case PSBT_IN_REQUIRED_TIME_LOCKTIME:
755
14
                {
756
14
                    ExpectedKeySize("Input Required Time Based Locktime", key, 1);
757
14
                    if (m_psbt_version < 2) {
758
1
                        throw std::ios_base::failure("Required time based locktime is not allowed in PSBTv0");
759
1
                    }
760
13
                    time_locktime.emplace();
761
13
                    UnserializeFromVector(s, *time_locktime);
762
13
                    if (*time_locktime < LOCKTIME_THRESHOLD) {
763
1
                        throw std::ios_base::failure("Required time based locktime is invalid (less than 500000000)");
764
1
                    }
765
12
                    break;
766
13
                }
767
15
                case PSBT_IN_REQUIRED_HEIGHT_LOCKTIME:
768
15
                {
769
15
                    ExpectedKeySize("Input Required Height Based Locktime", key, 1);
770
15
                    if (m_psbt_version < 2) {
771
1
                        throw std::ios_base::failure("Required height based locktime is not allowed in PSBTv0");
772
1
                    }
773
14
                    height_locktime.emplace();
774
14
                    UnserializeFromVector(s, *height_locktime);
775
14
                    if (*height_locktime >= LOCKTIME_THRESHOLD) {
776
1
                        throw std::ios_base::failure("Required height based locktime is invalid (greater than or equal to 500000000)");
777
13
                    } else if (*height_locktime == 0) {
778
1
                        throw std::ios_base::failure("Required height based locktime is invalid (0)");
779
1
                    }
780
12
                    break;
781
14
                }
782
174
                case PSBT_IN_TAP_KEY_SIG:
783
174
                {
784
174
                    ExpectedKeySize("Input Taproot Key Path Signature", key, 1);
785
174
                    s >> m_tap_key_sig;
786
174
                    if (m_tap_key_sig.size() < 64) {
787
1
                        throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
788
173
                    } else if (m_tap_key_sig.size() > 65) {
789
1
                        throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
790
1
                    }
791
172
                    break;
792
174
                }
793
336
                case PSBT_IN_TAP_SCRIPT_SIG:
794
336
                {
795
336
                    ExpectedKeySize("Input Taproot Script Path Signature", key, 65);
796
336
                    SpanReader s_key{std::span{key}.subspan(1)};
797
336
                    XOnlyPubKey xonly;
798
336
                    uint256 hash;
799
336
                    s_key >> xonly;
800
336
                    s_key >> hash;
801
336
                    std::vector<unsigned char> sig;
802
336
                    s >> sig;
803
336
                    if (sig.size() < 64) {
804
1
                        throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
805
335
                    } else if (sig.size() > 65) {
806
1
                        throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
807
1
                    }
808
334
                    m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
809
334
                    break;
810
336
                }
811
1.39k
                case PSBT_IN_TAP_LEAF_SCRIPT:
812
1.39k
                {
813
1.39k
                    if (key.size() < 34) {
814
0
                        throw std::ios_base::failure("Input Taproot leaf script key is not at least 34 bytes");
815
1.39k
                    } else if ((key.size() - 2) % 32 != 0) {
816
3
                        throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
817
3
                    }
818
1.39k
                    std::vector<unsigned char> script_v;
819
1.39k
                    s >> script_v;
820
1.39k
                    if (script_v.empty()) {
821
0
                        throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
822
0
                    }
823
1.39k
                    uint8_t leaf_ver = script_v.back();
824
1.39k
                    script_v.pop_back();
825
1.39k
                    const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
826
1.39k
                    m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
827
1.39k
                    break;
828
1.39k
                }
829
3.68k
                case PSBT_IN_TAP_BIP32_DERIVATION:
830
3.68k
                {
831
3.68k
                    ExpectedKeySize("Input Taproot BIP32 Keypath", key, 33);
832
3.68k
                    SpanReader s_key{std::span{key}.subspan(1)};
833
3.68k
                    XOnlyPubKey xonly;
834
3.68k
                    s_key >> xonly;
835
3.68k
                    std::set<uint256> leaf_hashes;
836
3.68k
                    uint64_t value_len = ReadCompactSize(s);
837
3.68k
                    size_t before_hashes = s.size();
838
3.68k
                    s >> leaf_hashes;
839
3.68k
                    size_t after_hashes = s.size();
840
3.68k
                    size_t hashes_len = before_hashes - after_hashes;
841
3.68k
                    if (hashes_len > value_len) {
842
1
                        throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
843
1
                    }
844
3.67k
                    size_t origin_len = value_len - hashes_len;
845
3.67k
                    m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
846
3.67k
                    break;
847
3.68k
                }
848
892
                case PSBT_IN_TAP_INTERNAL_KEY:
849
892
                {
850
892
                    ExpectedKeySize("Input Taproot Internal Key", key, 1);
851
892
                    UnserializeFromVector(s, m_tap_internal_key);
852
892
                    break;
853
3.68k
                }
854
728
                case PSBT_IN_TAP_MERKLE_ROOT:
855
728
                {
856
728
                    ExpectedKeySize("Input Taproot Merkle Root", key, 1);
857
728
                    UnserializeFromVector(s, m_tap_merkle_root);
858
728
                    break;
859
3.68k
                }
860
526
                case PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS:
861
526
                {
862
526
                    ExpectedKeySize("Input MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
863
526
                    DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
864
526
                    break;
865
3.68k
                }
866
904
                case PSBT_IN_MUSIG2_PUB_NONCE:
867
904
                {
868
904
                    if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
869
2
                        throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
870
2
                    }
871
902
                    CPubKey agg_pub, part_pub;
872
902
                    uint256 leaf_hash;
873
902
                    DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
874
875
902
                    std::vector<uint8_t> pubnonce;
876
902
                    s >> pubnonce;
877
902
                    if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) {
878
1
                        throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
879
1
                    }
880
881
901
                    m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
882
901
                    break;
883
902
                }
884
304
                case PSBT_IN_MUSIG2_PARTIAL_SIG:
885
304
                {
886
304
                    if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
887
2
                        throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
888
2
                    }
889
302
                    CPubKey agg_pub, part_pub;
890
302
                    uint256 leaf_hash;
891
302
                    DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
892
893
302
                    uint256 partial_sig;
894
302
                    UnserializeFromVector(s, partial_sig);
895
896
302
                    m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
897
302
                    break;
898
304
                }
899
1
                case PSBT_IN_PROPRIETARY:
900
1
                {
901
1
                    PSBTProprietary this_prop;
902
1
                    skey >> this_prop.identifier;
903
1
                    this_prop.subtype = ReadCompactSize(skey);
904
1
                    this_prop.key = key;
905
906
1
                    s >> this_prop.value;
907
1
                    m_proprietary.insert(this_prop);
908
1
                    break;
909
304
                }
910
                // Unknown stuff
911
5
                default:
912
                    // Read in the value
913
5
                    std::vector<unsigned char> val_bytes;
914
5
                    s >> val_bytes;
915
5
                    unknown.emplace(std::move(key), std::move(val_bytes));
916
5
                    break;
917
16.1k
            }
918
16.1k
        }
919
920
1.61k
        if (!found_sep) {
921
0
            throw std::ios_base::failure("Separator is missing at the end of an input map");
922
0
        }
923
924
        // Make sure required PSBTv2 fields are present
925
1.61k
        if (m_psbt_version >= 2) {
926
1.47k
            if (!found_prev_txid) {
927
1
                throw std::ios_base::failure("Previous TXID is required in PSBTv2");
928
1
            }
929
1.47k
            if (!found_prev_out) {
930
1
                throw std::ios_base::failure("Previous output's index is required in PSBTv2");
931
1
            }
932
1.47k
        }
933
1.61k
    }
934
};
935
936
/** A structure for PSBTs which contains per output information */
937
class PSBTOutput
938
{
939
private:
940
    uint32_t m_psbt_version;
941
942
public:
943
    CScript redeem_script;
944
    CScript witness_script;
945
    std::map<CPubKey, KeyOriginInfo> hd_keypaths;
946
947
    XOnlyPubKey m_tap_internal_key;
948
    std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
949
    std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
950
    std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
951
952
    std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
953
    std::set<PSBTProprietary> m_proprietary;
954
955
    CAmount amount;
956
    CScript script;
957
958
    bool IsNull() const;
959
    void FillSignatureData(SignatureData& sigdata) const;
960
    void FromSignatureData(const SignatureData& sigdata);
961
    [[nodiscard]] bool Merge(const PSBTOutput& output);
962
13
    uint32_t GetVersion() const { return m_psbt_version; }
963
964
    explicit PSBTOutput(uint32_t psbt_version, CAmount amount, const CScript& script)
965
4.31k
        : m_psbt_version(psbt_version),
966
4.31k
        amount(amount),
967
4.31k
        script(script)
968
4.31k
    {
969
4.31k
        assert(m_psbt_version == 0 || m_psbt_version == 2);
970
4.31k
    }
971
972
    // Construct a PSBTOutput when the amount and script are expected to be serialized
973
    template <typename Stream>
974
    explicit PSBTOutput(deserialize_type, Stream& s, uint32_t psbt_version)
975
2.24k
        : m_psbt_version(psbt_version)
976
2.24k
    {
977
2.24k
        assert(m_psbt_version == 2);
978
2.24k
        Unserialize(s);
979
2.24k
    }
Unexecuted instantiation: PSBTOutput::PSBTOutput<DataStream>(deserialize_type, DataStream&, unsigned int)
PSBTOutput::PSBTOutput<SpanReader>(deserialize_type, SpanReader&, unsigned int)
Line
Count
Source
975
2.24k
        : m_psbt_version(psbt_version)
976
2.24k
    {
977
2.24k
        assert(m_psbt_version == 2);
978
2.24k
        Unserialize(s);
979
2.24k
    }
980
981
    bool operator==(const PSBTOutput&) const = default;
982
983
    template <typename Stream>
984
1.93k
    inline void Serialize(Stream& s) const {
985
        // Write the redeem script
986
1.93k
        if (!redeem_script.empty()) {
987
16
            SerializeToVector(s, CompactSizeWriter(PSBT_OUT_REDEEMSCRIPT));
988
16
            s << redeem_script;
989
16
        }
990
991
        // Write the witness script
992
1.93k
        if (!witness_script.empty()) {
993
37
            SerializeToVector(s, CompactSizeWriter(PSBT_OUT_WITNESSSCRIPT));
994
37
            s << witness_script;
995
37
        }
996
997
        // Write any hd keypaths
998
1.93k
        SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_OUT_BIP32_DERIVATION));
999
1000
1.93k
        if (m_psbt_version >= 2) {
1001
            // Write amount and spk
1002
1.87k
            SerializeToVector(s, CompactSizeWriter(PSBT_OUT_AMOUNT));
1003
1.87k
            SerializeToVector(s, amount);
1004
1005
1.87k
            SerializeToVector(s, CompactSizeWriter(PSBT_OUT_SCRIPT));
1006
1.87k
            s << script;
1007
1.87k
        }
1008
1009
        // Write proprietary things
1010
1.93k
        for (const auto& entry : m_proprietary) {
1011
0
            s << entry.key;
1012
0
            s << entry.value;
1013
0
        }
1014
1015
        // Write taproot internal key
1016
1.93k
        if (!m_tap_internal_key.IsNull()) {
1017
404
            SerializeToVector(s, PSBT_OUT_TAP_INTERNAL_KEY);
1018
404
            s << ToByteVector(m_tap_internal_key);
1019
404
        }
1020
1021
        // Write taproot tree
1022
1.93k
        if (!m_tap_tree.empty()) {
1023
315
            SerializeToVector(s, PSBT_OUT_TAP_TREE);
1024
315
            std::vector<unsigned char> value;
1025
315
            VectorWriter s_value{value, 0};
1026
695
            for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
1027
695
                s_value << depth;
1028
695
                s_value << leaf_ver;
1029
695
                s_value << script;
1030
695
            }
1031
315
            s << value;
1032
315
        }
1033
1034
        // Write taproot bip32 keypaths
1035
1.93k
        for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
1036
1.66k
            const auto& [leaf_hashes, origin] = leaf;
1037
1.66k
            SerializeToVector(s, PSBT_OUT_TAP_BIP32_DERIVATION, xonly);
1038
1.66k
            std::vector<unsigned char> value;
1039
1.66k
            VectorWriter s_value{value, 0};
1040
1.66k
            s_value << leaf_hashes;
1041
1.66k
            SerializeKeyOrigin(s_value, origin);
1042
1.66k
            s << value;
1043
1.66k
        }
1044
1045
        // Write MuSig2 Participants
1046
1.93k
        for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
1047
256
            SerializeToVector(s, CompactSizeWriter(PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
1048
256
            std::vector<unsigned char> value;
1049
256
            VectorWriter s_value{value, 0};
1050
717
            for (auto& pk : part_pubs) {
1051
717
                s_value << std::span{pk};
1052
717
            }
1053
256
            s << value;
1054
256
        }
1055
1056
        // Write unknown things
1057
1.93k
        for (auto& entry : unknown) {
1058
0
            s << entry.first;
1059
0
            s << entry.second;
1060
0
        }
1061
1062
1.93k
        s << PSBT_SEPARATOR;
1063
1.93k
    }
1064
1065
1066
    template <typename Stream>
1067
2.39k
    inline void Unserialize(Stream& s) {
1068
        // Used for duplicate key detection
1069
2.39k
        std::set<std::vector<unsigned char>> key_lookup;
1070
        // Cache whether PSBTv2 required fields are found
1071
2.39k
        bool found_amount = false;
1072
2.39k
        bool found_script = false;
1073
1074
        // Read loop
1075
2.39k
        bool found_sep = false;
1076
12.0k
        while(!s.empty()) {
1077
            // Read the key of format "<keylen><keytype><keydata>" after which
1078
            // "key" will contain "<keytype><keydata>"
1079
12.0k
            std::vector<unsigned char> key;
1080
12.0k
            s >> key;
1081
1082
            // the key is empty if that was actually a separator byte
1083
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
1084
12.0k
            if (key.empty()) {
1085
2.37k
                found_sep = true;
1086
2.37k
                break;
1087
2.37k
            }
1088
1089
            // Duplicate keys are not permitted
1090
9.62k
            if (!key_lookup.emplace(key).second) {
1091
2
                throw std::ios_base::failure(tfm::format("Duplicate Key, output key \"%s\" already provided", HexStr(key)));
1092
2
            }
1093
1094
            // "skey" is used so that "key" is unchanged after reading keytype below
1095
9.62k
            SpanReader skey{key};
1096
            // keytype is of the format compact size uint at the beginning of "key"
1097
9.62k
            uint64_t type = ReadCompactSize(skey);
1098
1099
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
1100
            // format "<valuelen><valuedata>" from the stream "s", and value checks
1101
9.62k
            switch(type) {
1102
20
                case PSBT_OUT_REDEEMSCRIPT:
1103
20
                {
1104
20
                    ExpectedKeySize("Output redeemScript", key, 1);
1105
20
                    s >> redeem_script;
1106
20
                    break;
1107
0
                }
1108
51
                case PSBT_OUT_WITNESSSCRIPT:
1109
51
                {
1110
51
                    ExpectedKeySize("Output witnessScript", key, 1);
1111
51
                    s >> witness_script;
1112
51
                    break;
1113
0
                }
1114
385
                case PSBT_OUT_BIP32_DERIVATION:
1115
385
                {
1116
385
                    DeserializeHDKeypaths(s, key, hd_keypaths);
1117
385
                    break;
1118
0
                }
1119
2.24k
                case PSBT_OUT_AMOUNT:
1120
2.24k
                {
1121
2.24k
                    ExpectedKeySize("Output Amount", key, 1);
1122
2.24k
                    if (m_psbt_version < 2) {
1123
1
                        throw std::ios_base::failure("Output amount is not allowed in PSBTv0");
1124
1
                    }
1125
2.24k
                    UnserializeFromVector(s, amount);
1126
2.24k
                    found_amount = true;
1127
2.24k
                    break;
1128
2.24k
                }
1129
2.24k
                case PSBT_OUT_SCRIPT:
1130
2.24k
                {
1131
2.24k
                    ExpectedKeySize("Output Script", key, 1);
1132
2.24k
                    if (m_psbt_version < 2) {
1133
1
                        throw std::ios_base::failure("Output script is not allowed in PSBTv0");
1134
1
                    }
1135
2.24k
                    s >> script;
1136
2.24k
                    found_script = true;
1137
2.24k
                    break;
1138
2.24k
                }
1139
714
                case PSBT_OUT_TAP_INTERNAL_KEY:
1140
714
                {
1141
714
                    ExpectedKeySize("Output Taproot Internal Key", key, 1);
1142
714
                    UnserializeFromVector(s, m_tap_internal_key);
1143
714
                    break;
1144
2.24k
                }
1145
557
                case PSBT_OUT_TAP_TREE:
1146
557
                {
1147
557
                    ExpectedKeySize("Output Taproot Tree Key", key, 1);
1148
557
                    std::vector<unsigned char> tree_v;
1149
557
                    s >> tree_v;
1150
557
                    SpanReader s_tree{tree_v};
1151
557
                    if (s_tree.empty()) {
1152
1
                        throw std::ios_base::failure("Output Taproot tree must not be empty");
1153
1
                    }
1154
556
                    TaprootBuilder builder;
1155
1.78k
                    while (!s_tree.empty()) {
1156
1.22k
                        uint8_t depth;
1157
1.22k
                        uint8_t leaf_ver;
1158
1.22k
                        std::vector<unsigned char> script;
1159
1.22k
                        s_tree >> depth;
1160
1.22k
                        s_tree >> leaf_ver;
1161
1.22k
                        s_tree >> script;
1162
1.22k
                        if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1163
0
                            throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
1164
0
                        }
1165
1.22k
                        if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
1166
0
                            throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
1167
0
                        }
1168
1.22k
                        m_tap_tree.emplace_back(depth, leaf_ver, script);
1169
1.22k
                        builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
1170
1.22k
                    }
1171
556
                    if (!builder.IsComplete()) {
1172
0
                        throw std::ios_base::failure("Output Taproot tree is malformed");
1173
0
                    }
1174
556
                    break;
1175
556
                }
1176
2.94k
                case PSBT_OUT_TAP_BIP32_DERIVATION:
1177
2.94k
                {
1178
2.94k
                    ExpectedKeySize("Output Taproot BIP32 Keypath", key, 33);
1179
2.94k
                    XOnlyPubKey xonly(uint256(std::span<uint8_t>(key).last(32)));
1180
2.94k
                    std::set<uint256> leaf_hashes;
1181
2.94k
                    uint64_t value_len = ReadCompactSize(s);
1182
2.94k
                    size_t before_hashes = s.size();
1183
2.94k
                    s >> leaf_hashes;
1184
2.94k
                    size_t after_hashes = s.size();
1185
2.94k
                    size_t hashes_len = before_hashes - after_hashes;
1186
2.94k
                    if (hashes_len > value_len) {
1187
0
                        throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
1188
0
                    }
1189
2.94k
                    size_t origin_len = value_len - hashes_len;
1190
2.94k
                    m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
1191
2.94k
                    break;
1192
2.94k
                }
1193
457
                case PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS:
1194
457
                {
1195
457
                    ExpectedKeySize("Output MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
1196
457
                    DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Output"});
1197
457
                    break;
1198
2.94k
                }
1199
1
                case PSBT_OUT_PROPRIETARY:
1200
1
                {
1201
1
                    PSBTProprietary this_prop;
1202
1
                    skey >> this_prop.identifier;
1203
1
                    this_prop.subtype = ReadCompactSize(skey);
1204
1
                    this_prop.key = key;
1205
1206
1
                    s >> this_prop.value;
1207
1
                    m_proprietary.insert(this_prop);
1208
1
                    break;
1209
2.94k
                }
1210
                // Unknown stuff
1211
0
                default: {
1212
                    // Read in the value
1213
0
                    std::vector<unsigned char> val_bytes;
1214
0
                    s >> val_bytes;
1215
0
                    unknown.emplace(std::move(key), std::move(val_bytes));
1216
0
                    break;
1217
2.94k
                }
1218
9.62k
            }
1219
9.62k
        }
1220
1221
2.37k
        if (!found_sep) {
1222
0
            throw std::ios_base::failure("Separator is missing at the end of an output map");
1223
0
        }
1224
1225
        // Make sure required PSBTv2 fields are present
1226
2.37k
        if (m_psbt_version >= 2) {
1227
2.24k
            if (!found_amount) {
1228
1
                throw std::ios_base::failure("Output amount is required in PSBTv2");
1229
1
            }
1230
2.24k
            if (!found_script) {
1231
1
                throw std::ios_base::failure("Output script is required in PSBTv2");
1232
1
            }
1233
2.24k
        }
1234
2.37k
    }
void PSBTOutput::Unserialize<DataStream>(DataStream&)
Line
Count
Source
1067
2
    inline void Unserialize(Stream& s) {
1068
        // Used for duplicate key detection
1069
2
        std::set<std::vector<unsigned char>> key_lookup;
1070
        // Cache whether PSBTv2 required fields are found
1071
2
        bool found_amount = false;
1072
2
        bool found_script = false;
1073
1074
        // Read loop
1075
2
        bool found_sep = false;
1076
2
        while(!s.empty()) {
1077
            // Read the key of format "<keylen><keytype><keydata>" after which
1078
            // "key" will contain "<keytype><keydata>"
1079
2
            std::vector<unsigned char> key;
1080
2
            s >> key;
1081
1082
            // the key is empty if that was actually a separator byte
1083
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
1084
2
            if (key.empty()) {
1085
2
                found_sep = true;
1086
2
                break;
1087
2
            }
1088
1089
            // Duplicate keys are not permitted
1090
0
            if (!key_lookup.emplace(key).second) {
1091
0
                throw std::ios_base::failure(tfm::format("Duplicate Key, output key \"%s\" already provided", HexStr(key)));
1092
0
            }
1093
1094
            // "skey" is used so that "key" is unchanged after reading keytype below
1095
0
            SpanReader skey{key};
1096
            // keytype is of the format compact size uint at the beginning of "key"
1097
0
            uint64_t type = ReadCompactSize(skey);
1098
1099
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
1100
            // format "<valuelen><valuedata>" from the stream "s", and value checks
1101
0
            switch(type) {
1102
0
                case PSBT_OUT_REDEEMSCRIPT:
1103
0
                {
1104
0
                    ExpectedKeySize("Output redeemScript", key, 1);
1105
0
                    s >> redeem_script;
1106
0
                    break;
1107
0
                }
1108
0
                case PSBT_OUT_WITNESSSCRIPT:
1109
0
                {
1110
0
                    ExpectedKeySize("Output witnessScript", key, 1);
1111
0
                    s >> witness_script;
1112
0
                    break;
1113
0
                }
1114
0
                case PSBT_OUT_BIP32_DERIVATION:
1115
0
                {
1116
0
                    DeserializeHDKeypaths(s, key, hd_keypaths);
1117
0
                    break;
1118
0
                }
1119
0
                case PSBT_OUT_AMOUNT:
1120
0
                {
1121
0
                    ExpectedKeySize("Output Amount", key, 1);
1122
0
                    if (m_psbt_version < 2) {
1123
0
                        throw std::ios_base::failure("Output amount is not allowed in PSBTv0");
1124
0
                    }
1125
0
                    UnserializeFromVector(s, amount);
1126
0
                    found_amount = true;
1127
0
                    break;
1128
0
                }
1129
0
                case PSBT_OUT_SCRIPT:
1130
0
                {
1131
0
                    ExpectedKeySize("Output Script", key, 1);
1132
0
                    if (m_psbt_version < 2) {
1133
0
                        throw std::ios_base::failure("Output script is not allowed in PSBTv0");
1134
0
                    }
1135
0
                    s >> script;
1136
0
                    found_script = true;
1137
0
                    break;
1138
0
                }
1139
0
                case PSBT_OUT_TAP_INTERNAL_KEY:
1140
0
                {
1141
0
                    ExpectedKeySize("Output Taproot Internal Key", key, 1);
1142
0
                    UnserializeFromVector(s, m_tap_internal_key);
1143
0
                    break;
1144
0
                }
1145
0
                case PSBT_OUT_TAP_TREE:
1146
0
                {
1147
0
                    ExpectedKeySize("Output Taproot Tree Key", key, 1);
1148
0
                    std::vector<unsigned char> tree_v;
1149
0
                    s >> tree_v;
1150
0
                    SpanReader s_tree{tree_v};
1151
0
                    if (s_tree.empty()) {
1152
0
                        throw std::ios_base::failure("Output Taproot tree must not be empty");
1153
0
                    }
1154
0
                    TaprootBuilder builder;
1155
0
                    while (!s_tree.empty()) {
1156
0
                        uint8_t depth;
1157
0
                        uint8_t leaf_ver;
1158
0
                        std::vector<unsigned char> script;
1159
0
                        s_tree >> depth;
1160
0
                        s_tree >> leaf_ver;
1161
0
                        s_tree >> script;
1162
0
                        if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1163
0
                            throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
1164
0
                        }
1165
0
                        if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
1166
0
                            throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
1167
0
                        }
1168
0
                        m_tap_tree.emplace_back(depth, leaf_ver, script);
1169
0
                        builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
1170
0
                    }
1171
0
                    if (!builder.IsComplete()) {
1172
0
                        throw std::ios_base::failure("Output Taproot tree is malformed");
1173
0
                    }
1174
0
                    break;
1175
0
                }
1176
0
                case PSBT_OUT_TAP_BIP32_DERIVATION:
1177
0
                {
1178
0
                    ExpectedKeySize("Output Taproot BIP32 Keypath", key, 33);
1179
0
                    XOnlyPubKey xonly(uint256(std::span<uint8_t>(key).last(32)));
1180
0
                    std::set<uint256> leaf_hashes;
1181
0
                    uint64_t value_len = ReadCompactSize(s);
1182
0
                    size_t before_hashes = s.size();
1183
0
                    s >> leaf_hashes;
1184
0
                    size_t after_hashes = s.size();
1185
0
                    size_t hashes_len = before_hashes - after_hashes;
1186
0
                    if (hashes_len > value_len) {
1187
0
                        throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
1188
0
                    }
1189
0
                    size_t origin_len = value_len - hashes_len;
1190
0
                    m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
1191
0
                    break;
1192
0
                }
1193
0
                case PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS:
1194
0
                {
1195
0
                    ExpectedKeySize("Output MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
1196
0
                    DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Output"});
1197
0
                    break;
1198
0
                }
1199
0
                case PSBT_OUT_PROPRIETARY:
1200
0
                {
1201
0
                    PSBTProprietary this_prop;
1202
0
                    skey >> this_prop.identifier;
1203
0
                    this_prop.subtype = ReadCompactSize(skey);
1204
0
                    this_prop.key = key;
1205
1206
0
                    s >> this_prop.value;
1207
0
                    m_proprietary.insert(this_prop);
1208
0
                    break;
1209
0
                }
1210
                // Unknown stuff
1211
0
                default: {
1212
                    // Read in the value
1213
0
                    std::vector<unsigned char> val_bytes;
1214
0
                    s >> val_bytes;
1215
0
                    unknown.emplace(std::move(key), std::move(val_bytes));
1216
0
                    break;
1217
0
                }
1218
0
            }
1219
0
        }
1220
1221
2
        if (!found_sep) {
1222
0
            throw std::ios_base::failure("Separator is missing at the end of an output map");
1223
0
        }
1224
1225
        // Make sure required PSBTv2 fields are present
1226
2
        if (m_psbt_version >= 2) {
1227
0
            if (!found_amount) {
1228
0
                throw std::ios_base::failure("Output amount is required in PSBTv2");
1229
0
            }
1230
0
            if (!found_script) {
1231
0
                throw std::ios_base::failure("Output script is required in PSBTv2");
1232
0
            }
1233
0
        }
1234
2
    }
void PSBTOutput::Unserialize<SpanReader>(SpanReader&)
Line
Count
Source
1067
2.38k
    inline void Unserialize(Stream& s) {
1068
        // Used for duplicate key detection
1069
2.38k
        std::set<std::vector<unsigned char>> key_lookup;
1070
        // Cache whether PSBTv2 required fields are found
1071
2.38k
        bool found_amount = false;
1072
2.38k
        bool found_script = false;
1073
1074
        // Read loop
1075
2.38k
        bool found_sep = false;
1076
12.0k
        while(!s.empty()) {
1077
            // Read the key of format "<keylen><keytype><keydata>" after which
1078
            // "key" will contain "<keytype><keydata>"
1079
12.0k
            std::vector<unsigned char> key;
1080
12.0k
            s >> key;
1081
1082
            // the key is empty if that was actually a separator byte
1083
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
1084
12.0k
            if (key.empty()) {
1085
2.37k
                found_sep = true;
1086
2.37k
                break;
1087
2.37k
            }
1088
1089
            // Duplicate keys are not permitted
1090
9.62k
            if (!key_lookup.emplace(key).second) {
1091
2
                throw std::ios_base::failure(tfm::format("Duplicate Key, output key \"%s\" already provided", HexStr(key)));
1092
2
            }
1093
1094
            // "skey" is used so that "key" is unchanged after reading keytype below
1095
9.62k
            SpanReader skey{key};
1096
            // keytype is of the format compact size uint at the beginning of "key"
1097
9.62k
            uint64_t type = ReadCompactSize(skey);
1098
1099
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
1100
            // format "<valuelen><valuedata>" from the stream "s", and value checks
1101
9.62k
            switch(type) {
1102
20
                case PSBT_OUT_REDEEMSCRIPT:
1103
20
                {
1104
20
                    ExpectedKeySize("Output redeemScript", key, 1);
1105
20
                    s >> redeem_script;
1106
20
                    break;
1107
0
                }
1108
51
                case PSBT_OUT_WITNESSSCRIPT:
1109
51
                {
1110
51
                    ExpectedKeySize("Output witnessScript", key, 1);
1111
51
                    s >> witness_script;
1112
51
                    break;
1113
0
                }
1114
385
                case PSBT_OUT_BIP32_DERIVATION:
1115
385
                {
1116
385
                    DeserializeHDKeypaths(s, key, hd_keypaths);
1117
385
                    break;
1118
0
                }
1119
2.24k
                case PSBT_OUT_AMOUNT:
1120
2.24k
                {
1121
2.24k
                    ExpectedKeySize("Output Amount", key, 1);
1122
2.24k
                    if (m_psbt_version < 2) {
1123
1
                        throw std::ios_base::failure("Output amount is not allowed in PSBTv0");
1124
1
                    }
1125
2.24k
                    UnserializeFromVector(s, amount);
1126
2.24k
                    found_amount = true;
1127
2.24k
                    break;
1128
2.24k
                }
1129
2.24k
                case PSBT_OUT_SCRIPT:
1130
2.24k
                {
1131
2.24k
                    ExpectedKeySize("Output Script", key, 1);
1132
2.24k
                    if (m_psbt_version < 2) {
1133
1
                        throw std::ios_base::failure("Output script is not allowed in PSBTv0");
1134
1
                    }
1135
2.24k
                    s >> script;
1136
2.24k
                    found_script = true;
1137
2.24k
                    break;
1138
2.24k
                }
1139
714
                case PSBT_OUT_TAP_INTERNAL_KEY:
1140
714
                {
1141
714
                    ExpectedKeySize("Output Taproot Internal Key", key, 1);
1142
714
                    UnserializeFromVector(s, m_tap_internal_key);
1143
714
                    break;
1144
2.24k
                }
1145
557
                case PSBT_OUT_TAP_TREE:
1146
557
                {
1147
557
                    ExpectedKeySize("Output Taproot Tree Key", key, 1);
1148
557
                    std::vector<unsigned char> tree_v;
1149
557
                    s >> tree_v;
1150
557
                    SpanReader s_tree{tree_v};
1151
557
                    if (s_tree.empty()) {
1152
1
                        throw std::ios_base::failure("Output Taproot tree must not be empty");
1153
1
                    }
1154
556
                    TaprootBuilder builder;
1155
1.78k
                    while (!s_tree.empty()) {
1156
1.22k
                        uint8_t depth;
1157
1.22k
                        uint8_t leaf_ver;
1158
1.22k
                        std::vector<unsigned char> script;
1159
1.22k
                        s_tree >> depth;
1160
1.22k
                        s_tree >> leaf_ver;
1161
1.22k
                        s_tree >> script;
1162
1.22k
                        if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1163
0
                            throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
1164
0
                        }
1165
1.22k
                        if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
1166
0
                            throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
1167
0
                        }
1168
1.22k
                        m_tap_tree.emplace_back(depth, leaf_ver, script);
1169
1.22k
                        builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
1170
1.22k
                    }
1171
556
                    if (!builder.IsComplete()) {
1172
0
                        throw std::ios_base::failure("Output Taproot tree is malformed");
1173
0
                    }
1174
556
                    break;
1175
556
                }
1176
2.94k
                case PSBT_OUT_TAP_BIP32_DERIVATION:
1177
2.94k
                {
1178
2.94k
                    ExpectedKeySize("Output Taproot BIP32 Keypath", key, 33);
1179
2.94k
                    XOnlyPubKey xonly(uint256(std::span<uint8_t>(key).last(32)));
1180
2.94k
                    std::set<uint256> leaf_hashes;
1181
2.94k
                    uint64_t value_len = ReadCompactSize(s);
1182
2.94k
                    size_t before_hashes = s.size();
1183
2.94k
                    s >> leaf_hashes;
1184
2.94k
                    size_t after_hashes = s.size();
1185
2.94k
                    size_t hashes_len = before_hashes - after_hashes;
1186
2.94k
                    if (hashes_len > value_len) {
1187
0
                        throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
1188
0
                    }
1189
2.94k
                    size_t origin_len = value_len - hashes_len;
1190
2.94k
                    m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
1191
2.94k
                    break;
1192
2.94k
                }
1193
457
                case PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS:
1194
457
                {
1195
457
                    ExpectedKeySize("Output MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
1196
457
                    DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Output"});
1197
457
                    break;
1198
2.94k
                }
1199
1
                case PSBT_OUT_PROPRIETARY:
1200
1
                {
1201
1
                    PSBTProprietary this_prop;
1202
1
                    skey >> this_prop.identifier;
1203
1
                    this_prop.subtype = ReadCompactSize(skey);
1204
1
                    this_prop.key = key;
1205
1206
1
                    s >> this_prop.value;
1207
1
                    m_proprietary.insert(this_prop);
1208
1
                    break;
1209
2.94k
                }
1210
                // Unknown stuff
1211
0
                default: {
1212
                    // Read in the value
1213
0
                    std::vector<unsigned char> val_bytes;
1214
0
                    s >> val_bytes;
1215
0
                    unknown.emplace(std::move(key), std::move(val_bytes));
1216
0
                    break;
1217
2.94k
                }
1218
9.62k
            }
1219
9.62k
        }
1220
1221
2.37k
        if (!found_sep) {
1222
0
            throw std::ios_base::failure("Separator is missing at the end of an output map");
1223
0
        }
1224
1225
        // Make sure required PSBTv2 fields are present
1226
2.37k
        if (m_psbt_version >= 2) {
1227
2.24k
            if (!found_amount) {
1228
1
                throw std::ios_base::failure("Output amount is required in PSBTv2");
1229
1
            }
1230
2.24k
            if (!found_script) {
1231
1
                throw std::ios_base::failure("Output script is required in PSBTv2");
1232
1
            }
1233
2.24k
        }
1234
2.37k
    }
1235
};
1236
1237
/** A version of CTransaction with the PSBT format*/
1238
class PartiallySignedTransaction
1239
{
1240
private:
1241
    std::optional<uint32_t> m_version;
1242
1243
public:
1244
    // We use a vector of CExtPubKey in the event that there happens to be the same KeyOriginInfos for different CExtPubKeys
1245
    // Note that this map swaps the key and values from the serialization
1246
    std::map<KeyOriginInfo, std::set<CExtPubKey>> m_xpubs;
1247
    std::optional<std::bitset<8>> m_tx_modifiable;
1248
    std::vector<PSBTInput> inputs;
1249
    std::vector<PSBTOutput> outputs;
1250
    std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
1251
    std::set<PSBTProprietary> m_proprietary;
1252
1253
    uint32_t tx_version;
1254
    std::optional<uint32_t> fallback_locktime;
1255
1256
    bool IsNull() const;
1257
    uint32_t GetVersion() const;
1258
1259
    /** Merge psbt into this. The two psbts must have the same underlying CTransaction (i.e. the
1260
      * same actual Bitcoin transaction.) Returns true if the merge succeeded, false otherwise. */
1261
    [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
1262
    bool AddInput(const PSBTInput& psbtin);
1263
    bool AddOutput(const PSBTOutput& psbtout);
1264
    std::optional<uint32_t> ComputeTimeLock() const;
1265
    std::optional<CMutableTransaction> GetUnsignedTx() const;
1266
    std::optional<Txid> GetUniqueID() const;
1267
    explicit PartiallySignedTransaction(const CMutableTransaction& tx, uint32_t version = 2);
1268
1269
    template <typename Stream>
1270
891
    inline void Serialize(Stream& s) const {
1271
1272
        // magic bytes
1273
891
        s << PSBT_MAGIC_BYTES;
1274
1275
891
        if (GetVersion() < 2) {
1276
            // unsigned tx flag
1277
36
            SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_UNSIGNED_TX));
1278
1279
            // Write serialized tx to a stream
1280
36
            SerializeToVector(s, TX_NO_WITNESS(*GetUnsignedTx()));
1281
36
        }
1282
1283
        // Write xpubs
1284
891
        for (const auto& xpub_pair : m_xpubs) {
1285
0
            for (const auto& xpub : xpub_pair.second) {
1286
0
                unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
1287
0
                xpub.EncodeWithVersion(ser_xpub);
1288
                // Note that the serialization swaps the key and value
1289
                // The xpub is the key (for uniqueness) while the path is the value
1290
0
                SerializeToVector(s, PSBT_GLOBAL_XPUB, ser_xpub);
1291
0
                SerializeHDKeypath(s, xpub_pair.first);
1292
0
            }
1293
0
        }
1294
1295
891
        if (GetVersion() >= 2) {
1296
            // Write PSBTv2 tx version, locktime, counts, etc.
1297
855
            SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_TX_VERSION));
1298
855
            SerializeToVector(s, tx_version);
1299
855
            if (fallback_locktime != std::nullopt) {
1300
855
                SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_FALLBACK_LOCKTIME));
1301
855
                SerializeToVector(s, *fallback_locktime);
1302
855
            }
1303
1304
855
            SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_INPUT_COUNT));
1305
855
            SerializeToVector(s, CompactSizeWriter(inputs.size()));
1306
855
            SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_OUTPUT_COUNT));
1307
855
            SerializeToVector(s, CompactSizeWriter(outputs.size()));
1308
1309
855
            if (m_tx_modifiable != std::nullopt) {
1310
0
                SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_TX_MODIFIABLE));
1311
0
                SerializeToVector(s, static_cast<uint8_t>(m_tx_modifiable->to_ulong()));
1312
0
            }
1313
855
        }
1314
1315
        // PSBT version
1316
891
        if (GetVersion() > 0) {
1317
855
            SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_VERSION));
1318
855
            SerializeToVector(s, *m_version);
1319
855
        }
1320
1321
        // Write proprietary things
1322
891
        for (const auto& entry : m_proprietary) {
1323
2
            s << entry.key;
1324
2
            s << entry.value;
1325
2
        }
1326
1327
        // Write the unknown things
1328
891
        for (auto& entry : unknown) {
1329
0
            s << entry.first;
1330
0
            s << entry.second;
1331
0
        }
1332
1333
        // Separator
1334
891
        s << PSBT_SEPARATOR;
1335
1336
        // Write inputs
1337
1.28k
        for (const PSBTInput& input : inputs) {
1338
1.28k
            s << input;
1339
1.28k
        }
1340
        // Write outputs
1341
1.93k
        for (const PSBTOutput& output : outputs) {
1342
1.93k
            s << output;
1343
1.93k
        }
1344
891
    }
1345
1346
1347
    template <typename Stream>
1348
1.40k
    inline void Unserialize(Stream& s) {
1349
        // Read the magic bytes
1350
1.40k
        uint8_t magic[5];
1351
1.40k
        s >> magic;
1352
1.40k
        if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
1353
2
            throw std::ios_base::failure("Invalid PSBT magic bytes");
1354
2
        }
1355
1356
        // Used for duplicate key detection
1357
1.39k
        std::set<std::vector<unsigned char>> key_lookup;
1358
1359
        // Track the global xpubs we have already seen. Just for sanity checking
1360
1.39k
        std::set<CExtPubKey> global_xpubs;
1361
1362
        // Read global data
1363
1.39k
        bool found_sep = false;
1364
1.39k
        std::optional<CMutableTransaction> tx;
1365
1.39k
        uint64_t input_count = 0;
1366
1.39k
        uint64_t output_count = 0;
1367
1.39k
        bool found_input_count = false;
1368
1.39k
        bool found_output_count = false;
1369
1.39k
        bool found_tx_version = false;
1370
1.39k
        bool found_fallback_locktime = false;
1371
7.74k
        while(!s.empty()) {
1372
            // Read the key of format "<keylen><keytype><keydata>" after which
1373
            // "key" will contain "<keytype><keydata>"
1374
7.74k
            std::vector<unsigned char> key;
1375
7.74k
            s >> key;
1376
1377
            // the key is empty if that was actually a separator byte
1378
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
1379
7.74k
            if (key.empty()) {
1380
1.39k
                found_sep = true;
1381
1.39k
                break;
1382
1.39k
            }
1383
1384
            // Duplicate keys are not permitted
1385
6.34k
            if (!key_lookup.emplace(key).second) {
1386
0
                throw std::ios_base::failure(tfm::format("Duplicate Key, global key \"%s\" already provided", HexStr(key)));
1387
0
            }
1388
1389
            // "skey" is used so that "key" is unchanged after reading keytype below
1390
6.34k
            SpanReader skey{key};
1391
            // keytype is of the format compact size uint at the beginning of "key"
1392
6.34k
            uint64_t type = ReadCompactSize(skey);
1393
1394
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
1395
            // format "<valuelen><valuedata>" from the stream "s", and value checks
1396
6.34k
            switch(type) {
1397
163
                case PSBT_GLOBAL_UNSIGNED_TX:
1398
163
                {
1399
163
                    ExpectedKeySize("Global Unsigned TX", key, 1);
1400
                    // Set the stream to serialize with non-witness since this should always be non-witness
1401
163
                    tx.emplace();
1402
163
                    UnserializeFromVector(s, TX_NO_WITNESS(*tx));
1403
                    // Make sure that all scriptSigs and scriptWitnesses are empty
1404
205
                    for (const CTxIn& txin : tx->vin) {
1405
205
                        if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
1406
1
                            throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
1407
1
                        }
1408
205
                    }
1409
162
                    tx_version = tx->version;
1410
162
                    fallback_locktime = tx->nLockTime;
1411
                    // Set the input and output counts
1412
162
                    input_count = tx->vin.size();
1413
162
                    output_count = tx->vout.size();
1414
162
                    break;
1415
163
                }
1416
1.23k
                case PSBT_GLOBAL_TX_VERSION:
1417
1.23k
                {
1418
1.23k
                    ExpectedKeySize("Global Transaction Version", key, 1);
1419
1.23k
                    UnserializeFromVector(s, tx_version);
1420
1.23k
                    found_tx_version = true;
1421
1.23k
                    break;
1422
163
                }
1423
1.21k
                case PSBT_GLOBAL_FALLBACK_LOCKTIME:
1424
1.21k
                {
1425
1.21k
                    ExpectedKeySize("Global Fallback Locktime", key, 1);
1426
1.21k
                    fallback_locktime.emplace();
1427
1.21k
                    UnserializeFromVector(s, *fallback_locktime);
1428
1.21k
                    found_fallback_locktime = true;
1429
1.21k
                    break;
1430
163
                }
1431
1.23k
                case PSBT_GLOBAL_INPUT_COUNT:
1432
1.23k
                {
1433
1.23k
                    ExpectedKeySize("Global Input Count", key, 1);
1434
1.23k
                    CompactSizeReader reader(input_count);
1435
1.23k
                    UnserializeFromVector(s, reader);
1436
1.23k
                    found_input_count = true;
1437
1.23k
                    break;
1438
163
                }
1439
1.23k
                case PSBT_GLOBAL_OUTPUT_COUNT:
1440
1.23k
                {
1441
1.23k
                    ExpectedKeySize("Global Output Count", key, 1);
1442
1.23k
                    CompactSizeReader reader(output_count);
1443
1.23k
                    UnserializeFromVector(s, reader);
1444
1.23k
                    found_output_count = true;
1445
1.23k
                    break;
1446
163
                }
1447
13
                case PSBT_GLOBAL_TX_MODIFIABLE:
1448
13
                {
1449
13
                    ExpectedKeySize("Global TX Modifiable Flags", key, 1);
1450
13
                    uint8_t tx_mod;
1451
13
                    UnserializeFromVector(s, tx_mod);
1452
13
                    m_tx_modifiable.emplace(tx_mod);
1453
13
                    break;
1454
163
                }
1455
3
                case PSBT_GLOBAL_XPUB:
1456
3
                {
1457
3
                    ExpectedKeySize("Global XPUB", key, BIP32_EXTKEY_WITH_VERSION_SIZE + 1);
1458
                    // Read in the xpub from key
1459
3
                    CExtPubKey xpub;
1460
3
                    xpub.DecodeWithVersion(&key.data()[1]);
1461
3
                    if (!xpub.pubkey.IsFullyValid()) {
1462
0
                       throw std::ios_base::failure("Invalid pubkey");
1463
0
                    }
1464
3
                    global_xpubs.insert(xpub);
1465
                    // Read in the keypath from stream
1466
3
                    KeyOriginInfo keypath;
1467
3
                    DeserializeHDKeypath(s, keypath);
1468
1469
                    // Note that we store these swapped to make searches faster.
1470
                    // Serialization uses xpub -> keypath to enqure key uniqueness
1471
3
                    if (!m_xpubs.contains(keypath)) {
1472
                        // Make a new set to put the xpub in
1473
3
                        m_xpubs[keypath] = {xpub};
1474
3
                    } else {
1475
                        // Insert xpub into existing set
1476
0
                        m_xpubs[keypath].insert(xpub);
1477
0
                    }
1478
3
                    break;
1479
3
                }
1480
1.23k
                case PSBT_GLOBAL_VERSION:
1481
1.23k
                {
1482
1.23k
                    ExpectedKeySize("Global PSBT Version", key, 1);
1483
1.23k
                    uint32_t v;
1484
1.23k
                    UnserializeFromVector(s, v);
1485
1.23k
                    m_version = v;
1486
1.23k
                    if (*m_version > PSBT_HIGHEST_VERSION) {
1487
0
                        throw std::ios_base::failure("Unsupported version number");
1488
0
                    }
1489
1.23k
                    break;
1490
1.23k
                }
1491
1.23k
                case PSBT_GLOBAL_PROPRIETARY:
1492
4
                {
1493
4
                    PSBTProprietary this_prop;
1494
4
                    skey >> this_prop.identifier;
1495
4
                    this_prop.subtype = ReadCompactSize(skey);
1496
4
                    this_prop.key = key;
1497
1498
4
                    s >> this_prop.value;
1499
4
                    m_proprietary.insert(this_prop);
1500
4
                    break;
1501
1.23k
                }
1502
                // Unknown stuff
1503
0
                default: {
1504
                    // Read in the value
1505
0
                    std::vector<unsigned char> val_bytes;
1506
0
                    s >> val_bytes;
1507
0
                    unknown.emplace(std::move(key), std::move(val_bytes));
1508
0
                }
1509
6.34k
            }
1510
6.34k
        }
1511
1512
1.39k
        if (!found_sep) {
1513
0
            throw std::ios_base::failure("Separator is missing at the end of the global map");
1514
0
        }
1515
1516
1.39k
        const uint32_t psbt_ver = GetVersion();
1517
1518
        // Check PSBT version constraints
1519
1.39k
        if (psbt_ver == 0) {
1520
            // Make sure that we got an unsigned tx for PSBTv0
1521
159
            if (!tx) {
1522
1
                throw std::ios_base::failure("No unsigned transaction was provided");
1523
1
            }
1524
            // Make sure no PSBTv2 fields are present
1525
158
            if (found_tx_version) {
1526
1
                throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is not allowed in PSBTv0");
1527
1
            }
1528
157
            if (found_fallback_locktime) {
1529
0
                throw std::ios_base::failure("PSBT_GLOBAL_FALLBACK_LOCKTIME is not allowed in PSBTv0");
1530
0
            }
1531
157
            if (found_input_count) {
1532
1
                throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is not allowed in PSBTv0");
1533
1
            }
1534
156
            if (found_output_count) {
1535
1
                throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is not allowed in PSBTv0");
1536
1
            }
1537
155
            if (m_tx_modifiable != std::nullopt) {
1538
1
                throw std::ios_base::failure("PSBT_GLOBAL_TX_MODIFIABLE is not allowed in PSBTv0");
1539
1
            }
1540
155
        }
1541
        // Disallow v1
1542
1.39k
        if (psbt_ver == 1) {
1543
1
            throw std::ios_base::failure("There is no PSBT version 1");
1544
1
        }
1545
1.39k
        if (psbt_ver == 2) {
1546
            // Tx version, input, and output counts are required
1547
1.23k
            if (!found_tx_version) {
1548
2
                throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is required in PSBTv2");
1549
2
            }
1550
1.23k
            if (!found_input_count) {
1551
1
                throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is required in PSBTv2");
1552
1
            }
1553
1.23k
            if (!found_output_count) {
1554
1
                throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is required in PSBTv2");
1555
1
            }
1556
            // Unsigned tx is disallowed
1557
1.23k
            if (tx) {
1558
1
                throw std::ios_base::failure("PSBT_GLOBAL_UNSIGNED_TX is not allowed in PSBTv2");
1559
1
            }
1560
1.23k
        }
1561
1.38k
        if (psbt_ver > 2) {
1562
0
            throw std::ios_base::failure("Unknown PSBT version");
1563
0
        }
1564
1565
        // Read input data
1566
1.38k
        unsigned int i = 0;
1567
3.05k
        while (!s.empty() && i < input_count) {
1568
1.67k
            if (psbt_ver < 2) {
1569
189
                inputs.emplace_back(psbt_ver, tx->vin[i].prevout.hash, tx->vin[i].prevout.n, tx->vin[i].nSequence);
1570
189
                s >> inputs.back();
1571
1.48k
            } else {
1572
1.48k
                inputs.emplace_back(deserialize, s, psbt_ver);
1573
1.48k
            }
1574
1575
            // Make sure the non-witness utxo matches the outpoint
1576
1.67k
            const PSBTInput& input = inputs.back();
1577
1.67k
            if (input.non_witness_utxo) {
1578
409
                if (psbt_ver < 2) {
1579
45
                    if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
1580
1
                        throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1581
1
                    }
1582
44
                    if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
1583
3
                        throw std::ios_base::failure("Input specifies output index that does not exist");
1584
3
                    }
1585
364
                } else {
1586
364
                    if (input.non_witness_utxo->GetHash() != input.prev_txid) {
1587
0
                        throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1588
0
                    }
1589
364
                    if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1590
0
                        throw std::ios_base::failure("Input specifies output index that does not exist");
1591
0
                    }
1592
364
                }
1593
409
            }
1594
1.66k
            ++i;
1595
1.66k
        }
1596
        // Make sure that the number of inputs matches the number of inputs in the transaction
1597
1.38k
        if (inputs.size() != input_count) {
1598
0
            throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
1599
0
        }
1600
1601
        // Read output data
1602
1.38k
        i = 0;
1603
3.77k
        while (!s.empty() && i < output_count) {
1604
2.39k
            if (psbt_ver < 2) {
1605
147
                outputs.emplace_back(psbt_ver, tx->vout[i].nValue, tx->vout[i].scriptPubKey);
1606
147
                s >> outputs.back();
1607
2.24k
            } else {
1608
2.24k
                outputs.emplace_back(deserialize, s, psbt_ver);
1609
2.24k
            }
1610
2.39k
            ++i;
1611
2.39k
        }
1612
        // Make sure that the number of outputs matches the number of outputs in the transaction
1613
1.38k
        if (outputs.size() != output_count) {
1614
1
            throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
1615
1
        }
1616
1.38k
    }
void PartiallySignedTransaction::Unserialize<DataStream>(DataStream&)
Line
Count
Source
1348
1
    inline void Unserialize(Stream& s) {
1349
        // Read the magic bytes
1350
1
        uint8_t magic[5];
1351
1
        s >> magic;
1352
1
        if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
1353
0
            throw std::ios_base::failure("Invalid PSBT magic bytes");
1354
0
        }
1355
1356
        // Used for duplicate key detection
1357
1
        std::set<std::vector<unsigned char>> key_lookup;
1358
1359
        // Track the global xpubs we have already seen. Just for sanity checking
1360
1
        std::set<CExtPubKey> global_xpubs;
1361
1362
        // Read global data
1363
1
        bool found_sep = false;
1364
1
        std::optional<CMutableTransaction> tx;
1365
1
        uint64_t input_count = 0;
1366
1
        uint64_t output_count = 0;
1367
1
        bool found_input_count = false;
1368
1
        bool found_output_count = false;
1369
1
        bool found_tx_version = false;
1370
1
        bool found_fallback_locktime = false;
1371
2
        while(!s.empty()) {
1372
            // Read the key of format "<keylen><keytype><keydata>" after which
1373
            // "key" will contain "<keytype><keydata>"
1374
2
            std::vector<unsigned char> key;
1375
2
            s >> key;
1376
1377
            // the key is empty if that was actually a separator byte
1378
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
1379
2
            if (key.empty()) {
1380
1
                found_sep = true;
1381
1
                break;
1382
1
            }
1383
1384
            // Duplicate keys are not permitted
1385
1
            if (!key_lookup.emplace(key).second) {
1386
0
                throw std::ios_base::failure(tfm::format("Duplicate Key, global key \"%s\" already provided", HexStr(key)));
1387
0
            }
1388
1389
            // "skey" is used so that "key" is unchanged after reading keytype below
1390
1
            SpanReader skey{key};
1391
            // keytype is of the format compact size uint at the beginning of "key"
1392
1
            uint64_t type = ReadCompactSize(skey);
1393
1394
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
1395
            // format "<valuelen><valuedata>" from the stream "s", and value checks
1396
1
            switch(type) {
1397
1
                case PSBT_GLOBAL_UNSIGNED_TX:
1398
1
                {
1399
1
                    ExpectedKeySize("Global Unsigned TX", key, 1);
1400
                    // Set the stream to serialize with non-witness since this should always be non-witness
1401
1
                    tx.emplace();
1402
1
                    UnserializeFromVector(s, TX_NO_WITNESS(*tx));
1403
                    // Make sure that all scriptSigs and scriptWitnesses are empty
1404
2
                    for (const CTxIn& txin : tx->vin) {
1405
2
                        if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
1406
0
                            throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
1407
0
                        }
1408
2
                    }
1409
1
                    tx_version = tx->version;
1410
1
                    fallback_locktime = tx->nLockTime;
1411
                    // Set the input and output counts
1412
1
                    input_count = tx->vin.size();
1413
1
                    output_count = tx->vout.size();
1414
1
                    break;
1415
1
                }
1416
0
                case PSBT_GLOBAL_TX_VERSION:
1417
0
                {
1418
0
                    ExpectedKeySize("Global Transaction Version", key, 1);
1419
0
                    UnserializeFromVector(s, tx_version);
1420
0
                    found_tx_version = true;
1421
0
                    break;
1422
1
                }
1423
0
                case PSBT_GLOBAL_FALLBACK_LOCKTIME:
1424
0
                {
1425
0
                    ExpectedKeySize("Global Fallback Locktime", key, 1);
1426
0
                    fallback_locktime.emplace();
1427
0
                    UnserializeFromVector(s, *fallback_locktime);
1428
0
                    found_fallback_locktime = true;
1429
0
                    break;
1430
1
                }
1431
0
                case PSBT_GLOBAL_INPUT_COUNT:
1432
0
                {
1433
0
                    ExpectedKeySize("Global Input Count", key, 1);
1434
0
                    CompactSizeReader reader(input_count);
1435
0
                    UnserializeFromVector(s, reader);
1436
0
                    found_input_count = true;
1437
0
                    break;
1438
1
                }
1439
0
                case PSBT_GLOBAL_OUTPUT_COUNT:
1440
0
                {
1441
0
                    ExpectedKeySize("Global Output Count", key, 1);
1442
0
                    CompactSizeReader reader(output_count);
1443
0
                    UnserializeFromVector(s, reader);
1444
0
                    found_output_count = true;
1445
0
                    break;
1446
1
                }
1447
0
                case PSBT_GLOBAL_TX_MODIFIABLE:
1448
0
                {
1449
0
                    ExpectedKeySize("Global TX Modifiable Flags", key, 1);
1450
0
                    uint8_t tx_mod;
1451
0
                    UnserializeFromVector(s, tx_mod);
1452
0
                    m_tx_modifiable.emplace(tx_mod);
1453
0
                    break;
1454
1
                }
1455
0
                case PSBT_GLOBAL_XPUB:
1456
0
                {
1457
0
                    ExpectedKeySize("Global XPUB", key, BIP32_EXTKEY_WITH_VERSION_SIZE + 1);
1458
                    // Read in the xpub from key
1459
0
                    CExtPubKey xpub;
1460
0
                    xpub.DecodeWithVersion(&key.data()[1]);
1461
0
                    if (!xpub.pubkey.IsFullyValid()) {
1462
0
                       throw std::ios_base::failure("Invalid pubkey");
1463
0
                    }
1464
0
                    global_xpubs.insert(xpub);
1465
                    // Read in the keypath from stream
1466
0
                    KeyOriginInfo keypath;
1467
0
                    DeserializeHDKeypath(s, keypath);
1468
1469
                    // Note that we store these swapped to make searches faster.
1470
                    // Serialization uses xpub -> keypath to enqure key uniqueness
1471
0
                    if (!m_xpubs.contains(keypath)) {
1472
                        // Make a new set to put the xpub in
1473
0
                        m_xpubs[keypath] = {xpub};
1474
0
                    } else {
1475
                        // Insert xpub into existing set
1476
0
                        m_xpubs[keypath].insert(xpub);
1477
0
                    }
1478
0
                    break;
1479
0
                }
1480
0
                case PSBT_GLOBAL_VERSION:
1481
0
                {
1482
0
                    ExpectedKeySize("Global PSBT Version", key, 1);
1483
0
                    uint32_t v;
1484
0
                    UnserializeFromVector(s, v);
1485
0
                    m_version = v;
1486
0
                    if (*m_version > PSBT_HIGHEST_VERSION) {
1487
0
                        throw std::ios_base::failure("Unsupported version number");
1488
0
                    }
1489
0
                    break;
1490
0
                }
1491
0
                case PSBT_GLOBAL_PROPRIETARY:
1492
0
                {
1493
0
                    PSBTProprietary this_prop;
1494
0
                    skey >> this_prop.identifier;
1495
0
                    this_prop.subtype = ReadCompactSize(skey);
1496
0
                    this_prop.key = key;
1497
1498
0
                    s >> this_prop.value;
1499
0
                    m_proprietary.insert(this_prop);
1500
0
                    break;
1501
0
                }
1502
                // Unknown stuff
1503
0
                default: {
1504
                    // Read in the value
1505
0
                    std::vector<unsigned char> val_bytes;
1506
0
                    s >> val_bytes;
1507
0
                    unknown.emplace(std::move(key), std::move(val_bytes));
1508
0
                }
1509
1
            }
1510
1
        }
1511
1512
1
        if (!found_sep) {
1513
0
            throw std::ios_base::failure("Separator is missing at the end of the global map");
1514
0
        }
1515
1516
1
        const uint32_t psbt_ver = GetVersion();
1517
1518
        // Check PSBT version constraints
1519
1
        if (psbt_ver == 0) {
1520
            // Make sure that we got an unsigned tx for PSBTv0
1521
1
            if (!tx) {
1522
0
                throw std::ios_base::failure("No unsigned transaction was provided");
1523
0
            }
1524
            // Make sure no PSBTv2 fields are present
1525
1
            if (found_tx_version) {
1526
0
                throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is not allowed in PSBTv0");
1527
0
            }
1528
1
            if (found_fallback_locktime) {
1529
0
                throw std::ios_base::failure("PSBT_GLOBAL_FALLBACK_LOCKTIME is not allowed in PSBTv0");
1530
0
            }
1531
1
            if (found_input_count) {
1532
0
                throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is not allowed in PSBTv0");
1533
0
            }
1534
1
            if (found_output_count) {
1535
0
                throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is not allowed in PSBTv0");
1536
0
            }
1537
1
            if (m_tx_modifiable != std::nullopt) {
1538
0
                throw std::ios_base::failure("PSBT_GLOBAL_TX_MODIFIABLE is not allowed in PSBTv0");
1539
0
            }
1540
1
        }
1541
        // Disallow v1
1542
1
        if (psbt_ver == 1) {
1543
0
            throw std::ios_base::failure("There is no PSBT version 1");
1544
0
        }
1545
1
        if (psbt_ver == 2) {
1546
            // Tx version, input, and output counts are required
1547
0
            if (!found_tx_version) {
1548
0
                throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is required in PSBTv2");
1549
0
            }
1550
0
            if (!found_input_count) {
1551
0
                throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is required in PSBTv2");
1552
0
            }
1553
0
            if (!found_output_count) {
1554
0
                throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is required in PSBTv2");
1555
0
            }
1556
            // Unsigned tx is disallowed
1557
0
            if (tx) {
1558
0
                throw std::ios_base::failure("PSBT_GLOBAL_UNSIGNED_TX is not allowed in PSBTv2");
1559
0
            }
1560
0
        }
1561
1
        if (psbt_ver > 2) {
1562
0
            throw std::ios_base::failure("Unknown PSBT version");
1563
0
        }
1564
1565
        // Read input data
1566
1
        unsigned int i = 0;
1567
3
        while (!s.empty() && i < input_count) {
1568
2
            if (psbt_ver < 2) {
1569
2
                inputs.emplace_back(psbt_ver, tx->vin[i].prevout.hash, tx->vin[i].prevout.n, tx->vin[i].nSequence);
1570
2
                s >> inputs.back();
1571
2
            } else {
1572
0
                inputs.emplace_back(deserialize, s, psbt_ver);
1573
0
            }
1574
1575
            // Make sure the non-witness utxo matches the outpoint
1576
2
            const PSBTInput& input = inputs.back();
1577
2
            if (input.non_witness_utxo) {
1578
0
                if (psbt_ver < 2) {
1579
0
                    if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
1580
0
                        throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1581
0
                    }
1582
0
                    if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
1583
0
                        throw std::ios_base::failure("Input specifies output index that does not exist");
1584
0
                    }
1585
0
                } else {
1586
0
                    if (input.non_witness_utxo->GetHash() != input.prev_txid) {
1587
0
                        throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1588
0
                    }
1589
0
                    if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1590
0
                        throw std::ios_base::failure("Input specifies output index that does not exist");
1591
0
                    }
1592
0
                }
1593
0
            }
1594
2
            ++i;
1595
2
        }
1596
        // Make sure that the number of inputs matches the number of inputs in the transaction
1597
1
        if (inputs.size() != input_count) {
1598
0
            throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
1599
0
        }
1600
1601
        // Read output data
1602
1
        i = 0;
1603
3
        while (!s.empty() && i < output_count) {
1604
2
            if (psbt_ver < 2) {
1605
2
                outputs.emplace_back(psbt_ver, tx->vout[i].nValue, tx->vout[i].scriptPubKey);
1606
2
                s >> outputs.back();
1607
2
            } else {
1608
0
                outputs.emplace_back(deserialize, s, psbt_ver);
1609
0
            }
1610
2
            ++i;
1611
2
        }
1612
        // Make sure that the number of outputs matches the number of outputs in the transaction
1613
1
        if (outputs.size() != output_count) {
1614
0
            throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
1615
0
        }
1616
1
    }
void PartiallySignedTransaction::Unserialize<SpanReader>(SpanReader&)
Line
Count
Source
1348
1.39k
    inline void Unserialize(Stream& s) {
1349
        // Read the magic bytes
1350
1.39k
        uint8_t magic[5];
1351
1.39k
        s >> magic;
1352
1.39k
        if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
1353
2
            throw std::ios_base::failure("Invalid PSBT magic bytes");
1354
2
        }
1355
1356
        // Used for duplicate key detection
1357
1.39k
        std::set<std::vector<unsigned char>> key_lookup;
1358
1359
        // Track the global xpubs we have already seen. Just for sanity checking
1360
1.39k
        std::set<CExtPubKey> global_xpubs;
1361
1362
        // Read global data
1363
1.39k
        bool found_sep = false;
1364
1.39k
        std::optional<CMutableTransaction> tx;
1365
1.39k
        uint64_t input_count = 0;
1366
1.39k
        uint64_t output_count = 0;
1367
1.39k
        bool found_input_count = false;
1368
1.39k
        bool found_output_count = false;
1369
1.39k
        bool found_tx_version = false;
1370
1.39k
        bool found_fallback_locktime = false;
1371
7.73k
        while(!s.empty()) {
1372
            // Read the key of format "<keylen><keytype><keydata>" after which
1373
            // "key" will contain "<keytype><keydata>"
1374
7.73k
            std::vector<unsigned char> key;
1375
7.73k
            s >> key;
1376
1377
            // the key is empty if that was actually a separator byte
1378
            // This is a special case for key lengths 0 as those are not allowed (except for separator)
1379
7.73k
            if (key.empty()) {
1380
1.39k
                found_sep = true;
1381
1.39k
                break;
1382
1.39k
            }
1383
1384
            // Duplicate keys are not permitted
1385
6.34k
            if (!key_lookup.emplace(key).second) {
1386
0
                throw std::ios_base::failure(tfm::format("Duplicate Key, global key \"%s\" already provided", HexStr(key)));
1387
0
            }
1388
1389
            // "skey" is used so that "key" is unchanged after reading keytype below
1390
6.34k
            SpanReader skey{key};
1391
            // keytype is of the format compact size uint at the beginning of "key"
1392
6.34k
            uint64_t type = ReadCompactSize(skey);
1393
1394
            // Do stuff based on keytype "type", i.e., key checks, reading values of the
1395
            // format "<valuelen><valuedata>" from the stream "s", and value checks
1396
6.34k
            switch(type) {
1397
162
                case PSBT_GLOBAL_UNSIGNED_TX:
1398
162
                {
1399
162
                    ExpectedKeySize("Global Unsigned TX", key, 1);
1400
                    // Set the stream to serialize with non-witness since this should always be non-witness
1401
162
                    tx.emplace();
1402
162
                    UnserializeFromVector(s, TX_NO_WITNESS(*tx));
1403
                    // Make sure that all scriptSigs and scriptWitnesses are empty
1404
203
                    for (const CTxIn& txin : tx->vin) {
1405
203
                        if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
1406
1
                            throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
1407
1
                        }
1408
203
                    }
1409
161
                    tx_version = tx->version;
1410
161
                    fallback_locktime = tx->nLockTime;
1411
                    // Set the input and output counts
1412
161
                    input_count = tx->vin.size();
1413
161
                    output_count = tx->vout.size();
1414
161
                    break;
1415
162
                }
1416
1.23k
                case PSBT_GLOBAL_TX_VERSION:
1417
1.23k
                {
1418
1.23k
                    ExpectedKeySize("Global Transaction Version", key, 1);
1419
1.23k
                    UnserializeFromVector(s, tx_version);
1420
1.23k
                    found_tx_version = true;
1421
1.23k
                    break;
1422
162
                }
1423
1.21k
                case PSBT_GLOBAL_FALLBACK_LOCKTIME:
1424
1.21k
                {
1425
1.21k
                    ExpectedKeySize("Global Fallback Locktime", key, 1);
1426
1.21k
                    fallback_locktime.emplace();
1427
1.21k
                    UnserializeFromVector(s, *fallback_locktime);
1428
1.21k
                    found_fallback_locktime = true;
1429
1.21k
                    break;
1430
162
                }
1431
1.23k
                case PSBT_GLOBAL_INPUT_COUNT:
1432
1.23k
                {
1433
1.23k
                    ExpectedKeySize("Global Input Count", key, 1);
1434
1.23k
                    CompactSizeReader reader(input_count);
1435
1.23k
                    UnserializeFromVector(s, reader);
1436
1.23k
                    found_input_count = true;
1437
1.23k
                    break;
1438
162
                }
1439
1.23k
                case PSBT_GLOBAL_OUTPUT_COUNT:
1440
1.23k
                {
1441
1.23k
                    ExpectedKeySize("Global Output Count", key, 1);
1442
1.23k
                    CompactSizeReader reader(output_count);
1443
1.23k
                    UnserializeFromVector(s, reader);
1444
1.23k
                    found_output_count = true;
1445
1.23k
                    break;
1446
162
                }
1447
13
                case PSBT_GLOBAL_TX_MODIFIABLE:
1448
13
                {
1449
13
                    ExpectedKeySize("Global TX Modifiable Flags", key, 1);
1450
13
                    uint8_t tx_mod;
1451
13
                    UnserializeFromVector(s, tx_mod);
1452
13
                    m_tx_modifiable.emplace(tx_mod);
1453
13
                    break;
1454
162
                }
1455
3
                case PSBT_GLOBAL_XPUB:
1456
3
                {
1457
3
                    ExpectedKeySize("Global XPUB", key, BIP32_EXTKEY_WITH_VERSION_SIZE + 1);
1458
                    // Read in the xpub from key
1459
3
                    CExtPubKey xpub;
1460
3
                    xpub.DecodeWithVersion(&key.data()[1]);
1461
3
                    if (!xpub.pubkey.IsFullyValid()) {
1462
0
                       throw std::ios_base::failure("Invalid pubkey");
1463
0
                    }
1464
3
                    global_xpubs.insert(xpub);
1465
                    // Read in the keypath from stream
1466
3
                    KeyOriginInfo keypath;
1467
3
                    DeserializeHDKeypath(s, keypath);
1468
1469
                    // Note that we store these swapped to make searches faster.
1470
                    // Serialization uses xpub -> keypath to enqure key uniqueness
1471
3
                    if (!m_xpubs.contains(keypath)) {
1472
                        // Make a new set to put the xpub in
1473
3
                        m_xpubs[keypath] = {xpub};
1474
3
                    } else {
1475
                        // Insert xpub into existing set
1476
0
                        m_xpubs[keypath].insert(xpub);
1477
0
                    }
1478
3
                    break;
1479
3
                }
1480
1.23k
                case PSBT_GLOBAL_VERSION:
1481
1.23k
                {
1482
1.23k
                    ExpectedKeySize("Global PSBT Version", key, 1);
1483
1.23k
                    uint32_t v;
1484
1.23k
                    UnserializeFromVector(s, v);
1485
1.23k
                    m_version = v;
1486
1.23k
                    if (*m_version > PSBT_HIGHEST_VERSION) {
1487
0
                        throw std::ios_base::failure("Unsupported version number");
1488
0
                    }
1489
1.23k
                    break;
1490
1.23k
                }
1491
1.23k
                case PSBT_GLOBAL_PROPRIETARY:
1492
4
                {
1493
4
                    PSBTProprietary this_prop;
1494
4
                    skey >> this_prop.identifier;
1495
4
                    this_prop.subtype = ReadCompactSize(skey);
1496
4
                    this_prop.key = key;
1497
1498
4
                    s >> this_prop.value;
1499
4
                    m_proprietary.insert(this_prop);
1500
4
                    break;
1501
1.23k
                }
1502
                // Unknown stuff
1503
0
                default: {
1504
                    // Read in the value
1505
0
                    std::vector<unsigned char> val_bytes;
1506
0
                    s >> val_bytes;
1507
0
                    unknown.emplace(std::move(key), std::move(val_bytes));
1508
0
                }
1509
6.34k
            }
1510
6.34k
        }
1511
1512
1.39k
        if (!found_sep) {
1513
0
            throw std::ios_base::failure("Separator is missing at the end of the global map");
1514
0
        }
1515
1516
1.39k
        const uint32_t psbt_ver = GetVersion();
1517
1518
        // Check PSBT version constraints
1519
1.39k
        if (psbt_ver == 0) {
1520
            // Make sure that we got an unsigned tx for PSBTv0
1521
158
            if (!tx) {
1522
1
                throw std::ios_base::failure("No unsigned transaction was provided");
1523
1
            }
1524
            // Make sure no PSBTv2 fields are present
1525
157
            if (found_tx_version) {
1526
1
                throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is not allowed in PSBTv0");
1527
1
            }
1528
156
            if (found_fallback_locktime) {
1529
0
                throw std::ios_base::failure("PSBT_GLOBAL_FALLBACK_LOCKTIME is not allowed in PSBTv0");
1530
0
            }
1531
156
            if (found_input_count) {
1532
1
                throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is not allowed in PSBTv0");
1533
1
            }
1534
155
            if (found_output_count) {
1535
1
                throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is not allowed in PSBTv0");
1536
1
            }
1537
154
            if (m_tx_modifiable != std::nullopt) {
1538
1
                throw std::ios_base::failure("PSBT_GLOBAL_TX_MODIFIABLE is not allowed in PSBTv0");
1539
1
            }
1540
154
        }
1541
        // Disallow v1
1542
1.39k
        if (psbt_ver == 1) {
1543
1
            throw std::ios_base::failure("There is no PSBT version 1");
1544
1
        }
1545
1.38k
        if (psbt_ver == 2) {
1546
            // Tx version, input, and output counts are required
1547
1.23k
            if (!found_tx_version) {
1548
2
                throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is required in PSBTv2");
1549
2
            }
1550
1.23k
            if (!found_input_count) {
1551
1
                throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is required in PSBTv2");
1552
1
            }
1553
1.23k
            if (!found_output_count) {
1554
1
                throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is required in PSBTv2");
1555
1
            }
1556
            // Unsigned tx is disallowed
1557
1.23k
            if (tx) {
1558
1
                throw std::ios_base::failure("PSBT_GLOBAL_UNSIGNED_TX is not allowed in PSBTv2");
1559
1
            }
1560
1.23k
        }
1561
1.38k
        if (psbt_ver > 2) {
1562
0
            throw std::ios_base::failure("Unknown PSBT version");
1563
0
        }
1564
1565
        // Read input data
1566
1.38k
        unsigned int i = 0;
1567
3.04k
        while (!s.empty() && i < input_count) {
1568
1.66k
            if (psbt_ver < 2) {
1569
187
                inputs.emplace_back(psbt_ver, tx->vin[i].prevout.hash, tx->vin[i].prevout.n, tx->vin[i].nSequence);
1570
187
                s >> inputs.back();
1571
1.48k
            } else {
1572
1.48k
                inputs.emplace_back(deserialize, s, psbt_ver);
1573
1.48k
            }
1574
1575
            // Make sure the non-witness utxo matches the outpoint
1576
1.66k
            const PSBTInput& input = inputs.back();
1577
1.66k
            if (input.non_witness_utxo) {
1578
409
                if (psbt_ver < 2) {
1579
45
                    if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
1580
1
                        throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1581
1
                    }
1582
44
                    if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
1583
3
                        throw std::ios_base::failure("Input specifies output index that does not exist");
1584
3
                    }
1585
364
                } else {
1586
364
                    if (input.non_witness_utxo->GetHash() != input.prev_txid) {
1587
0
                        throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1588
0
                    }
1589
364
                    if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1590
0
                        throw std::ios_base::failure("Input specifies output index that does not exist");
1591
0
                    }
1592
364
                }
1593
409
            }
1594
1.66k
            ++i;
1595
1.66k
        }
1596
        // Make sure that the number of inputs matches the number of inputs in the transaction
1597
1.38k
        if (inputs.size() != input_count) {
1598
0
            throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
1599
0
        }
1600
1601
        // Read output data
1602
1.38k
        i = 0;
1603
3.76k
        while (!s.empty() && i < output_count) {
1604
2.38k
            if (psbt_ver < 2) {
1605
145
                outputs.emplace_back(psbt_ver, tx->vout[i].nValue, tx->vout[i].scriptPubKey);
1606
145
                s >> outputs.back();
1607
2.24k
            } else {
1608
2.24k
                outputs.emplace_back(deserialize, s, psbt_ver);
1609
2.24k
            }
1610
2.38k
            ++i;
1611
2.38k
        }
1612
        // Make sure that the number of outputs matches the number of outputs in the transaction
1613
1.38k
        if (outputs.size() != output_count) {
1614
1
            throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
1615
1
        }
1616
1.38k
    }
1617
1618
    template <typename Stream>
1619
1.40k
    PartiallySignedTransaction(deserialize_type, Stream& s) {
1620
1.40k
        Unserialize(s);
1621
1.40k
    }
PartiallySignedTransaction::PartiallySignedTransaction<DataStream>(deserialize_type, DataStream&)
Line
Count
Source
1619
1
    PartiallySignedTransaction(deserialize_type, Stream& s) {
1620
1
        Unserialize(s);
1621
1
    }
PartiallySignedTransaction::PartiallySignedTransaction<SpanReader>(deserialize_type, SpanReader&)
Line
Count
Source
1619
1.39k
    PartiallySignedTransaction(deserialize_type, Stream& s) {
1620
1.39k
        Unserialize(s);
1621
1.39k
    }
1622
};
1623
1624
enum class PSBTRole {
1625
    CREATOR,
1626
    UPDATER,
1627
    SIGNER,
1628
    FINALIZER,
1629
    EXTRACTOR
1630
};
1631
1632
std::string PSBTRoleName(PSBTRole role);
1633
1634
/** Compute a PrecomputedTransactionData object from a psbt. */
1635
std::optional<PrecomputedTransactionData> PrecomputePSBTData(const PartiallySignedTransaction& psbt);
1636
1637
/** Checks whether a PSBTInput is already signed by checking for non-null finalized fields. */
1638
bool PSBTInputSigned(const PSBTInput& input);
1639
1640
/** Checks whether a PSBTInput is already signed by doing script verification using final fields. */
1641
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
1642
1643
/** Signs a PSBTInput, verifying that all provided data matches what is being signed.
1644
 *
1645
 * txdata should be the output of PrecomputePSBTData (which can be shared across
1646
 * multiple SignPSBTInput calls). If it is nullptr, a dummy signature will be created.
1647
 **/
1648
[[nodiscard]] PSBTError SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options, SignatureData* out_sigdata = nullptr);
1649
1650
/**  Reduces the size of the PSBT by dropping unnecessary `non_witness_utxos` (i.e. complete previous transactions) from a psbt when all inputs are segwit v1. */
1651
void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx);
1652
1653
/** Counts the unsigned inputs of a PSBT. */
1654
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt);
1655
1656
/** Updates a PSBTOutput with information from provider.
1657
 *
1658
 * This fills in the redeem_script, witness_script, and hd_keypaths where possible.
1659
 */
1660
void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index);
1661
1662
/**
1663
 * Finalizes a PSBT if possible, combining partial signatures.
1664
 *
1665
 * @param[in,out] psbtx PartiallySignedTransaction to finalize
1666
 * return True if the PSBT is now complete, false otherwise
1667
 */
1668
bool FinalizePSBT(PartiallySignedTransaction& psbtx);
1669
1670
/**
1671
 * Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
1672
 *
1673
 * @param[in]  psbtx PartiallySignedTransaction
1674
 * @param[out] result CMutableTransaction representing the complete transaction, if successful
1675
 * @return True if we successfully extracted the transaction, false otherwise
1676
 */
1677
bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result);
1678
1679
/**
1680
 * Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial signatures from each input.
1681
 *
1682
 * @param[in]  psbtxs the PSBTs to combine
1683
 * @return     The combined PSBT or std::nullopt if the PSBTs cannot be combined
1684
 */
1685
[[nodiscard]] std::optional<PartiallySignedTransaction> CombinePSBTs(const std::vector<PartiallySignedTransaction>& psbtxs);
1686
1687
//! Decode a base64ed PSBT into a PartiallySignedTransaction
1688
[[nodiscard]] util::Result<PartiallySignedTransaction> DecodeBase64PSBT(const std::string& base64_tx);
1689
//! Decode a raw (binary blob) PSBT into a PartiallySignedTransaction
1690
[[nodiscard]] util::Result<PartiallySignedTransaction> DecodeRawPSBT(std::span<const std::byte> tx_data);
1691
1692
#endif // BITCOIN_PSBT_H