Coverage Report

Created: 2026-10-07 20:26

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