Branch data Line data Source code
1 : : // Copyright (c) 2009-2022 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 : : // Magic bytes
21 : : static constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff};
22 : :
23 : : // Global types
24 : : static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00;
25 : : static constexpr uint8_t PSBT_GLOBAL_XPUB = 0x01;
26 : : static constexpr uint8_t PSBT_GLOBAL_VERSION = 0xFB;
27 : : static constexpr uint8_t PSBT_GLOBAL_PROPRIETARY = 0xFC;
28 : :
29 : : // Input types
30 : : static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00;
31 : : static constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01;
32 : : static constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02;
33 : : static constexpr uint8_t PSBT_IN_SIGHASH = 0x03;
34 : : static constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04;
35 : : static constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05;
36 : : static constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06;
37 : : static constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07;
38 : : static constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08;
39 : : static constexpr uint8_t PSBT_IN_RIPEMD160 = 0x0A;
40 : : static constexpr uint8_t PSBT_IN_SHA256 = 0x0B;
41 : : static constexpr uint8_t PSBT_IN_HASH160 = 0x0C;
42 : : static constexpr uint8_t PSBT_IN_HASH256 = 0x0D;
43 : : static constexpr uint8_t PSBT_IN_TAP_KEY_SIG = 0x13;
44 : : static constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG = 0x14;
45 : : static constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT = 0x15;
46 : : static constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
47 : : static constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY = 0x17;
48 : : static constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT = 0x18;
49 : : static constexpr uint8_t PSBT_IN_PROPRIETARY = 0xFC;
50 : :
51 : : // Output types
52 : : static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00;
53 : : static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01;
54 : : static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02;
55 : : static constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
56 : : static constexpr uint8_t PSBT_OUT_TAP_TREE = 0x06;
57 : : static constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
58 : : static constexpr uint8_t PSBT_OUT_PROPRIETARY = 0xFC;
59 : :
60 : : // The separator is 0x00. Reading this in means that the unserializer can interpret it
61 : : // as a 0 length key which indicates that this is the separator. The separator has no value.
62 : : static constexpr uint8_t PSBT_SEPARATOR = 0x00;
63 : :
64 : : // BIP 174 does not specify a maximum file size, but we set a limit anyway
65 : : // to prevent reading a stream indefinitely and running out of memory.
66 : : const std::streamsize MAX_FILE_SIZE_PSBT = 100000000; // 100 MB
67 : :
68 : : // PSBT version number
69 : : static constexpr uint32_t PSBT_HIGHEST_VERSION = 0;
70 : :
71 : : /** A structure for PSBT proprietary types */
72 [ - + ]: 193469 : struct PSBTProprietary
73 : : {
74 : : uint64_t subtype;
75 : : std::vector<unsigned char> identifier;
76 : : std::vector<unsigned char> key;
77 : : std::vector<unsigned char> value;
78 : :
79 : 261034 : bool operator<(const PSBTProprietary &b) const {
80 : 261034 : return key < b.key;
81 : : }
82 : : bool operator==(const PSBTProprietary &b) const {
83 : : return key == b.key;
84 : : }
85 : : };
86 : :
87 : : // Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
88 : : // The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
89 : : template<typename Stream, typename... X>
90 : 286765 : void SerializeToVector(Stream& s, const X&... args)
91 : : {
92 : 286765 : SizeComputer sizecomp;
93 : 286765 : SerializeMany(sizecomp, args...);
94 : 286765 : WriteCompactSize(s, sizecomp.size());
95 : 286765 : SerializeMany(s, args...);
96 : 286765 : }
97 : :
98 : : // Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
99 : : template<typename Stream, typename... X>
100 : 107676 : void UnserializeFromVector(Stream& s, X&&... args)
101 : : {
102 : 107676 : size_t expected_size = ReadCompactSize(s);
103 : 107676 : size_t remaining_before = s.size();
104 : 107676 : UnserializeMany(s, args...);
105 : 107676 : size_t remaining_after = s.size();
106 [ + + + + : 107676 : if (remaining_after + expected_size != remaining_before) {
+ + + + +
+ + + + +
+ + ]
107 [ + - - + : 532 : throw std::ios_base::failure("Size of value was not the stated size");
+ - + - -
+ + - + -
- + + - +
- - + + -
+ - - + +
- + - - +
+ - + - -
+ + - + -
- + + - ]
108 : : }
109 : 107676 : }
110 : :
111 : : // Deserialize bytes of given length from the stream as a KeyOriginInfo
112 : : template<typename Stream>
113 : 82491 : KeyOriginInfo DeserializeKeyOrigin(Stream& s, uint64_t length)
114 : : {
115 : : // Read in key path
116 [ + + ]: 82491 : if (length % 4 || length == 0) {
117 [ + - - + : 268 : throw std::ios_base::failure("Invalid length for HD key path");
+ - ]
118 : : }
119 : :
120 : 82349 : KeyOriginInfo hd_keypath;
121 [ + + ]: 82349 : s >> hd_keypath.fingerprint;
122 [ + + ]: 3147735 : for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
123 : 3065423 : uint32_t index;
124 [ + + ]: 3065423 : s >> index;
125 [ + - ]: 3065334 : hd_keypath.path.push_back(index);
126 : 3065423 : }
127 : 82223 : return hd_keypath;
128 [ + - ]: 82491 : }
129 : :
130 : : // Deserialize a length prefixed KeyOriginInfo from a stream
131 : : template<typename Stream>
132 : 55602 : void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
133 : : {
134 : 55602 : hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
135 : 55602 : }
136 : :
137 : : // Deserialize HD keypaths into a map
138 : : template<typename Stream>
139 : 44978 : void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
140 : : {
141 : : // Make sure that the key is the size of pubkey + 1
142 [ + + + + ]: 44978 : if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
143 [ + - + - ]: 10399 : throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
144 : : }
145 : : // Read in the pubkey from key
146 : 34977 : CPubKey pubkey(key.begin() + 1, key.end());
147 [ + + ]: 34977 : if (!pubkey.IsFullyValid()) {
148 [ + - + - ]: 168 : throw std::ios_base::failure("Invalid pubkey");
149 : : }
150 [ + + ]: 34809 : if (hd_keypaths.count(pubkey) > 0) {
151 [ + - + - ]: 22 : throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided");
152 : : }
153 : :
154 : 34787 : KeyOriginInfo keypath;
155 [ + + ]: 34787 : DeserializeHDKeypath(s, keypath);
156 : :
157 : : // Add to map
158 [ + - ]: 34579 : hd_keypaths.emplace(pubkey, std::move(keypath));
159 : 45168 : }
160 : :
161 : : // Serialize a KeyOriginInfo to a stream
162 : : template<typename Stream>
163 : 49768 : void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
164 : : {
165 : 49768 : s << hd_keypath.fingerprint;
166 [ + + + + ]: 2498953 : for (const auto& path : hd_keypath.path) {
167 : 2449185 : s << path;
168 : 2449185 : }
169 : 49768 : }
170 : :
171 : : // Serialize a length prefixed KeyOriginInfo to a stream
172 : : template<typename Stream>
173 : 36175 : void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
174 : : {
175 : 36175 : WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
176 [ + - ]: 36175 : SerializeKeyOrigin(s, hd_keypath);
177 : 36175 : }
178 : :
179 : : // Serialize HD keypaths to a stream from a map
180 : : template<typename Stream>
181 : 242523 : void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
182 : : {
183 [ + + ]: 267650 : for (const auto& keypath_pair : hd_keypaths) {
184 [ + + ]: 25127 : if (!keypath_pair.first.IsValid()) {
185 [ + - - + : 218 : throw std::ios_base::failure("Invalid CPubKey being serialized");
+ - ]
186 : : }
187 : 24909 : SerializeToVector(s, type, Span{keypath_pair.first});
188 [ + - ]: 24909 : SerializeHDKeypath(s, keypath_pair.second);
189 : 25127 : }
190 : 242523 : }
191 : :
192 : : /** A structure for PSBTs which contain per-input information */
193 [ + - + - : 396027 : struct PSBTInput
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- - + ]
194 : : {
195 : : CTransactionRef non_witness_utxo;
196 : : CTxOut witness_utxo;
197 : : CScript redeem_script;
198 : : CScript witness_script;
199 : : CScript final_script_sig;
200 : : CScriptWitness final_script_witness;
201 : : std::map<CPubKey, KeyOriginInfo> hd_keypaths;
202 : : std::map<CKeyID, SigPair> partial_sigs;
203 : : std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
204 : : std::map<uint256, std::vector<unsigned char>> sha256_preimages;
205 : : std::map<uint160, std::vector<unsigned char>> hash160_preimages;
206 : : std::map<uint256, std::vector<unsigned char>> hash256_preimages;
207 : :
208 : : // Taproot fields
209 : : std::vector<unsigned char> m_tap_key_sig;
210 : : std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
211 : : std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
212 : : std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
213 : : XOnlyPubKey m_tap_internal_key;
214 : : uint256 m_tap_merkle_root;
215 : :
216 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
217 : : std::set<PSBTProprietary> m_proprietary;
218 : : std::optional<int> sighash_type;
219 : :
220 : : bool IsNull() const;
221 : : void FillSignatureData(SignatureData& sigdata) const;
222 : : void FromSignatureData(const SignatureData& sigdata);
223 : : void Merge(const PSBTInput& input);
224 [ + - + - : 163552 : PSBTInput() {}
+ - + - -
+ + - +
- ]
225 : :
226 : : template <typename Stream>
227 : 108282 : inline void Serialize(Stream& s) const {
228 : : // Write the utxo
229 [ + + ]: 108282 : if (non_witness_utxo) {
230 : 465 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_NON_WITNESS_UTXO));
231 : 465 : SerializeToVector(s, TX_NO_WITNESS(non_witness_utxo));
232 : 465 : }
233 [ + + ]: 108282 : if (!witness_utxo.IsNull()) {
234 : 4772 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESS_UTXO));
235 : 4772 : SerializeToVector(s, witness_utxo);
236 : 4772 : }
237 : :
238 [ + + + + ]: 108282 : if (final_script_sig.empty() && final_script_witness.IsNull()) {
239 : : // Write any partial signatures
240 [ + + ]: 116058 : for (auto sig_pair : partial_sigs) {
241 [ + - + - : 10968 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), Span{sig_pair.second.first});
+ - ]
242 [ + - ]: 10968 : s << sig_pair.second.second;
243 : 10968 : }
244 : :
245 : : // Write the sighash type
246 [ + + ]: 105090 : if (sighash_type != std::nullopt) {
247 : 106 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SIGHASH));
248 : 106 : SerializeToVector(s, *sighash_type);
249 : 106 : }
250 : :
251 : : // Write the redeem script
252 [ + + ]: 105090 : if (!redeem_script.empty()) {
253 : 1684 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_REDEEMSCRIPT));
254 : 1684 : s << redeem_script;
255 : 1684 : }
256 : :
257 : : // Write the witness script
258 [ + + ]: 105090 : if (!witness_script.empty()) {
259 : 2960 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESSSCRIPT));
260 : 2960 : s << witness_script;
261 : 2960 : }
262 : :
263 : : // Write any hd keypaths
264 : 105090 : SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_IN_BIP32_DERIVATION));
265 : :
266 : : // Write any ripemd160 preimage
267 [ + + ]: 111545 : for (const auto& [hash, preimage] : ripemd160_preimages) {
268 : 12910 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_RIPEMD160), Span{hash});
269 : 12910 : s << preimage;
270 : 6455 : }
271 : :
272 : : // Write any sha256 preimage
273 [ + + ]: 123498 : for (const auto& [hash, preimage] : sha256_preimages) {
274 : 36816 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SHA256), Span{hash});
275 : 36816 : s << preimage;
276 : 18408 : }
277 : :
278 : : // Write any hash160 preimage
279 [ + + ]: 110253 : for (const auto& [hash, preimage] : hash160_preimages) {
280 : 10326 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH160), Span{hash});
281 : 10326 : s << preimage;
282 : 5163 : }
283 : :
284 : : // Write any hash256 preimage
285 [ + + ]: 108968 : for (const auto& [hash, preimage] : hash256_preimages) {
286 : 7756 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH256), Span{hash});
287 : 7756 : s << preimage;
288 : 3878 : }
289 : :
290 : : // Write taproot key sig
291 [ + + ]: 105090 : if (!m_tap_key_sig.empty()) {
292 : 269 : SerializeToVector(s, PSBT_IN_TAP_KEY_SIG);
293 : 269 : s << m_tap_key_sig;
294 : 269 : }
295 : :
296 : : // Write taproot script sigs
297 [ + + ]: 115297 : for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
298 : 30621 : const auto& [xonly, leaf_hash] = pubkey_leaf;
299 : 20414 : SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
300 : 20414 : s << sig;
301 : 10207 : }
302 : :
303 : : // Write taproot leaf scripts
304 [ + + ]: 134257 : for (const auto& [leaf, control_blocks] : m_tap_scripts) {
305 : 127550 : const auto& [script, leaf_ver] = leaf;
306 [ + + ]: 92942 : for (const auto& control_block : control_blocks) {
307 : 34608 : SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, Span{control_block});
308 [ + - + - : 103824 : std::vector<unsigned char> value_v(script.begin(), script.end());
+ - ]
309 [ + - + - ]: 69216 : value_v.push_back((uint8_t)leaf_ver);
310 [ + - ]: 34608 : s << value_v;
311 : 34608 : }
312 : 29167 : }
313 : :
314 : : // Write taproot bip32 keypaths
315 [ + + ]: 107583 : for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
316 : 4986 : const auto& [leaf_hashes, origin] = leaf_origin;
317 : 4986 : SerializeToVector(s, PSBT_IN_TAP_BIP32_DERIVATION, xonly);
318 : 2493 : std::vector<unsigned char> value;
319 [ + - ]: 2493 : VectorWriter s_value{value, 0};
320 [ + - ]: 2493 : s_value << leaf_hashes;
321 [ + - + - ]: 2493 : SerializeKeyOrigin(s_value, origin);
322 [ + - ]: 2493 : s << value;
323 : 2493 : }
324 : :
325 : : // Write taproot internal key
326 [ + + ]: 105090 : if (!m_tap_internal_key.IsNull()) {
327 : 488 : SerializeToVector(s, PSBT_IN_TAP_INTERNAL_KEY);
328 [ + - ]: 488 : s << ToByteVector(m_tap_internal_key);
329 : 488 : }
330 : :
331 : : // Write taproot merkle root
332 [ + + ]: 105090 : if (!m_tap_merkle_root.IsNull()) {
333 : 1499 : SerializeToVector(s, PSBT_IN_TAP_MERKLE_ROOT);
334 : 1499 : SerializeToVector(s, m_tap_merkle_root);
335 : 1499 : }
336 : 105090 : }
337 : :
338 : : // Write script sig
339 [ + + ]: 108282 : if (!final_script_sig.empty()) {
340 : 2171 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTSIG));
341 : 2171 : s << final_script_sig;
342 : 2171 : }
343 : : // write script witness
344 [ + + ]: 108282 : if (!final_script_witness.IsNull()) {
345 : 1023 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTWITNESS));
346 : 1023 : SerializeToVector(s, final_script_witness.stack);
347 : 1023 : }
348 : :
349 : : // Write proprietary things
350 [ + + ]: 116831 : for (const auto& entry : m_proprietary) {
351 : 8549 : s << entry.key;
352 : 8549 : s << entry.value;
353 : 8549 : }
354 : :
355 : : // Write unknown things
356 [ + + ]: 207699 : for (auto& entry : unknown) {
357 : 99417 : s << entry.first;
358 : 99417 : s << entry.second;
359 : 99417 : }
360 : :
361 : 108282 : s << PSBT_SEPARATOR;
362 : 108282 : }
363 : :
364 : :
365 : : template <typename Stream>
366 : 151413 : inline void Unserialize(Stream& s) {
367 : : // Used for duplicate key detection
368 : 151413 : std::set<std::vector<unsigned char>> key_lookup;
369 : :
370 : : // Read loop
371 : 151413 : bool found_sep = false;
372 [ + + ]: 506335 : while(!s.empty()) {
373 : : // Read
374 : 506261 : std::vector<unsigned char> key;
375 [ + + ]: 506261 : s >> key;
376 : :
377 : : // the key is empty if that was actually a separator byte
378 : : // This is a special case for key lengths 0 as those are not allowed (except for separator)
379 [ + + ]: 505891 : if (key.empty()) {
380 : 148588 : found_sep = true;
381 : 148588 : break;
382 : : }
383 : :
384 : : // Type is compact size uint at beginning of key
385 [ + - + - ]: 357303 : SpanReader skey{key};
386 [ + + ]: 357303 : uint64_t type = ReadCompactSize(skey);
387 : :
388 : : // Do stuff based on type
389 [ + + + + : 357283 : switch(type) {
+ + + + +
+ + + + +
+ + + + +
+ + ]
390 : : case PSBT_IN_NON_WITNESS_UTXO:
391 : : {
392 [ + - + + ]: 1592 : if (!key_lookup.emplace(key).second) {
393 [ + - + - ]: 11 : throw std::ios_base::failure("Duplicate Key, input non-witness utxo already provided");
394 [ + + ]: 1581 : } else if (key.size() != 1) {
395 [ + - + - ]: 66 : throw std::ios_base::failure("Non-witness utxo key is more than one byte type");
396 : : }
397 : : // Set the stream to unserialize with witness since this is always a valid network transaction
398 [ + - + + ]: 1515 : UnserializeFromVector(s, TX_WITH_WITNESS(non_witness_utxo));
399 : 972 : break;
400 : : }
401 : : case PSBT_IN_WITNESS_UTXO:
402 [ + - + + ]: 10007 : if (!key_lookup.emplace(key).second) {
403 [ + - + - ]: 8 : throw std::ios_base::failure("Duplicate Key, input witness utxo already provided");
404 [ + + ]: 9999 : } else if (key.size() != 1) {
405 [ + - + - ]: 23 : throw std::ios_base::failure("Witness utxo key is more than one byte type");
406 : : }
407 [ + + ]: 9976 : UnserializeFromVector(s, witness_utxo);
408 : 9950 : break;
409 : : case PSBT_IN_PARTIAL_SIG:
410 : : {
411 : : // Make sure that the key is the size of pubkey + 1
412 [ + + + + ]: 29791 : if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
413 [ + - + - ]: 24 : throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
414 : : }
415 : : // Read in the pubkey from key
416 [ + - ]: 29767 : CPubKey pubkey(key.begin() + 1, key.end());
417 [ + - + + ]: 29767 : if (!pubkey.IsFullyValid()) {
418 [ + - + - ]: 87 : throw std::ios_base::failure("Invalid pubkey");
419 : : }
420 [ + - + - : 29680 : if (partial_sigs.count(pubkey.GetID()) > 0) {
+ + ]
421 [ + - + - ]: 16 : throw std::ios_base::failure("Duplicate Key, input partial signature for pubkey already provided");
422 : : }
423 : :
424 : : // Read in the signature from value
425 : 29664 : std::vector<unsigned char> sig;
426 [ + + ]: 29664 : s >> sig;
427 : :
428 : : // Add to list
429 [ + - + - ]: 29543 : partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
430 : : break;
431 : 29767 : }
432 : : case PSBT_IN_SIGHASH:
433 [ + - + + ]: 240 : if (!key_lookup.emplace(key).second) {
434 [ + - + - ]: 10 : throw std::ios_base::failure("Duplicate Key, input sighash type already provided");
435 [ + + ]: 230 : } else if (key.size() != 1) {
436 [ + - + - ]: 27 : throw std::ios_base::failure("Sighash type key is more than one byte type");
437 : : }
438 : : int sighash;
439 [ + + ]: 203 : UnserializeFromVector(s, sighash);
440 : 182 : sighash_type = sighash;
441 : 182 : break;
442 : : case PSBT_IN_REDEEMSCRIPT:
443 : : {
444 [ + - + + ]: 3599 : if (!key_lookup.emplace(key).second) {
445 [ + - + - ]: 11 : throw std::ios_base::failure("Duplicate Key, input redeemScript already provided");
446 [ + + ]: 3588 : } else if (key.size() != 1) {
447 [ + - + - ]: 21 : throw std::ios_base::failure("Input redeemScript key is more than one byte type");
448 : : }
449 [ + + ]: 3567 : s >> redeem_script;
450 : 3559 : break;
451 : : }
452 : : case PSBT_IN_WITNESSSCRIPT:
453 : : {
454 [ + - + + ]: 5062 : if (!key_lookup.emplace(key).second) {
455 [ + - + - ]: 10 : throw std::ios_base::failure("Duplicate Key, input witnessScript already provided");
456 [ + + ]: 5052 : } else if (key.size() != 1) {
457 [ + - + - ]: 15 : throw std::ios_base::failure("Input witnessScript key is more than one byte type");
458 : : }
459 [ + + ]: 5037 : s >> witness_script;
460 : 5027 : break;
461 : : }
462 : : case PSBT_IN_BIP32_DERIVATION:
463 : : {
464 [ + + ]: 7808 : DeserializeHDKeypaths(s, key, hd_keypaths);
465 : 7744 : break;
466 : : }
467 : : case PSBT_IN_SCRIPTSIG:
468 : : {
469 [ + - + + ]: 4346 : if (!key_lookup.emplace(key).second) {
470 [ + - + - ]: 8 : throw std::ios_base::failure("Duplicate Key, input final scriptSig already provided");
471 [ + + ]: 4338 : } else if (key.size() != 1) {
472 [ + - + - ]: 18 : throw std::ios_base::failure("Final scriptSig key is more than one byte type");
473 : : }
474 [ + + ]: 4320 : s >> final_script_sig;
475 : 4317 : break;
476 : : }
477 : : case PSBT_IN_SCRIPTWITNESS:
478 : : {
479 [ + - + + ]: 1770 : if (!key_lookup.emplace(key).second) {
480 [ + - + - ]: 9 : throw std::ios_base::failure("Duplicate Key, input final scriptWitness already provided");
481 [ + + ]: 1761 : } else if (key.size() != 1) {
482 [ + - + - ]: 15 : throw std::ios_base::failure("Final scriptWitness key is more than one byte type");
483 : : }
484 [ + + ]: 1746 : UnserializeFromVector(s, final_script_witness.stack);
485 : 1635 : break;
486 : : }
487 : : case PSBT_IN_RIPEMD160:
488 : : {
489 : : // Make sure that the key is the size of a ripemd160 hash + 1
490 [ + + ]: 12001 : if (key.size() != CRIPEMD160::OUTPUT_SIZE + 1) {
491 [ + - + - ]: 22 : throw std::ios_base::failure("Size of key was not the expected size for the type ripemd160 preimage");
492 : : }
493 : : // Read in the hash from key
494 [ + - ]: 11979 : std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
495 [ + - + - ]: 11979 : uint160 hash(hash_vec);
496 [ + - + + ]: 11979 : if (ripemd160_preimages.count(hash) > 0) {
497 [ + - + - ]: 11 : throw std::ios_base::failure("Duplicate Key, input ripemd160 preimage already provided");
498 : : }
499 : :
500 : : // Read in the preimage from value
501 : 11968 : std::vector<unsigned char> preimage;
502 [ + + ]: 11968 : s >> preimage;
503 : :
504 : : // Add to preimages list
505 [ + - ]: 11926 : ripemd160_preimages.emplace(hash, std::move(preimage));
506 : : break;
507 : 11979 : }
508 : : case PSBT_IN_SHA256:
509 : : {
510 : : // Make sure that the key is the size of a sha256 hash + 1
511 [ + + ]: 28876 : if (key.size() != CSHA256::OUTPUT_SIZE + 1) {
512 [ + - + - ]: 14 : throw std::ios_base::failure("Size of key was not the expected size for the type sha256 preimage");
513 : : }
514 : : // Read in the hash from key
515 [ + - ]: 28862 : std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
516 [ + - + - ]: 28862 : uint256 hash(hash_vec);
517 [ + - + + ]: 28862 : if (sha256_preimages.count(hash) > 0) {
518 [ + - + - ]: 10 : throw std::ios_base::failure("Duplicate Key, input sha256 preimage already provided");
519 : : }
520 : :
521 : : // Read in the preimage from value
522 : 28852 : std::vector<unsigned char> preimage;
523 [ + + ]: 28852 : s >> preimage;
524 : :
525 : : // Add to preimages list
526 [ + - ]: 28808 : sha256_preimages.emplace(hash, std::move(preimage));
527 : : break;
528 : 28862 : }
529 : : case PSBT_IN_HASH160:
530 : : {
531 : : // Make sure that the key is the size of a hash160 hash + 1
532 [ + + ]: 9650 : if (key.size() != CHash160::OUTPUT_SIZE + 1) {
533 [ + - + - ]: 19 : throw std::ios_base::failure("Size of key was not the expected size for the type hash160 preimage");
534 : : }
535 : : // Read in the hash from key
536 [ + - ]: 9631 : std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
537 [ + - + - ]: 9631 : uint160 hash(hash_vec);
538 [ + - + + ]: 9631 : if (hash160_preimages.count(hash) > 0) {
539 [ + - + - ]: 11 : throw std::ios_base::failure("Duplicate Key, input hash160 preimage already provided");
540 : : }
541 : :
542 : : // Read in the preimage from value
543 : 9620 : std::vector<unsigned char> preimage;
544 [ + + ]: 9620 : s >> preimage;
545 : :
546 : : // Add to preimages list
547 [ + - ]: 9585 : hash160_preimages.emplace(hash, std::move(preimage));
548 : : break;
549 : 9631 : }
550 : : case PSBT_IN_HASH256:
551 : : {
552 : : // Make sure that the key is the size of a hash256 hash + 1
553 [ + + ]: 7711 : if (key.size() != CHash256::OUTPUT_SIZE + 1) {
554 [ + - + - ]: 18 : throw std::ios_base::failure("Size of key was not the expected size for the type hash256 preimage");
555 : : }
556 : : // Read in the hash from key
557 [ + - ]: 7693 : std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
558 [ + - + - ]: 7693 : uint256 hash(hash_vec);
559 [ + - + + ]: 7693 : if (hash256_preimages.count(hash) > 0) {
560 [ + - + - ]: 9 : throw std::ios_base::failure("Duplicate Key, input hash256 preimage already provided");
561 : : }
562 : :
563 : : // Read in the preimage from value
564 : 7684 : std::vector<unsigned char> preimage;
565 [ + + ]: 7684 : s >> preimage;
566 : :
567 : : // Add to preimages list
568 [ + - ]: 7648 : hash256_preimages.emplace(hash, std::move(preimage));
569 : : break;
570 : 7693 : }
571 : : case PSBT_IN_TAP_KEY_SIG:
572 : : {
573 [ + - + + ]: 514 : if (!key_lookup.emplace(key).second) {
574 [ + - + - ]: 10 : throw std::ios_base::failure("Duplicate Key, input Taproot key signature already provided");
575 [ + + ]: 504 : } else if (key.size() != 1) {
576 [ + - + - ]: 19 : throw std::ios_base::failure("Input Taproot key signature key is more than one byte type");
577 : : }
578 [ + + ]: 485 : s >> m_tap_key_sig;
579 [ + + ]: 469 : if (m_tap_key_sig.size() < 64) {
580 [ + - + - ]: 9 : throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
581 [ + + ]: 460 : } else if (m_tap_key_sig.size() > 65) {
582 [ + - + - ]: 10 : throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
583 : : }
584 : 450 : break;
585 : : }
586 : : case PSBT_IN_TAP_SCRIPT_SIG:
587 : : {
588 [ + - + + ]: 14872 : if (!key_lookup.emplace(key).second) {
589 [ + - + - ]: 11 : throw std::ios_base::failure("Duplicate Key, input Taproot script signature already provided");
590 [ + + ]: 14861 : } else if (key.size() != 65) {
591 [ + - + - ]: 22 : throw std::ios_base::failure("Input Taproot script signature key is not 65 bytes");
592 : : }
593 [ + - + - ]: 14839 : SpanReader s_key{Span{key}.subspan(1)};
594 [ + - ]: 14839 : XOnlyPubKey xonly;
595 [ + - ]: 14839 : uint256 hash;
596 [ + - ]: 14839 : s_key >> xonly;
597 [ + - ]: 14839 : s_key >> hash;
598 : 14839 : std::vector<unsigned char> sig;
599 [ + + ]: 14839 : s >> sig;
600 [ + + ]: 14803 : if (sig.size() < 64) {
601 [ + - + - ]: 32 : throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
602 [ + + ]: 14771 : } else if (sig.size() > 65) {
603 [ + - + - ]: 18 : throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
604 : : }
605 [ + - + - ]: 14753 : m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
606 : : break;
607 : 14839 : }
608 : : case PSBT_IN_TAP_LEAF_SCRIPT:
609 : : {
610 [ + - + + ]: 52748 : if (!key_lookup.emplace(key).second) {
611 [ + - + - ]: 14 : throw std::ios_base::failure("Duplicate Key, input Taproot leaf script already provided");
612 [ + + ]: 52734 : } else if (key.size() < 34) {
613 [ + - + - ]: 27 : throw std::ios_base::failure("Taproot leaf script key is not at least 34 bytes");
614 [ + + ]: 52707 : } else if ((key.size() - 2) % 32 != 0) {
615 [ + - + - ]: 16 : throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
616 : : }
617 : 52691 : std::vector<unsigned char> script_v;
618 [ + + ]: 52691 : s >> script_v;
619 [ + + ]: 52625 : if (script_v.empty()) {
620 [ + - + - ]: 33 : throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
621 : : }
622 : 52592 : uint8_t leaf_ver = script_v.back();
623 : 52592 : script_v.pop_back();
624 [ + - ]: 52592 : const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
625 [ + - + - : 52592 : m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
+ - ]
626 : : break;
627 : 52691 : }
628 : : case PSBT_IN_TAP_BIP32_DERIVATION:
629 : : {
630 [ + - + + ]: 4565 : if (!key_lookup.emplace(key).second) {
631 [ + - + - ]: 8 : throw std::ios_base::failure("Duplicate Key, input Taproot BIP32 keypath already provided");
632 [ + + ]: 4557 : } else if (key.size() != 33) {
633 [ + - + - ]: 23 : throw std::ios_base::failure("Input Taproot BIP32 keypath key is not at 33 bytes");
634 : : }
635 [ + - + - ]: 4534 : SpanReader s_key{Span{key}.subspan(1)};
636 [ + - ]: 4534 : XOnlyPubKey xonly;
637 [ + - ]: 4534 : s_key >> xonly;
638 : 4534 : std::set<uint256> leaf_hashes;
639 [ + + ]: 4534 : uint64_t value_len = ReadCompactSize(s);
640 : 4522 : size_t before_hashes = s.size();
641 [ + + ]: 4522 : s >> leaf_hashes;
642 : 4407 : size_t after_hashes = s.size();
643 : 4407 : size_t hashes_len = before_hashes - after_hashes;
644 [ + + ]: 4407 : if (hashes_len > value_len) {
645 [ + - + - ]: 19 : throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
646 : : }
647 : 4388 : size_t origin_len = value_len - hashes_len;
648 [ + + + - : 4405 : m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
+ - ]
649 : : break;
650 : 4534 : }
651 : : case PSBT_IN_TAP_INTERNAL_KEY:
652 : : {
653 [ + - + + ]: 715 : if (!key_lookup.emplace(key).second) {
654 [ + - + - ]: 9 : throw std::ios_base::failure("Duplicate Key, input Taproot internal key already provided");
655 [ + + ]: 706 : } else if (key.size() != 1) {
656 [ + - + - ]: 17 : throw std::ios_base::failure("Input Taproot internal key key is more than one byte type");
657 : : }
658 [ + + ]: 689 : UnserializeFromVector(s, m_tap_internal_key);
659 : 687 : break;
660 : : }
661 : : case PSBT_IN_TAP_MERKLE_ROOT:
662 : : {
663 [ + - + + ]: 1787 : if (!key_lookup.emplace(key).second) {
664 [ + - + - ]: 7 : throw std::ios_base::failure("Duplicate Key, input Taproot merkle root already provided");
665 [ + + ]: 1780 : } else if (key.size() != 1) {
666 [ + - + - ]: 19 : throw std::ios_base::failure("Input Taproot merkle root key is more than one byte type");
667 : : }
668 [ + + ]: 1761 : UnserializeFromVector(s, m_tap_merkle_root);
669 : 1749 : break;
670 : : }
671 : : case PSBT_IN_PROPRIETARY:
672 : : {
673 : 12998 : PSBTProprietary this_prop;
674 [ + + ]: 12998 : skey >> this_prop.identifier;
675 [ + + ]: 12976 : this_prop.subtype = ReadCompactSize(skey);
676 [ + - ]: 12975 : this_prop.key = key;
677 : :
678 [ + - + + ]: 12975 : if (m_proprietary.count(this_prop) > 0) {
679 [ + - + - ]: 18 : throw std::ios_base::failure("Duplicate Key, proprietary key already found");
680 : : }
681 [ + + ]: 12957 : s >> this_prop.value;
682 [ + - ]: 12919 : m_proprietary.insert(this_prop);
683 : : break;
684 : 12998 : }
685 : : // Unknown stuff
686 : : default:
687 [ + - + + ]: 146631 : if (unknown.count(key) > 0) {
688 [ + - + - ]: 30 : throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
689 : : }
690 : : // Read in the value
691 : 146601 : std::vector<unsigned char> val_bytes;
692 [ + + ]: 146601 : s >> val_bytes;
693 [ + - ]: 146505 : unknown.emplace(std::move(key), std::move(val_bytes));
694 : : break;
695 : 146601 : }
696 [ + + ]: 506261 : }
697 : :
698 [ + + ]: 148662 : if (!found_sep) {
699 [ + - + - ]: 74 : throw std::ios_base::failure("Separator is missing at the end of an input map");
700 : : }
701 : 154238 : }
702 : :
703 : : template <typename Stream>
704 : : PSBTInput(deserialize_type, Stream& s) {
705 : : Unserialize(s);
706 : : }
707 : : };
708 : :
709 : : /** A structure for PSBTs which contains per output information */
710 [ + - + - : 381313 : struct PSBTOutput
+ - + - -
+ ]
711 : : {
712 : : CScript redeem_script;
713 : : CScript witness_script;
714 : : std::map<CPubKey, KeyOriginInfo> hd_keypaths;
715 : : XOnlyPubKey m_tap_internal_key;
716 : : std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
717 : : std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
718 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
719 : : std::set<PSBTProprietary> m_proprietary;
720 : :
721 : : bool IsNull() const;
722 : : void FillSignatureData(SignatureData& sigdata) const;
723 : : void FromSignatureData(const SignatureData& sigdata);
724 : : void Merge(const PSBTOutput& output);
725 [ + - - + ]: 205749 : PSBTOutput() {}
726 : :
727 : : template <typename Stream>
728 : 127215 : inline void Serialize(Stream& s) const {
729 : : // Write the redeem script
730 [ + + ]: 127215 : if (!redeem_script.empty()) {
731 : 2505 : SerializeToVector(s, CompactSizeWriter(PSBT_OUT_REDEEMSCRIPT));
732 : 2505 : s << redeem_script;
733 : 2505 : }
734 : :
735 : : // Write the witness script
736 [ + + ]: 127215 : if (!witness_script.empty()) {
737 : 2238 : SerializeToVector(s, CompactSizeWriter(PSBT_OUT_WITNESSSCRIPT));
738 : 2238 : s << witness_script;
739 : 2238 : }
740 : :
741 : : // Write any hd keypaths
742 : 127215 : SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_OUT_BIP32_DERIVATION));
743 : :
744 : : // Write proprietary things
745 [ + + ]: 137010 : for (const auto& entry : m_proprietary) {
746 : 9795 : s << entry.key;
747 : 9795 : s << entry.value;
748 : 9795 : }
749 : :
750 : : // Write taproot internal key
751 [ + + ]: 127215 : if (!m_tap_internal_key.IsNull()) {
752 : 4602 : SerializeToVector(s, PSBT_OUT_TAP_INTERNAL_KEY);
753 [ + - ]: 4602 : s << ToByteVector(m_tap_internal_key);
754 : 4602 : }
755 : :
756 : : // Write taproot tree
757 [ + + ]: 127215 : if (!m_tap_tree.empty()) {
758 : 1123 : SerializeToVector(s, PSBT_OUT_TAP_TREE);
759 : 1123 : std::vector<unsigned char> value;
760 [ + - ]: 1123 : VectorWriter s_value{value, 0};
761 [ + + ]: 6937 : for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
762 [ + - ]: 5814 : s_value << depth;
763 [ + - ]: 5814 : s_value << leaf_ver;
764 [ + - ]: 5814 : s_value << script;
765 : 5814 : }
766 [ + - ]: 1123 : s << value;
767 : 1123 : }
768 : :
769 : : // Write taproot bip32 keypaths
770 [ + + ]: 138315 : for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
771 : 22200 : const auto& [leaf_hashes, origin] = leaf;
772 : 22200 : SerializeToVector(s, PSBT_OUT_TAP_BIP32_DERIVATION, xonly);
773 : 11100 : std::vector<unsigned char> value;
774 [ + - ]: 11100 : VectorWriter s_value{value, 0};
775 [ + - ]: 11100 : s_value << leaf_hashes;
776 [ + - + - ]: 11100 : SerializeKeyOrigin(s_value, origin);
777 [ + - ]: 11100 : s << value;
778 : 11100 : }
779 : :
780 : : // Write unknown things
781 [ + + ]: 193725 : for (auto& entry : unknown) {
782 : 66510 : s << entry.first;
783 : 66510 : s << entry.second;
784 : 66510 : }
785 : :
786 : 127215 : s << PSBT_SEPARATOR;
787 : 127215 : }
788 : :
789 : :
790 : : template <typename Stream>
791 : 183093 : inline void Unserialize(Stream& s) {
792 : : // Used for duplicate key detection
793 : 183093 : std::set<std::vector<unsigned char>> key_lookup;
794 : :
795 : : // Read loop
796 : 183093 : bool found_sep = false;
797 [ + + ]: 401826 : while(!s.empty()) {
798 : : // Read
799 : 401766 : std::vector<unsigned char> key;
800 [ + + ]: 401766 : s >> key;
801 : :
802 : : // the key is empty if that was actually a separator byte
803 : : // This is a special case for key lengths 0 as those are not allowed (except for separator)
804 [ + + ]: 401398 : if (key.empty()) {
805 : 181094 : found_sep = true;
806 : 181094 : break;
807 : : }
808 : :
809 : : // Type is compact size uint at beginning of key
810 [ + - + - ]: 220304 : SpanReader skey{key};
811 [ + + ]: 220304 : uint64_t type = ReadCompactSize(skey);
812 : :
813 : : // Do stuff based on type
814 [ + + + + : 220283 : switch(type) {
+ + + + ]
815 : : case PSBT_OUT_REDEEMSCRIPT:
816 : : {
817 [ + - + + ]: 5716 : if (!key_lookup.emplace(key).second) {
818 [ + - + - ]: 13 : throw std::ios_base::failure("Duplicate Key, output redeemScript already provided");
819 [ + + ]: 5703 : } else if (key.size() != 1) {
820 [ + - + - ]: 119 : throw std::ios_base::failure("Output redeemScript key is more than one byte type");
821 : : }
822 [ + + ]: 5584 : s >> redeem_script;
823 : 5565 : break;
824 : : }
825 : : case PSBT_OUT_WITNESSSCRIPT:
826 : : {
827 [ + - + + ]: 4537 : if (!key_lookup.emplace(key).second) {
828 [ + - + - ]: 18 : throw std::ios_base::failure("Duplicate Key, output witnessScript already provided");
829 [ + + ]: 4519 : } else if (key.size() != 1) {
830 [ + - + - ]: 27 : throw std::ios_base::failure("Output witnessScript key is more than one byte type");
831 : : }
832 [ + + ]: 4492 : s >> witness_script;
833 : 4474 : break;
834 : : }
835 : : case PSBT_OUT_BIP32_DERIVATION:
836 : : {
837 [ + + ]: 26952 : DeserializeHDKeypaths(s, key, hd_keypaths);
838 : 26746 : break;
839 : : }
840 : : case PSBT_OUT_TAP_INTERNAL_KEY:
841 : : {
842 [ + - + + ]: 5485 : if (!key_lookup.emplace(key).second) {
843 [ + - + - ]: 7 : throw std::ios_base::failure("Duplicate Key, output Taproot internal key already provided");
844 [ + + ]: 5478 : } else if (key.size() != 1) {
845 [ + - + - ]: 18 : throw std::ios_base::failure("Output Taproot internal key key is more than one byte type");
846 : : }
847 [ + + ]: 5460 : UnserializeFromVector(s, m_tap_internal_key);
848 : 5440 : break;
849 : : }
850 : : case PSBT_OUT_TAP_TREE:
851 : : {
852 [ + - + + ]: 3174 : if (!key_lookup.emplace(key).second) {
853 [ + - + - ]: 10 : throw std::ios_base::failure("Duplicate Key, output Taproot tree already provided");
854 [ + + ]: 3164 : } else if (key.size() != 1) {
855 [ + - + - ]: 21 : throw std::ios_base::failure("Output Taproot tree key is more than one byte type");
856 : : }
857 : 3143 : std::vector<unsigned char> tree_v;
858 [ + + ]: 3143 : s >> tree_v;
859 [ + - + - ]: 3108 : SpanReader s_tree{tree_v};
860 [ + - + + ]: 3108 : if (s_tree.empty()) {
861 [ + - + - ]: 11 : throw std::ios_base::failure("Output Taproot tree must not be empty");
862 : : }
863 [ + - ]: 3097 : TaprootBuilder builder;
864 [ + - + + ]: 179249 : while (!s_tree.empty()) {
865 : 176570 : uint8_t depth;
866 : 176570 : uint8_t leaf_ver;
867 : 176570 : std::vector<unsigned char> script;
868 [ + - ]: 176570 : s_tree >> depth;
869 [ + + ]: 176570 : s_tree >> leaf_ver;
870 [ + + ]: 176520 : s_tree >> script;
871 [ + + ]: 176262 : if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
872 [ + - + - ]: 42 : throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
873 : : }
874 [ + + ]: 176220 : if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
875 [ + - + - ]: 68 : throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
876 : : }
877 [ + - ]: 176152 : m_tap_tree.emplace_back(depth, leaf_ver, script);
878 [ + - + - ]: 176152 : builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
879 : 176570 : }
880 [ + - + + ]: 2679 : if (!builder.IsComplete()) {
881 [ + - + - ]: 93 : throw std::ios_base::failure("Output Taproot tree is malformed");
882 : : }
883 : : break;
884 : 3143 : }
885 : : case PSBT_OUT_TAP_BIP32_DERIVATION:
886 : : {
887 [ + - + + ]: 22764 : if (!key_lookup.emplace(key).second) {
888 [ + - + - ]: 14 : throw std::ios_base::failure("Duplicate Key, output Taproot BIP32 keypath already provided");
889 [ + + ]: 22750 : } else if (key.size() != 33) {
890 [ + - + - ]: 29 : throw std::ios_base::failure("Output Taproot BIP32 keypath key is not at 33 bytes");
891 : : }
892 [ + - + - : 22721 : XOnlyPubKey xonly(uint256(Span<uint8_t>(key).last(32)));
+ - + - ]
893 : 22721 : std::set<uint256> leaf_hashes;
894 [ + + ]: 22721 : uint64_t value_len = ReadCompactSize(s);
895 : 22705 : size_t before_hashes = s.size();
896 [ + + ]: 22705 : s >> leaf_hashes;
897 : 22576 : size_t after_hashes = s.size();
898 : 22576 : size_t hashes_len = before_hashes - after_hashes;
899 [ + + ]: 22576 : if (hashes_len > value_len) {
900 [ + - + - ]: 19 : throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
901 : : }
902 : 22557 : size_t origin_len = value_len - hashes_len;
903 [ + + + - : 22584 : m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
+ - ]
904 : : break;
905 : 22721 : }
906 : : case PSBT_OUT_PROPRIETARY:
907 : : {
908 : 25439 : PSBTProprietary this_prop;
909 [ + + ]: 25439 : skey >> this_prop.identifier;
910 [ + + ]: 25410 : this_prop.subtype = ReadCompactSize(skey);
911 [ + - ]: 25407 : this_prop.key = key;
912 : :
913 [ + - + + ]: 25407 : if (m_proprietary.count(this_prop) > 0) {
914 [ + - + - ]: 21 : throw std::ios_base::failure("Duplicate Key, proprietary key already found");
915 : : }
916 [ + + ]: 25386 : s >> this_prop.value;
917 [ + - ]: 25344 : m_proprietary.insert(this_prop);
918 : : break;
919 : 25439 : }
920 : : // Unknown stuff
921 : : default: {
922 [ + - + + ]: 126216 : if (unknown.count(key) > 0) {
923 [ + - + - ]: 24 : throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
924 : : }
925 : : // Read in the value
926 : 126192 : std::vector<unsigned char> val_bytes;
927 [ + + ]: 126192 : s >> val_bytes;
928 [ + - ]: 126048 : unknown.emplace(std::move(key), std::move(val_bytes));
929 : : break;
930 : 126192 : }
931 : : }
932 [ + + ]: 401766 : }
933 : :
934 [ + + ]: 181154 : if (!found_sep) {
935 [ + - + - ]: 60 : throw std::ios_base::failure("Separator is missing at the end of an output map");
936 : : }
937 : 185092 : }
938 : :
939 : : template <typename Stream>
940 : : PSBTOutput(deserialize_type, Stream& s) {
941 : : Unserialize(s);
942 : : }
943 : : };
944 : :
945 : : /** A version of CTransaction with the PSBT format*/
946 [ + - + - : 77812 : struct PartiallySignedTransaction
+ - - + ]
947 : : {
948 : : std::optional<CMutableTransaction> tx;
949 : : // We use a vector of CExtPubKey in the event that there happens to be the same KeyOriginInfos for different CExtPubKeys
950 : : // Note that this map swaps the key and values from the serialization
951 : : std::map<KeyOriginInfo, std::set<CExtPubKey>> m_xpubs;
952 : : std::vector<PSBTInput> inputs;
953 : : std::vector<PSBTOutput> outputs;
954 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
955 : : std::optional<uint32_t> m_version;
956 : : std::set<PSBTProprietary> m_proprietary;
957 : :
958 : : bool IsNull() const;
959 : : uint32_t GetVersion() const;
960 : :
961 : : /** Merge psbt into this. The two psbts must have the same underlying CTransaction (i.e. the
962 : : * same actual Bitcoin transaction.) Returns true if the merge succeeded, false otherwise. */
963 : : [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
964 : : bool AddInput(const CTxIn& txin, PSBTInput& psbtin);
965 : : bool AddOutput(const CTxOut& txout, const PSBTOutput& psbtout);
966 : 91736 : PartiallySignedTransaction() {}
967 : : explicit PartiallySignedTransaction(const CMutableTransaction& tx);
968 : : /**
969 : : * Finds the UTXO for a given input index
970 : : *
971 : : * @param[out] utxo The UTXO of the input if found
972 : : * @param[in] input_index Index of the input to retrieve the UTXO of
973 : : * @return Whether the UTXO for the specified input was found
974 : : */
975 : : bool GetInputUTXO(CTxOut& utxo, int input_index) const;
976 : :
977 : : template <typename Stream>
978 : 56770 : inline void Serialize(Stream& s) const {
979 : :
980 : : // magic bytes
981 : 56770 : s << PSBT_MAGIC_BYTES;
982 : :
983 : : // unsigned tx flag
984 : 56770 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_UNSIGNED_TX));
985 : :
986 : : // Write serialized tx to a stream
987 : 56770 : SerializeToVector(s, TX_NO_WITNESS(*tx));
988 : :
989 : : // Write xpubs
990 [ + + ]: 66992 : for (const auto& xpub_pair : m_xpubs) {
991 [ + + ]: 21488 : for (const auto& xpub : xpub_pair.second) {
992 : 11266 : unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
993 : 11266 : xpub.EncodeWithVersion(ser_xpub);
994 : : // Note that the serialization swaps the key and value
995 : : // The xpub is the key (for uniqueness) while the path is the value
996 : 11266 : SerializeToVector(s, PSBT_GLOBAL_XPUB, ser_xpub);
997 [ + - ]: 11266 : SerializeHDKeypath(s, xpub_pair.first);
998 : 11266 : }
999 : 10222 : }
1000 : :
1001 : : // PSBT version
1002 [ + - ]: 56770 : if (GetVersion() > 0) {
1003 : 0 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_VERSION));
1004 : 0 : SerializeToVector(s, *m_version);
1005 : 0 : }
1006 : :
1007 : : // Write proprietary things
1008 [ + + ]: 61150 : for (const auto& entry : m_proprietary) {
1009 : 4380 : s << entry.key;
1010 : 4380 : s << entry.value;
1011 : 4380 : }
1012 : :
1013 : : // Write the unknown things
1014 [ + + ]: 138205 : for (auto& entry : unknown) {
1015 : 81435 : s << entry.first;
1016 : 81435 : s << entry.second;
1017 : 81435 : }
1018 : :
1019 : : // Separator
1020 : 56770 : s << PSBT_SEPARATOR;
1021 : :
1022 : : // Write inputs
1023 [ + + ]: 164570 : for (const PSBTInput& input : inputs) {
1024 : 107800 : s << input;
1025 : 107800 : }
1026 : : // Write outputs
1027 [ + + ]: 183749 : for (const PSBTOutput& output : outputs) {
1028 : 126979 : s << output;
1029 : 126979 : }
1030 : 56770 : }
1031 : :
1032 : :
1033 : : template <typename Stream>
1034 : 87955 : inline void Unserialize(Stream& s) {
1035 : : // Read the magic bytes
1036 : 87955 : uint8_t magic[5];
1037 : 87955 : s >> magic;
1038 [ + + ]: 87955 : if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
1039 [ + - + - ]: 479 : throw std::ios_base::failure("Invalid PSBT magic bytes");
1040 : : }
1041 : :
1042 : : // Used for duplicate key detection
1043 : 87476 : std::set<std::vector<unsigned char>> key_lookup;
1044 : :
1045 : : // Track the global xpubs we have already seen. Just for sanity checking
1046 : 87476 : std::set<CExtPubKey> global_xpubs;
1047 : :
1048 : : // Read global data
1049 : 87476 : bool found_sep = false;
1050 [ + - + + ]: 327499 : while(!s.empty()) {
1051 : : // Read
1052 : 327435 : std::vector<unsigned char> key;
1053 [ + + ]: 327435 : s >> key;
1054 : :
1055 : : // the key is empty if that was actually a separator byte
1056 : : // This is a special case for key lengths 0 as those are not allowed (except for separator)
1057 [ + + ]: 327231 : if (key.empty()) {
1058 : 86204 : found_sep = true;
1059 : 86204 : break;
1060 : : }
1061 : :
1062 : : // Type is compact size uint at beginning of key
1063 [ + - + - ]: 241027 : SpanReader skey{key};
1064 [ + + ]: 241027 : uint64_t type = ReadCompactSize(skey);
1065 : :
1066 : : // Do stuff based on type
1067 [ + + + + : 240987 : switch(type) {
+ ]
1068 : : case PSBT_GLOBAL_UNSIGNED_TX:
1069 : : {
1070 [ + - + + ]: 86872 : if (!key_lookup.emplace(key).second) {
1071 [ + - + - ]: 17 : throw std::ios_base::failure("Duplicate Key, unsigned tx already provided");
1072 [ + + ]: 86855 : } else if (key.size() != 1) {
1073 [ + - + - ]: 32 : throw std::ios_base::failure("Global unsigned tx key is more than one byte type");
1074 : : }
1075 [ + - ]: 86823 : CMutableTransaction mtx;
1076 : : // Set the stream to serialize with non-witness since this should always be non-witness
1077 [ + - + + ]: 86823 : UnserializeFromVector(s, TX_NO_WITNESS(mtx));
1078 : 86438 : tx = std::move(mtx);
1079 : : // Make sure that all scriptSigs and scriptWitnesses are empty
1080 [ + + ]: 238481 : for (const CTxIn& txin : tx->vin) {
1081 [ + - + + ]: 152043 : if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
1082 [ + - + - ]: 40 : throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
1083 : : }
1084 : 152043 : }
1085 : : break;
1086 : 86823 : }
1087 : : case PSBT_GLOBAL_XPUB:
1088 : : {
1089 [ + + ]: 20962 : if (key.size() != BIP32_EXTKEY_WITH_VERSION_SIZE + 1) {
1090 [ + - + - ]: 31 : throw std::ios_base::failure("Size of key was not the expected size for the type global xpub");
1091 : : }
1092 : : // Read in the xpub from key
1093 [ + - ]: 20931 : CExtPubKey xpub;
1094 [ + - ]: 20931 : xpub.DecodeWithVersion(&key.data()[1]);
1095 [ + - + + ]: 20931 : if (!xpub.pubkey.IsFullyValid()) {
1096 [ + - + - ]: 100 : throw std::ios_base::failure("Invalid pubkey");
1097 : : }
1098 [ + - + + ]: 20831 : if (global_xpubs.count(xpub) > 0) {
1099 [ + - + - ]: 16 : throw std::ios_base::failure("Duplicate key, global xpub already provided");
1100 : : }
1101 [ + - ]: 20815 : global_xpubs.insert(xpub);
1102 : : // Read in the keypath from stream
1103 : 20815 : KeyOriginInfo keypath;
1104 [ + + ]: 20815 : DeserializeHDKeypath(s, keypath);
1105 : :
1106 : : // Note that we store these swapped to make searches faster.
1107 : : // Serialization uses xpub -> keypath to enqure key uniqueness
1108 [ + - + + ]: 20743 : if (m_xpubs.count(keypath) == 0) {
1109 : : // Make a new set to put the xpub in
1110 [ + - + - ]: 18622 : m_xpubs[keypath] = {xpub};
1111 : 18622 : } else {
1112 : : // Insert xpub into existing set
1113 [ + - + - ]: 2121 : m_xpubs[keypath].insert(xpub);
1114 : : }
1115 : : break;
1116 : 20931 : }
1117 : : case PSBT_GLOBAL_VERSION:
1118 : : {
1119 [ + + ]: 127 : if (m_version) {
1120 [ + - + - ]: 6 : throw std::ios_base::failure("Duplicate Key, version already provided");
1121 [ + + ]: 121 : } else if (key.size() != 1) {
1122 [ + - + - ]: 13 : throw std::ios_base::failure("Global version key is more than one byte type");
1123 : : }
1124 : 108 : uint32_t v;
1125 [ + + ]: 108 : UnserializeFromVector(s, v);
1126 : 91 : m_version = v;
1127 [ + + ]: 91 : if (*m_version > PSBT_HIGHEST_VERSION) {
1128 [ + - + - ]: 12 : throw std::ios_base::failure("Unsupported version number");
1129 : : }
1130 : : break;
1131 : 108 : }
1132 : : case PSBT_GLOBAL_PROPRIETARY:
1133 : : {
1134 : 8044 : PSBTProprietary this_prop;
1135 [ + + ]: 8044 : skey >> this_prop.identifier;
1136 [ + - ]: 8010 : this_prop.subtype = ReadCompactSize(skey);
1137 [ + - ]: 8010 : this_prop.key = key;
1138 : :
1139 [ + - + + ]: 8010 : if (m_proprietary.count(this_prop) > 0) {
1140 [ + - + - ]: 13 : throw std::ios_base::failure("Duplicate Key, proprietary key already found");
1141 : : }
1142 [ + + ]: 7997 : s >> this_prop.value;
1143 [ + - ]: 7956 : m_proprietary.insert(this_prop);
1144 : : break;
1145 : 8044 : }
1146 : : // Unknown stuff
1147 : : default: {
1148 [ + - + + ]: 124982 : if (unknown.count(key) > 0) {
1149 [ + - + - ]: 33 : throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
1150 : : }
1151 : : // Read in the value
1152 : 124949 : std::vector<unsigned char> val_bytes;
1153 [ + + ]: 124949 : s >> val_bytes;
1154 [ + - ]: 124847 : unknown.emplace(std::move(key), std::move(val_bytes));
1155 : 124949 : }
1156 : 124847 : }
1157 [ + + ]: 327435 : }
1158 : :
1159 [ + + ]: 86268 : if (!found_sep) {
1160 [ + - + - ]: 64 : throw std::ios_base::failure("Separator is missing at the end of the global map");
1161 : : }
1162 : :
1163 : : // Make sure that we got an unsigned tx
1164 [ + + ]: 86204 : if (!tx) {
1165 [ + - + - ]: 75 : throw std::ios_base::failure("No unsigned transaction was provided");
1166 : : }
1167 : :
1168 : : // Read input data
1169 : 86129 : unsigned int i = 0;
1170 [ + - + + : 234211 : while (!s.empty() && i < tx->vin.size()) {
+ + ]
1171 [ + - ]: 150358 : PSBTInput input;
1172 [ + + ]: 150358 : s >> input;
1173 [ + - ]: 148106 : inputs.push_back(input);
1174 : :
1175 : : // Make sure the non-witness utxo matches the outpoint
1176 [ + + + - : 148106 : if (input.non_witness_utxo && input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
+ - + + ]
1177 [ + - + - ]: 24 : throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1178 : : }
1179 : 148082 : ++i;
1180 : 150358 : }
1181 : : // Make sure that the number of inputs matches the number of inputs in the transaction
1182 [ + + ]: 83853 : if (inputs.size() != tx->vin.size()) {
1183 [ + - + - ]: 42 : throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
1184 : : }
1185 : :
1186 : : // Read output data
1187 : 83811 : i = 0;
1188 [ + - + + : 264669 : while (!s.empty() && i < tx->vout.size()) {
+ + ]
1189 [ + - ]: 182479 : PSBTOutput output;
1190 [ + + ]: 182479 : s >> output;
1191 [ + - ]: 180858 : outputs.push_back(output);
1192 : 180858 : ++i;
1193 : 182479 : }
1194 : : // Make sure that the number of outputs matches the number of outputs in the transaction
1195 [ + + ]: 82190 : if (outputs.size() != tx->vout.size()) {
1196 [ + - + - ]: 84 : throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
1197 : : }
1198 : 93804 : }
1199 : :
1200 : : template <typename Stream>
1201 : : PartiallySignedTransaction(deserialize_type, Stream& s) {
1202 : : Unserialize(s);
1203 : : }
1204 : : };
1205 : :
1206 : : enum class PSBTRole {
1207 : : CREATOR,
1208 : : UPDATER,
1209 : : SIGNER,
1210 : : FINALIZER,
1211 : : EXTRACTOR
1212 : : };
1213 : :
1214 : : std::string PSBTRoleName(PSBTRole role);
1215 : :
1216 : : /** Compute a PrecomputedTransactionData object from a psbt. */
1217 : : PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt);
1218 : :
1219 : : /** Checks whether a PSBTInput is already signed by checking for non-null finalized fields. */
1220 : : bool PSBTInputSigned(const PSBTInput& input);
1221 : :
1222 : : /** Checks whether a PSBTInput is already signed by doing script verification using final fields. */
1223 : : bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
1224 : :
1225 : : /** Signs a PSBTInput, verifying that all provided data matches what is being signed.
1226 : : *
1227 : : * txdata should be the output of PrecomputePSBTData (which can be shared across
1228 : : * multiple SignPSBTInput calls). If it is nullptr, a dummy signature will be created.
1229 : : **/
1230 : : bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, int sighash = SIGHASH_ALL, SignatureData* out_sigdata = nullptr, bool finalize = true);
1231 : :
1232 : : /** 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. */
1233 : : void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx, const int& sighash_type);
1234 : :
1235 : : /** Counts the unsigned inputs of a PSBT. */
1236 : : size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt);
1237 : :
1238 : : /** Updates a PSBTOutput with information from provider.
1239 : : *
1240 : : * This fills in the redeem_script, witness_script, and hd_keypaths where possible.
1241 : : */
1242 : : void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index);
1243 : :
1244 : : /**
1245 : : * Finalizes a PSBT if possible, combining partial signatures.
1246 : : *
1247 : : * @param[in,out] psbtx PartiallySignedTransaction to finalize
1248 : : * return True if the PSBT is now complete, false otherwise
1249 : : */
1250 : : bool FinalizePSBT(PartiallySignedTransaction& psbtx);
1251 : :
1252 : : /**
1253 : : * Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
1254 : : *
1255 : : * @param[in] psbtx PartiallySignedTransaction
1256 : : * @param[out] result CMutableTransaction representing the complete transaction, if successful
1257 : : * @return True if we successfully extracted the transaction, false otherwise
1258 : : */
1259 : : bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result);
1260 : :
1261 : : /**
1262 : : * Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial signatures from each input.
1263 : : *
1264 : : * @param[out] out the combined PSBT, if successful
1265 : : * @param[in] psbtxs the PSBTs to combine
1266 : : * @return error (OK if we successfully combined the transactions, other error if they were not compatible)
1267 : : */
1268 : : [[nodiscard]] TransactionError CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs);
1269 : :
1270 : : //! Decode a base64ed PSBT into a PartiallySignedTransaction
1271 : : [[nodiscard]] bool DecodeBase64PSBT(PartiallySignedTransaction& decoded_psbt, const std::string& base64_psbt, std::string& error);
1272 : : //! Decode a raw (binary blob) PSBT into a PartiallySignedTransaction
1273 : : [[nodiscard]] bool DecodeRawPSBT(PartiallySignedTransaction& decoded_psbt, Span<const std::byte> raw_psbt, std::string& error);
1274 : :
1275 : : #endif // BITCOIN_PSBT_H
|