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