Bitcoin Core Fuzz Coverage Report

Coverage Report

Created: 2026-03-24 13:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/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
0
    bool operator<(const PSBTProprietary &b) const {
91
0
        return key < b.key;
92
0
    }
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
0
{
103
0
    SizeComputer sizecomp;
104
0
    SerializeMany(sizecomp, args...);
105
0
    WriteCompactSize(s, sizecomp.size());
106
0
    SerializeMany(s, args...);
107
0
}
Unexecuted instantiation: void SerializeToVector<DataStream, CompactSizeWriter>(DataStream&, CompactSizeWriter const&)
Unexecuted instantiation: void SerializeToVector<DataStream, ParamsWrapper<TransactionSerParams, CMutableTransaction const> >(DataStream&, ParamsWrapper<TransactionSerParams, CMutableTransaction const> const&)
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&)
Unexecuted instantiation: void SerializeToVector<DataStream, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const> const> >(DataStream&, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const> const> const&)
Unexecuted instantiation: void SerializeToVector<DataStream, CTxOut>(DataStream&, CTxOut const&)
Unexecuted instantiation: void SerializeToVector<DataStream, CompactSizeWriter, std::span<unsigned char const, 18446744073709551615ul> >(DataStream&, CompactSizeWriter const&, std::span<unsigned char const, 18446744073709551615ul> const&)
Unexecuted instantiation: void SerializeToVector<DataStream, int>(DataStream&, int const&)
Unexecuted instantiation: void SerializeToVector<DataStream, unsigned char>(DataStream&, unsigned char const&)
Unexecuted instantiation: void SerializeToVector<DataStream, unsigned char, XOnlyPubKey, uint256>(DataStream&, unsigned char const&, XOnlyPubKey const&, uint256 const&)
Unexecuted instantiation: void SerializeToVector<DataStream, unsigned char, std::span<unsigned char const, 18446744073709551615ul> >(DataStream&, unsigned char const&, std::span<unsigned char const, 18446744073709551615ul> const&)
Unexecuted instantiation: void SerializeToVector<DataStream, unsigned char, XOnlyPubKey>(DataStream&, unsigned char const&, XOnlyPubKey const&)
Unexecuted instantiation: void SerializeToVector<DataStream, uint256>(DataStream&, uint256 const&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: 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&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, CompactSizeWriter>(VectorWriter&, CompactSizeWriter const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, ParamsWrapper<TransactionSerParams, CMutableTransaction const> >(VectorWriter&, ParamsWrapper<TransactionSerParams, CMutableTransaction const> const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, unsigned char, unsigned char [78]>(VectorWriter&, unsigned char const&, unsigned char const (&) [78])
Unexecuted instantiation: void SerializeToVector<VectorWriter, unsigned int>(VectorWriter&, unsigned int const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const> const> >(VectorWriter&, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const> const> const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, CTxOut>(VectorWriter&, CTxOut const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, CompactSizeWriter, std::span<unsigned char const, 18446744073709551615ul> >(VectorWriter&, CompactSizeWriter const&, std::span<unsigned char const, 18446744073709551615ul> const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, int>(VectorWriter&, int const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, unsigned char>(VectorWriter&, unsigned char const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, unsigned char, XOnlyPubKey, uint256>(VectorWriter&, unsigned char const&, XOnlyPubKey const&, uint256 const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, unsigned char, std::span<unsigned char const, 18446744073709551615ul> >(VectorWriter&, unsigned char const&, std::span<unsigned char const, 18446744073709551615ul> const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, unsigned char, XOnlyPubKey>(VectorWriter&, unsigned char const&, XOnlyPubKey const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, uint256>(VectorWriter&, uint256 const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, CompactSizeWriter, std::span<unsigned char const, 18446744073709551615ul>, std::span<unsigned char const, 18446744073709551615ul> >(VectorWriter&, CompactSizeWriter const&, std::span<unsigned char const, 18446744073709551615ul> const&, std::span<unsigned char const, 18446744073709551615ul> const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, CompactSizeWriter, std::span<unsigned char const, 18446744073709551615ul>, std::span<unsigned char const, 18446744073709551615ul>, uint256>(VectorWriter&, CompactSizeWriter const&, std::span<unsigned char const, 18446744073709551615ul> const&, std::span<unsigned char const, 18446744073709551615ul> const&, uint256 const&)
Unexecuted instantiation: void SerializeToVector<VectorWriter, std::vector<std::vector<unsigned char, std::allocator<unsigned char> >, std::allocator<std::vector<unsigned char, std::allocator<unsigned char> > > > >(VectorWriter&, std::vector<std::vector<unsigned char, std::allocator<unsigned char> >, std::allocator<std::vector<unsigned char, std::allocator<unsigned char> > > > const&)
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
0
{
113
0
    size_t expected_size = ReadCompactSize(s);
114
0
    size_t remaining_before = s.size();
115
0
    UnserializeMany(s, args...);
116
0
    size_t remaining_after = s.size();
117
0
    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
0
}
Unexecuted instantiation: void UnserializeFromVector<SpanReader, ParamsWrapper<TransactionSerParams, CMutableTransaction> >(SpanReader&, ParamsWrapper<TransactionSerParams, CMutableTransaction>&&)
Unexecuted instantiation: void UnserializeFromVector<SpanReader, unsigned int&>(SpanReader&, unsigned int&)
Unexecuted instantiation: void UnserializeFromVector<SpanReader, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const> > >(SpanReader&, ParamsWrapper<TransactionSerParams, std::shared_ptr<CTransaction const> >&&)
Unexecuted instantiation: void UnserializeFromVector<SpanReader, CTxOut&>(SpanReader&, CTxOut&)
Unexecuted instantiation: void UnserializeFromVector<SpanReader, int&>(SpanReader&, int&)
Unexecuted instantiation: 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> > > >&)
Unexecuted instantiation: void UnserializeFromVector<SpanReader, XOnlyPubKey&>(SpanReader&, XOnlyPubKey&)
Unexecuted instantiation: void UnserializeFromVector<SpanReader, uint256&>(SpanReader&, uint256&)
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
0
{
126
    // Read in key path
127
0
    if (length % 4 || length == 0) {
128
0
        throw std::ios_base::failure("Invalid length for HD key path");
129
0
    }
130
131
0
    KeyOriginInfo hd_keypath;
132
0
    s >> hd_keypath.fingerprint;
133
0
    for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
134
0
        uint32_t index;
135
0
        s >> index;
136
0
        hd_keypath.path.push_back(index);
137
0
    }
138
0
    return hd_keypath;
139
0
}
Unexecuted instantiation: KeyOriginInfo DeserializeKeyOrigin<SpanReader>(SpanReader&, unsigned long)
Unexecuted instantiation: KeyOriginInfo DeserializeKeyOrigin<DataStream>(DataStream&, unsigned long)
140
141
// Deserialize a length prefixed KeyOriginInfo from a stream
142
template<typename Stream>
143
void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
144
0
{
145
0
    hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
146
0
}
Unexecuted instantiation: void DeserializeHDKeypath<SpanReader>(SpanReader&, KeyOriginInfo&)
Unexecuted instantiation: void DeserializeHDKeypath<DataStream>(DataStream&, KeyOriginInfo&)
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
0
{
152
    // Make sure that the key is the size of pubkey + 1
153
0
    if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
154
0
        throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
155
0
    }
156
    // Read in the pubkey from key
157
0
    CPubKey pubkey(key.begin() + 1, key.end());
158
0
    if (!pubkey.IsFullyValid()) {
159
0
       throw std::ios_base::failure("Invalid pubkey");
160
0
    }
161
0
    if (hd_keypaths.contains(pubkey)) {
162
0
        throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided");
163
0
    }
164
165
0
    KeyOriginInfo keypath;
166
0
    DeserializeHDKeypath(s, keypath);
167
168
    // Add to map
169
0
    hd_keypaths.emplace(pubkey, std::move(keypath));
170
0
}
Unexecuted instantiation: 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> > >&)
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> > >&)
171
172
// Serialize a KeyOriginInfo to a stream
173
template<typename Stream>
174
void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
175
0
{
176
0
    s << hd_keypath.fingerprint;
177
0
    for (const auto& path : hd_keypath.path) {
178
0
        s << path;
179
0
    }
180
0
}
Unexecuted instantiation: void SerializeKeyOrigin<DataStream>(DataStream&, KeyOriginInfo)
Unexecuted instantiation: void SerializeKeyOrigin<VectorWriter>(VectorWriter&, KeyOriginInfo)
181
182
// Serialize a length prefixed KeyOriginInfo to a stream
183
template<typename Stream>
184
void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
185
0
{
186
0
    WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
187
0
    SerializeKeyOrigin(s, hd_keypath);
188
0
}
Unexecuted instantiation: void SerializeHDKeypath<DataStream>(DataStream&, KeyOriginInfo)
Unexecuted instantiation: void SerializeHDKeypath<VectorWriter>(VectorWriter&, KeyOriginInfo)
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
0
{
194
0
    for (const auto& keypath_pair : hd_keypaths) {
195
0
        if (!keypath_pair.first.IsValid()) {
196
0
            throw std::ios_base::failure("Invalid CPubKey being serialized");
197
0
        }
198
0
        SerializeToVector(s, type, std::span{keypath_pair.first});
199
0
        SerializeHDKeypath(s, keypath_pair.second);
200
0
    }
201
0
}
Unexecuted instantiation: void SerializeHDKeypaths<DataStream>(DataStream&, std::map<CPubKey, KeyOriginInfo, std::less<CPubKey>, std::allocator<std::pair<CPubKey const, KeyOriginInfo> > > const&, CompactSizeWriter)
Unexecuted instantiation: void SerializeHDKeypaths<VectorWriter>(VectorWriter&, std::map<CPubKey, KeyOriginInfo, std::less<CPubKey>, std::allocator<std::pair<CPubKey const, KeyOriginInfo> > > const&, CompactSizeWriter)
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
0
{
207
0
    std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
208
0
    skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
209
0
    CPubKey agg_pubkey(agg_pubkey_bytes);
210
0
    if (!agg_pubkey.IsFullyValid()) {
211
0
        throw std::ios_base::failure(context + " musig2 aggregate pubkey is invalid");
212
0
    }
213
214
0
    std::vector<CPubKey> participants;
215
0
    std::vector<unsigned char> val;
216
0
    s >> val;
217
0
    SpanReader s_val{val};
218
0
    while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
219
0
        std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
220
0
        s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
221
0
        CPubKey participant(part_pubkey_bytes);
222
0
        if (!participant.IsFullyValid()) {
223
0
            throw std::ios_base::failure(context + " musig2 participant pubkey is invalid");
224
0
        }
225
0
        participants.push_back(participant);
226
0
    }
227
0
    if (!s_val.empty()) {
228
0
        throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
229
0
    }
230
231
0
    out.emplace(agg_pubkey, participants);
232
0
}
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
0
{
239
0
    leaf_hash.SetNull();
240
241
0
    std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
242
0
    std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
243
244
0
    skey >> std::as_writable_bytes(std::span{part_pubkey_bytes}) >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
245
0
    agg_pub.Set(agg_pubkey_bytes.begin(), agg_pubkey_bytes.end());
246
0
    if (!agg_pub.IsFullyValid()) {
247
0
        throw std::ios_base::failure("musig2 aggregate pubkey is invalid");
248
0
    }
249
250
0
    part_pub.Set(part_pubkey_bytes.begin(), part_pubkey_bytes.end());
251
0
    if (!part_pub.IsFullyValid()) {
252
0
        throw std::ios_base::failure("musig2 participant pubkey is invalid");
253
0
    }
254
255
0
    if (!skey.empty()) {
256
0
        skey >> leaf_hash;
257
0
    }
258
0
}
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
0
    PSBTInput() = default;
300
301
    template <typename Stream>
302
0
    inline void Serialize(Stream& s) const {
303
        // Write the utxo
304
0
        if (non_witness_utxo) {
305
0
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_NON_WITNESS_UTXO));
306
0
            SerializeToVector(s, TX_NO_WITNESS(non_witness_utxo));
307
0
        }
308
0
        if (!witness_utxo.IsNull()) {
309
0
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESS_UTXO));
310
0
            SerializeToVector(s, witness_utxo);
311
0
        }
312
313
0
        if (final_script_sig.empty() && final_script_witness.IsNull()) {
314
            // Write any partial signatures
315
0
            for (const auto& sig_pair : partial_sigs) {
316
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
317
0
                s << sig_pair.second.second;
318
0
            }
319
320
            // Write the sighash type
321
0
            if (sighash_type != std::nullopt) {
322
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_SIGHASH));
323
0
                SerializeToVector(s, *sighash_type);
324
0
            }
325
326
            // Write the redeem script
327
0
            if (!redeem_script.empty()) {
328
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_REDEEMSCRIPT));
329
0
                s << redeem_script;
330
0
            }
331
332
            // Write the witness script
333
0
            if (!witness_script.empty()) {
334
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESSSCRIPT));
335
0
                s << witness_script;
336
0
            }
