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