Coverage Report

Created: 2026-04-29 19:21

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