337
338
            // Write any hd keypaths
339
0
            SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_IN_BIP32_DERIVATION));
340
341
            // Write any ripemd160 preimage
342
0
            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
0
            for (const auto& [hash, preimage] : sha256_preimages) {
349
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_SHA256), std::span{hash});
350
0
                s << preimage;
351
0
            }
352
353
            // Write any hash160 preimage
354
0
            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
0
            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
0
            if (!m_tap_key_sig.empty()) {
367
0
                SerializeToVector(s, PSBT_IN_TAP_KEY_SIG);
368
0
                s << m_tap_key_sig;
369
0
            }
370
371
            // Write taproot script sigs
372
0
            for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
373
0
                const auto& [xonly, leaf_hash] = pubkey_leaf;
374
0
                SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
375
0
                s << sig;
376
0
            }
377
378
            // Write taproot leaf scripts
379
0
            for (const auto& [leaf, control_blocks] : m_tap_scripts) {
380
0
                const auto& [script, leaf_ver] = leaf;
381
0
                for (const auto& control_block : control_blocks) {
382
0
                    SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, std::span{control_block});
383
0
                    std::vector<unsigned char> value_v(script.begin(), script.end());
384
0
                    value_v.push_back((uint8_t)leaf_ver);
385
0
                    s << value_v;
386
0
                }
387
0
            }
388
389
            // Write taproot bip32 keypaths
390
0
            for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
391
0
                const auto& [leaf_hashes, origin] = leaf_origin;
392
0
                SerializeToVector(s, PSBT_IN_TAP_BIP32_DERIVATION, xonly);
393
0
                std::vector<unsigned char> value;
394
0
                VectorWriter s_value{value, 0};
395
0
                s_value << leaf_hashes;
396
0
                SerializeKeyOrigin(s_value, origin);
397
0
                s << value;
398
0
            }
399
400
            // Write taproot internal key
401
0
            if (!m_tap_internal_key.IsNull()) {
402
0
                SerializeToVector(s, PSBT_IN_TAP_INTERNAL_KEY);
403
0
                s << ToByteVector(m_tap_internal_key);
404
0
            }
405
406
            // Write taproot merkle root
407
0
            if (!m_tap_merkle_root.IsNull()) {
408
0
                SerializeToVector(s, PSBT_IN_TAP_MERKLE_ROOT);
409
0
                SerializeToVector(s, m_tap_merkle_root);
410
0
            }
411
412
            // Write MuSig2 Participants
413
0
            for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
414
0
                SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
415
0
                std::vector<unsigned char> value;
416
0
                VectorWriter s_value{value, 0};
417
0
                for (auto& pk : part_pubs) {
418
0
                    s_value << std::span{pk};
419
0
                }
420
0
                s << value;
421
0
            }
422
423
            // Write MuSig2 pubnonces
424
0
            for (const auto& [agg_pubkey_leaf_hash, pubnonces] : m_musig2_pubnonces) {
425
0
                const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
426
0
                for (const auto& [part_pubkey, pubnonce] : pubnonces) {
427
0
                    if (leaf_hash.IsNull()) {
428
0
                        SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey});
429
0
                    } else {
430
0
                        SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey}, leaf_hash);
431
0
                    }
432
0
                    s << pubnonce;
433
0
                }
434
0
            }
435
436
            // Write MuSig2 partial signatures
437
0
            for (const auto& [agg_pubkey_leaf_hash, psigs] : m_musig2_partial_sigs) {
438
0
                const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
439
0
                for (const auto& [pubkey, psig] : psigs) {
440
0
                    if (leaf_hash.IsNull()) {
441
0
                        SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey});
442
0
                    } else {
443
0
                        SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey}, leaf_hash);
444
0
                    }
445
0
                    SerializeToVector(s, psig);
446
0
                }
447
0
            }
448
0
        }
449
450
        // Write script sig
451
0
        if (!final_script_sig.empty()) {
452
0
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTSIG));
453
0
            s << final_script_sig;
454
0
        }
455
        // write script witness
456
0
        if (!final_script_witness.IsNull()) {
457
0
            SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTWITNESS));
458
0
            SerializeToVector(s, final_script_witness.stack);
459
0
        }
460
461
        // Write proprietary things
462
0
        for (const auto& entry : m_proprietary) {
463
0
            s << entry.key;
464
0
            s << entry.value;
465
0
        }
466
467
        // Write unknown things
468
0
        for (auto& entry : unknown) {
469
0
            s << entry.first;
470
0
            s << entry.second;
471
0
        }
472
473
0
        s << PSBT_SEPARATOR;
474
0
    }
Unexecuted instantiation: void PSBTInput::Serialize<DataStream>(DataStream&) const
Unexecuted instantiation: void PSBTInput::Serialize<VectorWriter>(VectorWriter&) const
475
476
477
    template <typename Stream>
478
0
    inline void Unserialize(Stream& s) {
479
        // Used for duplicate key detection
480
0
        std::set<std::vector<unsigned char>> key_lookup;
481
482
        // Read loop
483
0
        bool found_sep = false;
484
0
        while(!s.empty()) {
485
            // Read the key of format "<keylen><keytype><keydata>" after which
486
            // "key" will contain "<keytype><keydata>"
487
0
            std::vector<unsigned char> key;
488
0
            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
0
            if (key.empty()) {
493
0
                found_sep = true;
494
0
                break;
495
0
            }
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
0
        if (!found_sep) {
866
0
            throw std::ios_base::failure("Separator is missing at the end of an input map");
867
0
        }
868
0
    }
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
0
    PSBTOutput() = default;
894
895
    template <typename Stream>
896
0
    inline void Serialize(Stream& s) const {
897
        // Write the redeem script
898
0
        if (!redeem_script.empty()) {
899
0
            SerializeToVector(s, CompactSizeWriter(PSBT_OUT_REDEEMSCRIPT));
900
0
            s << redeem_script;
901
0
        }
902
903
        // Write the witness script
904
0
        if (!witness_script.empty()) {
905
0
            SerializeToVector(s, CompactSizeWriter(PSBT_OUT_WITNESSSCRIPT));
906
0
            s << witness_script;
907
0
        }
908
909
        // Write any hd keypaths
910
0
        SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_OUT_BIP32_DERIVATION));
911
912
        // Write proprietary things
913
0
        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
0
        if (!m_tap_internal_key.IsNull()) {
920
0
            SerializeToVector(s, PSBT_OUT_TAP_INTERNAL_KEY);
921
0
            s << ToByteVector(m_tap_internal_key);
922
0
        }
923
924
        // Write taproot tree
925
0
        if (!m_tap_tree.empty()) {
926
0
            SerializeToVector(s, PSBT_OUT_TAP_TREE);
927
0
            std::vector<unsigned char> value;
928
0
            VectorWriter s_value{value, 0};
929
0
            for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
930
0
                s_value << depth;
931
0
                s_value << leaf_ver;
932
0
                s_value << script;
933
0
            }
934
0
            s << value;
935
0
        }
936
937
        // Write taproot bip32 keypaths
938
0
        for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
939
0
            const auto& [leaf_hashes, origin] = leaf;
940
0
            SerializeToVector(s, PSBT_OUT_TAP_BIP32_DERIVATION, xonly);
941
0
            std::vector<unsigned char> value;
942
0
            VectorWriter s_value{value, 0};
943
0
            s_value << leaf_hashes;
944
0
            SerializeKeyOrigin(s_value, origin);
945
0
            s << value;
946
0
        }
947
948
        // Write MuSig2 Participants
949
0
        for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
950
0
            SerializeToVector(s, CompactSizeWriter(PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
951
0
            std::vector<unsigned char> value;
952
0
            VectorWriter s_value{value, 0};
953
0
            for (auto& pk : part_pubs) {
954
0
                s_value << std::span{pk};
955
0
            }
956
0
            s << value;
957
0
        }
958
959
        // Write unknown things
960
0
        for (auto& entry : unknown) {
961
0
            s << entry.first;
962
0
            s << entry.second;
963
0
        }
964
965
0
        s << PSBT_SEPARATOR;
966
0
    }
Unexecuted instantiation: void PSBTOutput::Serialize<DataStream>(DataStream&) const
Unexecuted instantiation: void PSBTOutput::Serialize<VectorWriter>(VectorWriter&) const
967
968
969
    template <typename Stream>
970
0
    inline void Unserialize(Stream& s) {
971
        // Used for duplicate key detection
972
0
        std::set<std::vector<unsigned char>> key_lookup;
973
974
        // Read loop
975
0
        bool found_sep = false;
976
0
        while(!s.empty()) {
977
            // Read the key of format "<keylen><keytype><keydata>" after which
978
            // "key" will contain "<keytype><keydata>"
979
0
            std::vector<unsigned char> key;
980
0
            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
0
            if (key.empty()) {
985
0
                found_sep = true;
986
0
                break;
987
0
            }
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
0
        if (!found_sep) {
1127
0
            throw std::ios_base::failure("Separator is missing at the end of an output map");
1128
0
        }
1129
0
    }
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
0
    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
0
    inline void Serialize(Stream& s) const {
1171
1172
        // magic bytes
1173
0
        s << PSBT_MAGIC_BYTES;
1174
1175
        // unsigned tx flag
1176
0
        SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_UNSIGNED_TX));
1177
1178
        // Write serialized tx to a stream
1179
0
        SerializeToVector(s, TX_NO_WITNESS(*tx));
1180
1181
        // Write xpubs
1182
0
        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
0
        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
0
        for (const auto& entry : m_proprietary) {
1201
0
            s << entry.key;
1202
0
            s << entry.value;
1203
0
        }
1204
1205
        // Write the unknown things
1206
0
        for (auto& entry : unknown) {
1207
0
            s << entry.first;
1208
0
            s << entry.second;
1209
0
        }
1210
1211
        // Separator
1212
0
        s << PSBT_SEPARATOR;
1213
1214
        // Write inputs
1215
0
        for (const PSBTInput& input : inputs) {
1216
0
            s << input;
1217
0
        }
1218
        // Write outputs
1219
0
        for (const PSBTOutput& output : outputs) {
1220
0
            s << output;
1221
0
        }
1222
0
    }
Unexecuted instantiation: void PartiallySignedTransaction::Serialize<DataStream>(DataStream&) const
Unexecuted instantiation: void PartiallySignedTransaction::Serialize<VectorWriter>(VectorWriter&) const
1223
1224
1225
    template <typename Stream>
1226
0
    inline void Unserialize(Stream& s) {
1227
        // Read the magic bytes
1228
0
        uint8_t magic[5];
1229
0
        s >> magic;
1230
0
        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
0
        std::set<std::vector<unsigned char>> key_lookup;
1236
1237
        // Track the global xpubs we have already seen. Just for sanity checking
1238
0
        std::set<CExtPubKey> global_xpubs;
1239
1240
        // Read global data
1241
0
        bool found_sep = false;
1242
0
        while(!s.empty()) {
1243
            // Read the key of format "<keylen><keytype><keydata>" after which
1244
            // "key" will contain "<keytype><keydata>"
1245
0
            std::vector<unsigned char> key;
1246
0
            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
0
            if (key.empty()) {
1251
0
                found_sep = true;
1252
0
                break;
1253
0
            }
1254
1255
            // "skey" is used so that "key" is unchanged after reading keytype below
1256
0
            SpanReader skey{key};
1257
            // keytype is of the format compact size uint at the beginning of "key"
1258
0
            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
0
            switch(type) {
1263
0
                case PSBT_GLOBAL_UNSIGNED_TX:
1264
0
                {
1265
0
                    if (!key_lookup.emplace(key).second) {
1266
0
                        throw std::ios_base::failure("Duplicate Key, unsigned tx already provided");
1267
0
                    } 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
0
                    CMutableTransaction mtx;
1271
                    // Set the stream to serialize with non-witness since this should always be non-witness
1272
0
                    UnserializeFromVector(s, TX_NO_WITNESS(mtx));
1273
0
                    tx = std::move(mtx);
1274
                    // Make sure that all scriptSigs and scriptWitnesses are empty
1275
0
                    for (const CTxIn& txin : tx->vin) {
1276
0
                        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
0
                    }
1280
0
                    break;
1281
0
                }
1282
0
                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
0
            }
1352
0
        }
1353
1354
0
        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
0
        if (!tx) {
1360
0
            throw std::ios_base::failure("No unsigned transaction was provided");
1361
0
        }
1362
1363
        // Read input data
1364
0
        unsigned int i = 0;
1365
0
        while (!s.empty() && i < tx->vin.size()) {
1366
0
            PSBTInput input;
1367
0
            s >> input;
1368
0
            inputs.push_back(input);
1369
1370
            // Make sure the non-witness utxo matches the outpoint
1371
0
            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
0
            ++i;
1380
0
        }
1381
        // Make sure that the number of inputs matches the number of inputs in the transaction
1382
0
        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
0
        i = 0;
1388
0
        while (!s.empty() && i < tx->vout.size()) {
1389
0
            PSBTOutput output;
1390
0
            s >> output;
1391
0
            outputs.push_back(output);
1392
0
            ++i;
1393
0
        }
1394
        // Make sure that the number of outputs matches the number of outputs in the transaction
1395
0
        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
0
    }
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, std::optional<int> sighash = std::nullopt, SignatureData* out_sigdata = nullptr, bool finalize = true);
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