Bitcoin Core 29.99.0
P2P Digital Currency
psbt.h
Go to the documentation of this file.
1// Copyright (c) 2009-present The Bitcoin Core developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#ifndef BITCOIN_PSBT_H
6#define BITCOIN_PSBT_H
7
8#include <node/transaction.h>
9#include <policy/feerate.h>
11#include <pubkey.h>
12#include <script/keyorigin.h>
13#include <script/sign.h>
15#include <span.h>
16#include <streams.h>
17
18#include <optional>
19
20namespace node {
21enum class TransactionError;
22} // namespace node
23
24// Magic bytes
25static constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff};
26
27// Global types
28static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00;
29static constexpr uint8_t PSBT_GLOBAL_XPUB = 0x01;
30static constexpr uint8_t PSBT_GLOBAL_VERSION = 0xFB;
31static constexpr uint8_t PSBT_GLOBAL_PROPRIETARY = 0xFC;
32
33// Input types
34static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00;
35static constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01;
36static constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02;
37static constexpr uint8_t PSBT_IN_SIGHASH = 0x03;
38static constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04;
39static constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05;
40static constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06;
41static constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07;
42static constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08;
43static constexpr uint8_t PSBT_IN_RIPEMD160 = 0x0A;
44static constexpr uint8_t PSBT_IN_SHA256 = 0x0B;
45static constexpr uint8_t PSBT_IN_HASH160 = 0x0C;
46static constexpr uint8_t PSBT_IN_HASH256 = 0x0D;
47static constexpr uint8_t PSBT_IN_TAP_KEY_SIG = 0x13;
48static constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG = 0x14;
49static constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT = 0x15;
50static constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
51static constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY = 0x17;
52static constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT = 0x18;
53static constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS = 0x1a;
54static constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE = 0x1b;
55static constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG = 0x1c;
56static constexpr uint8_t PSBT_IN_PROPRIETARY = 0xFC;
57
58// Output types
59static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00;
60static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01;
61static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02;
62static constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
63static constexpr uint8_t PSBT_OUT_TAP_TREE = 0x06;
64static constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
65static constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS = 0x08;
66static constexpr uint8_t PSBT_OUT_PROPRIETARY = 0xFC;
67
68// The separator is 0x00. Reading this in means that the unserializer can interpret it
69// as a 0 length key which indicates that this is the separator. The separator has no value.
70static constexpr uint8_t PSBT_SEPARATOR = 0x00;
71
72// BIP 174 does not specify a maximum file size, but we set a limit anyway
73// to prevent reading a stream indefinitely and running out of memory.
74const std::streamsize MAX_FILE_SIZE_PSBT = 100000000; // 100 MB
75
76// PSBT version number
77static constexpr uint32_t PSBT_HIGHEST_VERSION = 0;
78
81{
82 uint64_t subtype;
83 std::vector<unsigned char> identifier;
84 std::vector<unsigned char> key;
85 std::vector<unsigned char> value;
86
87 bool operator<(const PSBTProprietary &b) const {
88 return key < b.key;
89 }
90 bool operator==(const PSBTProprietary &b) const {
91 return key == b.key;
92 }
93};
94
95// Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
96// The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
97template<typename Stream, typename... X>
98void SerializeToVector(Stream& s, const X&... args)
99{
100 SizeComputer sizecomp;
101 SerializeMany(sizecomp, args...);
102 WriteCompactSize(s, sizecomp.size());
103 SerializeMany(s, args...);
104}
105
106// Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
107template<typename Stream, typename... X>
108void UnserializeFromVector(Stream& s, X&&... args)
109{
110 size_t expected_size = ReadCompactSize(s);
111 size_t remaining_before = s.size();
113 size_t remaining_after = s.size();
114 if (remaining_after + expected_size != remaining_before) {
115 throw std::ios_base::failure("Size of value was not the stated size");
116 }
117}
118
119// Deserialize bytes of given length from the stream as a KeyOriginInfo
120template<typename Stream>
121KeyOriginInfo DeserializeKeyOrigin(Stream& s, uint64_t length)
122{
123 // Read in key path
124 if (length % 4 || length == 0) {
125 throw std::ios_base::failure("Invalid length for HD key path");
126 }
127
128 KeyOriginInfo hd_keypath;
129 s >> hd_keypath.fingerprint;
130 for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
131 uint32_t index;
132 s >> index;
133 hd_keypath.path.push_back(index);
134 }
135 return hd_keypath;
136}
137
138// Deserialize a length prefixed KeyOriginInfo from a stream
139template<typename Stream>
140void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
141{
142 hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
143}
144
145// Deserialize HD keypaths into a map
146template<typename Stream>
147void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
148{
149 // Make sure that the key is the size of pubkey + 1
150 if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
151 throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
152 }
153 // Read in the pubkey from key
154 CPubKey pubkey(key.begin() + 1, key.end());
155 if (!pubkey.IsFullyValid()) {
156 throw std::ios_base::failure("Invalid pubkey");
157 }
158 if (hd_keypaths.count(pubkey) > 0) {
159 throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided");
160 }
161
162 KeyOriginInfo keypath;
163 DeserializeHDKeypath(s, keypath);
164
165 // Add to map
166 hd_keypaths.emplace(pubkey, std::move(keypath));
167}
168
169// Serialize a KeyOriginInfo to a stream
170template<typename Stream>
171void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
172{
173 s << hd_keypath.fingerprint;
174 for (const auto& path : hd_keypath.path) {
175 s << path;
176 }
177}
178
179// Serialize a length prefixed KeyOriginInfo to a stream
180template<typename Stream>
181void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
182{
183 WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
184 SerializeKeyOrigin(s, hd_keypath);
185}
186
187// Serialize HD keypaths to a stream from a map
188template<typename Stream>
189void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
190{
191 for (const auto& keypath_pair : hd_keypaths) {
192 if (!keypath_pair.first.IsValid()) {
193 throw std::ios_base::failure("Invalid CPubKey being serialized");
194 }
195 SerializeToVector(s, type, std::span{keypath_pair.first});
196 SerializeHDKeypath(s, keypath_pair.second);
197 }
198}
199
200// Deserialize a PSBT_{IN/OUT}_MUSIG2_PARTICIPANT_PUBKEYS field
201template<typename Stream>
202void DeserializeMuSig2ParticipantPubkeys(Stream& s, SpanReader& skey, std::map<CPubKey, std::vector<CPubKey>>& out, std::string context)
203{
204 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
205 skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
206 CPubKey agg_pubkey(agg_pubkey_bytes);
207
208 std::vector<CPubKey> participants;
209 std::vector<unsigned char> val;
210 s >> val;
211 SpanReader s_val{val};
212 while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
213 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
214 s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
215 participants.emplace_back(std::span{part_pubkey_bytes});
216 }
217 if (!s_val.empty()) {
218 throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
219 }
220
221 out.emplace(agg_pubkey, participants);
222}
223
224// Deserialize the MuSig2 participant identifiers from PSBT_MUSIG2_{PUBNONCE/PARTIAL_SIG} fields
225// Both fields contain the same data after the type byte - aggregate pubkey | participant pubkey | leaf script hash
226template<typename Stream>
227void DeserializeMuSig2ParticipantDataIdentifier(Stream& skey, CPubKey& agg_pub, CPubKey& part_pub, uint256& leaf_hash)
228{
229 leaf_hash.SetNull();
230
231 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
232 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
233
234 skey >> std::as_writable_bytes(std::span{part_pubkey_bytes}) >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
235 agg_pub.Set(agg_pubkey_bytes.begin(), agg_pubkey_bytes.end());
236 part_pub.Set(part_pubkey_bytes.begin(), part_pubkey_bytes.end());
237
238 if (!skey.empty()) {
239 skey >> leaf_hash;
240 }
241}
242
245{
252 std::map<CPubKey, KeyOriginInfo> hd_keypaths;
253 std::map<CKeyID, SigPair> partial_sigs;
254 std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
255 std::map<uint256, std::vector<unsigned char>> sha256_preimages;
256 std::map<uint160, std::vector<unsigned char>> hash160_preimages;
257 std::map<uint256, std::vector<unsigned char>> hash256_preimages;
258
259 // Taproot fields
260 std::vector<unsigned char> m_tap_key_sig;
261 std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
262 std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
263 std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
266
267 // MuSig2 fields
268 std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
269 // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to pubnonce
270 std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, std::vector<uint8_t>>> m_musig2_pubnonces;
271 // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to partial_sig
272 std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, uint256>> m_musig2_partial_sigs;
273
274 std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
275 std::set<PSBTProprietary> m_proprietary;
276 std::optional<int> sighash_type;
277
278 bool IsNull() const;
279 void FillSignatureData(SignatureData& sigdata) const;
280 void FromSignatureData(const SignatureData& sigdata);
281 void Merge(const PSBTInput& input);
282 PSBTInput() = default;
283
284 template <typename Stream>
285 inline void Serialize(Stream& s) const {
286 // Write the utxo
287 if (non_witness_utxo) {
290 }
291 if (!witness_utxo.IsNull()) {
294 }
295
297 // Write any partial signatures
298 for (const auto& sig_pair : partial_sigs) {
299 SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
300 s << sig_pair.second.second;
301 }
302
303 // Write the sighash type
304 if (sighash_type != std::nullopt) {
307 }
308
309 // Write the redeem script
310 if (!redeem_script.empty()) {
312 s << redeem_script;
313 }
314
315 // Write the witness script
316 if (!witness_script.empty()) {
318 s << witness_script;
319 }
320
321 // Write any hd keypaths
323
324 // Write any ripemd160 preimage
325 for (const auto& [hash, preimage] : ripemd160_preimages) {
327 s << preimage;
328 }
329
330 // Write any sha256 preimage
331 for (const auto& [hash, preimage] : sha256_preimages) {
333 s << preimage;
334 }
335
336 // Write any hash160 preimage
337 for (const auto& [hash, preimage] : hash160_preimages) {
339 s << preimage;
340 }
341
342 // Write any hash256 preimage
343 for (const auto& [hash, preimage] : hash256_preimages) {
345 s << preimage;
346 }
347
348 // Write taproot key sig
349 if (!m_tap_key_sig.empty()) {
351 s << m_tap_key_sig;
352 }
353
354 // Write taproot script sigs
355 for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
356 const auto& [xonly, leaf_hash] = pubkey_leaf;
357 SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
358 s << sig;
359 }
360
361 // Write taproot leaf scripts
362 for (const auto& [leaf, control_blocks] : m_tap_scripts) {
363 const auto& [script, leaf_ver] = leaf;
364 for (const auto& control_block : control_blocks) {
365 SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, std::span{control_block});
366 std::vector<unsigned char> value_v(script.begin(), script.end());
367 value_v.push_back((uint8_t)leaf_ver);
368 s << value_v;
369 }
370 }
371
372 // Write taproot bip32 keypaths
373 for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
374 const auto& [leaf_hashes, origin] = leaf_origin;
376 std::vector<unsigned char> value;
377 VectorWriter s_value{value, 0};
378 s_value << leaf_hashes;
379 SerializeKeyOrigin(s_value, origin);
380 s << value;
381 }
382
383 // Write taproot internal key
384 if (!m_tap_internal_key.IsNull()) {
387 }
388
389 // Write taproot merkle root
390 if (!m_tap_merkle_root.IsNull()) {
393 }
394
395 // Write MuSig2 Participants
396 for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
398 std::vector<unsigned char> value;
399 VectorWriter s_value{value, 0};
400 for (auto& pk : part_pubs) {
401 s_value << std::span{pk};
402 }
403 s << value;
404 }
405
406 // Write MuSig2 pubnonces
407 for (const auto& [agg_pubkey_leaf_hash, pubnonces] : m_musig2_pubnonces) {
408 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
409 for (const auto& [part_pubkey, pubnonce] : pubnonces) {
410 if (leaf_hash.IsNull()) {
411 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey});
412 } else {
413 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey}, leaf_hash);
414 }
415 s << pubnonce;
416 }
417 }
418
419 // Write MuSig2 partial signatures
420 for (const auto& [agg_pubkey_leaf_hash, psigs] : m_musig2_partial_sigs) {
421 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
422 for (const auto& [pubkey, psig] : psigs) {
423 if (leaf_hash.IsNull()) {
424 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey});
425 } else {
426 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey}, leaf_hash);
427 }
428 SerializeToVector(s, psig);
429 }
430 }
431 }
432
433 // Write script sig
434 if (!final_script_sig.empty()) {
437 }
438 // write script witness
442 }
443
444 // Write proprietary things
445 for (const auto& entry : m_proprietary) {
446 s << entry.key;
447 s << entry.value;
448 }
449
450 // Write unknown things
451 for (auto& entry : unknown) {
452 s << entry.first;
453 s << entry.second;
454 }
455
456 s << PSBT_SEPARATOR;
457 }
458
459
460 template <typename Stream>
461 inline void Unserialize(Stream& s) {
462 // Used for duplicate key detection
463 std::set<std::vector<unsigned char>> key_lookup;
464
465 // Read loop
466 bool found_sep = false;
467 while(!s.empty()) {
468 // Read
469 std::vector<unsigned char> key;
470 s >> key;
471
472 // the key is empty if that was actually a separator byte
473 // This is a special case for key lengths 0 as those are not allowed (except for separator)
474 if (key.empty()) {
475 found_sep = true;
476 break;
477 }
478
479 // Type is compact size uint at beginning of key
480 SpanReader skey{key};
481 uint64_t type = ReadCompactSize(skey);
482
483 // Do stuff based on type
484 switch(type) {
486 {
487 if (!key_lookup.emplace(key).second) {
488 throw std::ios_base::failure("Duplicate Key, input non-witness utxo already provided");
489 } else if (key.size() != 1) {
490 throw std::ios_base::failure("Non-witness utxo key is more than one byte type");
491 }
492 // Set the stream to unserialize with witness since this is always a valid network transaction
494 break;
495 }
497 if (!key_lookup.emplace(key).second) {
498 throw std::ios_base::failure("Duplicate Key, input witness utxo already provided");
499 } else if (key.size() != 1) {
500 throw std::ios_base::failure("Witness utxo key is more than one byte type");
501 }
503 break;
505 {
506 // Make sure that the key is the size of pubkey + 1
507 if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
508 throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
509 }
510 // Read in the pubkey from key
511 CPubKey pubkey(key.begin() + 1, key.end());
512 if (!pubkey.IsFullyValid()) {
513 throw std::ios_base::failure("Invalid pubkey");
514 }
515 if (partial_sigs.count(pubkey.GetID()) > 0) {
516 throw std::ios_base::failure("Duplicate Key, input partial signature for pubkey already provided");
517 }
518
519 // Read in the signature from value
520 std::vector<unsigned char> sig;
521 s >> sig;
522
523 // Add to list
524 partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
525 break;
526 }
527 case PSBT_IN_SIGHASH:
528 if (!key_lookup.emplace(key).second) {
529 throw std::ios_base::failure("Duplicate Key, input sighash type already provided");
530 } else if (key.size() != 1) {
531 throw std::ios_base::failure("Sighash type key is more than one byte type");
532 }
533 int sighash;
534 UnserializeFromVector(s, sighash);
535 sighash_type = sighash;
536 break;
538 {
539 if (!key_lookup.emplace(key).second) {
540 throw std::ios_base::failure("Duplicate Key, input redeemScript already provided");
541 } else if (key.size() != 1) {
542 throw std::ios_base::failure("Input redeemScript key is more than one byte type");
543 }
544 s >> redeem_script;
545 break;
546 }
548 {
549 if (!key_lookup.emplace(key).second) {
550 throw std::ios_base::failure("Duplicate Key, input witnessScript already provided");
551 } else if (key.size() != 1) {
552 throw std::ios_base::failure("Input witnessScript key is more than one byte type");
553 }
554 s >> witness_script;
555 break;
556 }
558 {
560 break;
561 }
563 {
564 if (!key_lookup.emplace(key).second) {
565 throw std::ios_base::failure("Duplicate Key, input final scriptSig already provided");
566 } else if (key.size() != 1) {
567 throw std::ios_base::failure("Final scriptSig key is more than one byte type");
568 }
570 break;
571 }
573 {
574 if (!key_lookup.emplace(key).second) {
575 throw std::ios_base::failure("Duplicate Key, input final scriptWitness already provided");
576 } else if (key.size() != 1) {
577 throw std::ios_base::failure("Final scriptWitness key is more than one byte type");
578 }
580 break;
581 }
583 {
584 // Make sure that the key is the size of a ripemd160 hash + 1
585 if (key.size() != CRIPEMD160::OUTPUT_SIZE + 1) {
586 throw std::ios_base::failure("Size of key was not the expected size for the type ripemd160 preimage");
587 }
588 // Read in the hash from key
589 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
590 uint160 hash(hash_vec);
591 if (ripemd160_preimages.count(hash) > 0) {
592 throw std::ios_base::failure("Duplicate Key, input ripemd160 preimage already provided");
593 }
594
595 // Read in the preimage from value
596 std::vector<unsigned char> preimage;
597 s >> preimage;
598
599 // Add to preimages list
600 ripemd160_preimages.emplace(hash, std::move(preimage));
601 break;
602 }
603 case PSBT_IN_SHA256:
604 {
605 // Make sure that the key is the size of a sha256 hash + 1
606 if (key.size() != CSHA256::OUTPUT_SIZE + 1) {
607 throw std::ios_base::failure("Size of key was not the expected size for the type sha256 preimage");
608 }
609 // Read in the hash from key
610 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
611 uint256 hash(hash_vec);
612 if (sha256_preimages.count(hash) > 0) {
613 throw std::ios_base::failure("Duplicate Key, input sha256 preimage already provided");
614 }
615
616 // Read in the preimage from value
617 std::vector<unsigned char> preimage;
618 s >> preimage;
619
620 // Add to preimages list
621 sha256_preimages.emplace(hash, std::move(preimage));
622 break;
623 }
624 case PSBT_IN_HASH160:
625 {
626 // Make sure that the key is the size of a hash160 hash + 1
627 if (key.size() != CHash160::OUTPUT_SIZE + 1) {
628 throw std::ios_base::failure("Size of key was not the expected size for the type hash160 preimage");
629 }
630 // Read in the hash from key
631 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
632 uint160 hash(hash_vec);
633 if (hash160_preimages.count(hash) > 0) {
634 throw std::ios_base::failure("Duplicate Key, input hash160 preimage already provided");
635 }
636
637 // Read in the preimage from value
638 std::vector<unsigned char> preimage;
639 s >> preimage;
640
641 // Add to preimages list
642 hash160_preimages.emplace(hash, std::move(preimage));
643 break;
644 }
645 case PSBT_IN_HASH256:
646 {
647 // Make sure that the key is the size of a hash256 hash + 1
648 if (key.size() != CHash256::OUTPUT_SIZE + 1) {
649 throw std::ios_base::failure("Size of key was not the expected size for the type hash256 preimage");
650 }
651 // Read in the hash from key
652 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
653 uint256 hash(hash_vec);
654 if (hash256_preimages.count(hash) > 0) {
655 throw std::ios_base::failure("Duplicate Key, input hash256 preimage already provided");
656 }
657
658 // Read in the preimage from value
659 std::vector<unsigned char> preimage;
660 s >> preimage;
661
662 // Add to preimages list
663 hash256_preimages.emplace(hash, std::move(preimage));
664 break;
665 }
667 {
668 if (!key_lookup.emplace(key).second) {
669 throw std::ios_base::failure("Duplicate Key, input Taproot key signature already provided");
670 } else if (key.size() != 1) {
671 throw std::ios_base::failure("Input Taproot key signature key is more than one byte type");
672 }
673 s >> m_tap_key_sig;
674 if (m_tap_key_sig.size() < 64) {
675 throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
676 } else if (m_tap_key_sig.size() > 65) {
677 throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
678 }
679 break;
680 }
682 {
683 if (!key_lookup.emplace(key).second) {
684 throw std::ios_base::failure("Duplicate Key, input Taproot script signature already provided");
685 } else if (key.size() != 65) {
686 throw std::ios_base::failure("Input Taproot script signature key is not 65 bytes");
687 }
688 SpanReader s_key{std::span{key}.subspan(1)};
689 XOnlyPubKey xonly;
690 uint256 hash;
691 s_key >> xonly;
692 s_key >> hash;
693 std::vector<unsigned char> sig;
694 s >> sig;
695 if (sig.size() < 64) {
696 throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
697 } else if (sig.size() > 65) {
698 throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
699 }
700 m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
701 break;
702 }
704 {
705 if (!key_lookup.emplace(key).second) {
706 throw std::ios_base::failure("Duplicate Key, input Taproot leaf script already provided");
707 } else if (key.size() < 34) {
708 throw std::ios_base::failure("Taproot leaf script key is not at least 34 bytes");
709 } else if ((key.size() - 2) % 32 != 0) {
710 throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
711 }
712 std::vector<unsigned char> script_v;
713 s >> script_v;
714 if (script_v.empty()) {
715 throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
716 }
717 uint8_t leaf_ver = script_v.back();
718 script_v.pop_back();
719 const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
720 m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
721 break;
722 }
724 {
725 if (!key_lookup.emplace(key).second) {
726 throw std::ios_base::failure("Duplicate Key, input Taproot BIP32 keypath already provided");
727 } else if (key.size() != 33) {
728 throw std::ios_base::failure("Input Taproot BIP32 keypath key is not at 33 bytes");
729 }
730 SpanReader s_key{std::span{key}.subspan(1)};
731 XOnlyPubKey xonly;
732 s_key >> xonly;
733 std::set<uint256> leaf_hashes;
734 uint64_t value_len = ReadCompactSize(s);
735 size_t before_hashes = s.size();
736 s >> leaf_hashes;
737 size_t after_hashes = s.size();
738 size_t hashes_len = before_hashes - after_hashes;
739 if (hashes_len > value_len) {
740 throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
741 }
742 size_t origin_len = value_len - hashes_len;
743 m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
744 break;
745 }
747 {
748 if (!key_lookup.emplace(key).second) {
749 throw std::ios_base::failure("Duplicate Key, input Taproot internal key already provided");
750 } else if (key.size() != 1) {
751 throw std::ios_base::failure("Input Taproot internal key key is more than one byte type");
752 }
754 break;
755 }
757 {
758 if (!key_lookup.emplace(key).second) {
759 throw std::ios_base::failure("Duplicate Key, input Taproot merkle root already provided");
760 } else if (key.size() != 1) {
761 throw std::ios_base::failure("Input Taproot merkle root key is more than one byte type");
762 }
764 break;
765 }
767 {
768 if (!key_lookup.emplace(key).second) {
769 throw std::ios_base::failure("Duplicate Key, input participant pubkeys for an aggregate key already provided");
770 } else if (key.size() != CPubKey::COMPRESSED_SIZE + 1) {
771 throw std::ios_base::failure("Input musig2 participants pubkeys aggregate key is not 34 bytes");
772 }
773 DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
774 break;
775 }
777 {
778 if (!key_lookup.emplace(key).second) {
779 throw std::ios_base::failure("Duplicate Key, input musig2 pubnonce already provided");
780 } else if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
781 throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
782 }
783 CPubKey agg_pub, part_pub;
784 uint256 leaf_hash;
785 DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
786
787 std::vector<uint8_t> pubnonce;
788 s >> pubnonce;
789 if (pubnonce.size() != 66) {
790 throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
791 }
792
793 m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
794 break;
795 }
797 {
798 if (!key_lookup.emplace(key).second) {
799 throw std::ios_base::failure("Duplicate Key, input musig2 partial sig already provided");
800 } else if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
801 throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
802 }
803 CPubKey agg_pub, part_pub;
804 uint256 leaf_hash;
805 DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
806
807 uint256 partial_sig;
808 UnserializeFromVector(s, partial_sig);
809
810 m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
811 break;
812 }
814 {
815 PSBTProprietary this_prop;
816 skey >> this_prop.identifier;
817 this_prop.subtype = ReadCompactSize(skey);
818 this_prop.key = key;
819
820 if (m_proprietary.count(this_prop) > 0) {
821 throw std::ios_base::failure("Duplicate Key, proprietary key already found");
822 }
823 s >> this_prop.value;
824 m_proprietary.insert(this_prop);
825 break;
826 }
827 // Unknown stuff
828 default:
829 if (unknown.count(key) > 0) {
830 throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
831 }
832 // Read in the value
833 std::vector<unsigned char> val_bytes;
834 s >> val_bytes;
835 unknown.emplace(std::move(key), std::move(val_bytes));
836 break;
837 }
838 }
839
840 if (!found_sep) {
841 throw std::ios_base::failure("Separator is missing at the end of an input map");
842 }
843 }
844
845 template <typename Stream>
847 Unserialize(s);
848 }
849};
850
853{
856 std::map<CPubKey, KeyOriginInfo> hd_keypaths;
858 std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
859 std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
860 std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
861 std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
862 std::set<PSBTProprietary> m_proprietary;
863
864 bool IsNull() const;
865 void FillSignatureData(SignatureData& sigdata) const;
866 void FromSignatureData(const SignatureData& sigdata);
867 void Merge(const PSBTOutput& output);
868 PSBTOutput() = default;
869
870 template <typename Stream>
871 inline void Serialize(Stream& s) const {
872 // Write the redeem script
873 if (!redeem_script.empty()) {
875 s << redeem_script;
876 }
877
878 // Write the witness script
879 if (!witness_script.empty()) {
881 s << witness_script;
882 }
883
884 // Write any hd keypaths
886
887 // Write proprietary things
888 for (const auto& entry : m_proprietary) {
889 s << entry.key;
890 s << entry.value;
891 }
892
893 // Write taproot internal key
894 if (!m_tap_internal_key.IsNull()) {
897 }
898
899 // Write taproot tree
900 if (!m_tap_tree.empty()) {
902 std::vector<unsigned char> value;
903 VectorWriter s_value{value, 0};
904 for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
905 s_value << depth;
906 s_value << leaf_ver;
907 s_value << script;
908 }
909 s << value;
910 }
911
912 // Write taproot bip32 keypaths
913 for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
914 const auto& [leaf_hashes, origin] = leaf;
916 std::vector<unsigned char> value;
917 VectorWriter s_value{value, 0};
918 s_value << leaf_hashes;
919 SerializeKeyOrigin(s_value, origin);
920 s << value;
921 }
922
923 // Write MuSig2 Participants
924 for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
926 std::vector<unsigned char> value;
927 VectorWriter s_value{value, 0};
928 for (auto& pk : part_pubs) {
929 s_value << std::span{pk};
930 }
931 s << value;
932 }
933
934 // Write unknown things
935 for (auto& entry : unknown) {
936 s << entry.first;
937 s << entry.second;
938 }
939
940 s << PSBT_SEPARATOR;
941 }
942
943
944 template <typename Stream>
945 inline void Unserialize(Stream& s) {
946 // Used for duplicate key detection
947 std::set<std::vector<unsigned char>> key_lookup;
948
949 // Read loop
950 bool found_sep = false;
951 while(!s.empty()) {
952 // Read
953 std::vector<unsigned char> key;
954 s >> key;
955
956 // the key is empty if that was actually a separator byte
957 // This is a special case for key lengths 0 as those are not allowed (except for separator)
958 if (key.empty()) {
959 found_sep = true;
960 break;
961 }
962
963 // Type is compact size uint at beginning of key
964 SpanReader skey{key};
965 uint64_t type = ReadCompactSize(skey);
966
967 // Do stuff based on type
968 switch(type) {
970 {
971 if (!key_lookup.emplace(key).second) {
972 throw std::ios_base::failure("Duplicate Key, output redeemScript already provided");
973 } else if (key.size() != 1) {
974 throw std::ios_base::failure("Output redeemScript key is more than one byte type");
975 }
976 s >> redeem_script;
977 break;
978 }
980 {
981 if (!key_lookup.emplace(key).second) {
982 throw std::ios_base::failure("Duplicate Key, output witnessScript already provided");
983 } else if (key.size() != 1) {
984 throw std::ios_base::failure("Output witnessScript key is more than one byte type");
985 }
986 s >> witness_script;
987 break;
988 }
990 {
992 break;
993 }
995 {
996 if (!key_lookup.emplace(key).second) {
997 throw std::ios_base::failure("Duplicate Key, output Taproot internal key already provided");
998 } else if (key.size() != 1) {
999 throw std::ios_base::failure("Output Taproot internal key key is more than one byte type");
1000 }
1002 break;
1003 }
1004 case PSBT_OUT_TAP_TREE:
1005 {
1006 if (!key_lookup.emplace(key).second) {
1007 throw std::ios_base::failure("Duplicate Key, output Taproot tree already provided");
1008 } else if (key.size() != 1) {
1009 throw std::ios_base::failure("Output Taproot tree key is more than one byte type");
1010 }
1011 std::vector<unsigned char> tree_v;
1012 s >> tree_v;
1013 SpanReader s_tree{tree_v};
1014 if (s_tree.empty()) {
1015 throw std::ios_base::failure("Output Taproot tree must not be empty");
1016 }
1017 TaprootBuilder builder;
1018 while (!s_tree.empty()) {
1019 uint8_t depth;
1020 uint8_t leaf_ver;
1021 std::vector<unsigned char> script;
1022 s_tree >> depth;
1023 s_tree >> leaf_ver;
1024 s_tree >> script;
1025 if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1026 throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
1027 }
1028 if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
1029 throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
1030 }
1031 m_tap_tree.emplace_back(depth, leaf_ver, script);
1032 builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
1033 }
1034 if (!builder.IsComplete()) {
1035 throw std::ios_base::failure("Output Taproot tree is malformed");
1036 }
1037 break;
1038 }
1040 {
1041 if (!key_lookup.emplace(key).second) {
1042 throw std::ios_base::failure("Duplicate Key, output Taproot BIP32 keypath already provided");
1043 } else if (key.size() != 33) {
1044 throw std::ios_base::failure("Output Taproot BIP32 keypath key is not at 33 bytes");
1045 }
1046 XOnlyPubKey xonly(uint256(std::span<uint8_t>(key).last(32)));
1047 std::set<uint256> leaf_hashes;
1048 uint64_t value_len = ReadCompactSize(s);
1049 size_t before_hashes = s.size();
1050 s >> leaf_hashes;
1051 size_t after_hashes = s.size();
1052 size_t hashes_len = before_hashes - after_hashes;
1053 if (hashes_len > value_len) {
1054 throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
1055 }
1056 size_t origin_len = value_len - hashes_len;
1057 m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
1058 break;
1059 }
1061 {
1062 if (!key_lookup.emplace(key).second) {
1063 throw std::ios_base::failure("Duplicate Key, output participant pubkeys for an aggregate key already provided");
1064 } else if (key.size() != CPubKey::COMPRESSED_SIZE + 1) {
1065 throw std::ios_base::failure("Output musig2 participants pubkeys aggregate key is not 34 bytes");
1066 }
1067 DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Output"});
1068 break;
1069 }
1071 {
1072 PSBTProprietary this_prop;
1073 skey >> this_prop.identifier;
1074 this_prop.subtype = ReadCompactSize(skey);
1075 this_prop.key = key;
1076
1077 if (m_proprietary.count(this_prop) > 0) {
1078 throw std::ios_base::failure("Duplicate Key, proprietary key already found");
1079 }
1080 s >> this_prop.value;
1081 m_proprietary.insert(this_prop);
1082 break;
1083 }
1084 // Unknown stuff
1085 default: {
1086 if (unknown.count(key) > 0) {
1087 throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
1088 }
1089 // Read in the value
1090 std::vector<unsigned char> val_bytes;
1091 s >> val_bytes;
1092 unknown.emplace(std::move(key), std::move(val_bytes));
1093 break;
1094 }
1095 }
1096 }
1097
1098 if (!found_sep) {
1099 throw std::ios_base::failure("Separator is missing at the end of an output map");
1100 }
1101 }
1102
1103 template <typename Stream>
1105 Unserialize(s);
1106 }
1107};
1108
1111{
1112 std::optional<CMutableTransaction> tx;
1113 // We use a vector of CExtPubKey in the event that there happens to be the same KeyOriginInfos for different CExtPubKeys
1114 // Note that this map swaps the key and values from the serialization
1115 std::map<KeyOriginInfo, std::set<CExtPubKey>> m_xpubs;
1116 std::vector<PSBTInput> inputs;
1117 std::vector<PSBTOutput> outputs;
1118 std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
1119 std::optional<uint32_t> m_version;
1120 std::set<PSBTProprietary> m_proprietary;
1121
1122 bool IsNull() const;
1123 uint32_t GetVersion() const;
1124
1127 [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
1128 bool AddInput(const CTxIn& txin, PSBTInput& psbtin);
1129 bool AddOutput(const CTxOut& txout, const PSBTOutput& psbtout);
1139 bool GetInputUTXO(CTxOut& utxo, int input_index) const;
1140
1141 template <typename Stream>
1142 inline void Serialize(Stream& s) const {
1143
1144 // magic bytes
1146
1147 // unsigned tx flag
1149
1150 // Write serialized tx to a stream
1152
1153 // Write xpubs
1154 for (const auto& xpub_pair : m_xpubs) {
1155 for (const auto& xpub : xpub_pair.second) {
1156 unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
1157 xpub.EncodeWithVersion(ser_xpub);
1158 // Note that the serialization swaps the key and value
1159 // The xpub is the key (for uniqueness) while the path is the value
1161 SerializeHDKeypath(s, xpub_pair.first);
1162 }
1163 }
1164
1165 // PSBT version
1166 if (GetVersion() > 0) {
1169 }
1170
1171 // Write proprietary things
1172 for (const auto& entry : m_proprietary) {
1173 s << entry.key;
1174 s << entry.value;
1175 }
1176
1177 // Write the unknown things
1178 for (auto& entry : unknown) {
1179 s << entry.first;
1180 s << entry.second;
1181 }
1182
1183 // Separator
1184 s << PSBT_SEPARATOR;
1185
1186 // Write inputs
1187 for (const PSBTInput& input : inputs) {
1188 s << input;
1189 }
1190 // Write outputs
1191 for (const PSBTOutput& output : outputs) {
1192 s << output;
1193 }
1194 }
1195
1196
1197 template <typename Stream>
1198 inline void Unserialize(Stream& s) {
1199 // Read the magic bytes
1200 uint8_t magic[5];
1201 s >> magic;
1202 if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
1203 throw std::ios_base::failure("Invalid PSBT magic bytes");
1204 }
1205
1206 // Used for duplicate key detection
1207 std::set<std::vector<unsigned char>> key_lookup;
1208
1209 // Track the global xpubs we have already seen. Just for sanity checking
1210 std::set<CExtPubKey> global_xpubs;
1211
1212 // Read global data
1213 bool found_sep = false;
1214 while(!s.empty()) {
1215 // Read
1216 std::vector<unsigned char> key;
1217 s >> key;
1218
1219 // the key is empty if that was actually a separator byte
1220 // This is a special case for key lengths 0 as those are not allowed (except for separator)
1221 if (key.empty()) {
1222 found_sep = true;
1223 break;
1224 }
1225
1226 // Type is compact size uint at beginning of key
1227 SpanReader skey{key};
1228 uint64_t type = ReadCompactSize(skey);
1229
1230 // Do stuff based on type
1231 switch(type) {
1233 {
1234 if (!key_lookup.emplace(key).second) {
1235 throw std::ios_base::failure("Duplicate Key, unsigned tx already provided");
1236 } else if (key.size() != 1) {
1237 throw std::ios_base::failure("Global unsigned tx key is more than one byte type");
1238 }
1240 // Set the stream to serialize with non-witness since this should always be non-witness
1242 tx = std::move(mtx);
1243 // Make sure that all scriptSigs and scriptWitnesses are empty
1244 for (const CTxIn& txin : tx->vin) {
1245 if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
1246 throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
1247 }
1248 }
1249 break;
1250 }
1251 case PSBT_GLOBAL_XPUB:
1252 {
1253 if (key.size() != BIP32_EXTKEY_WITH_VERSION_SIZE + 1) {
1254 throw std::ios_base::failure("Size of key was not the expected size for the type global xpub");
1255 }
1256 // Read in the xpub from key
1257 CExtPubKey xpub;
1258 xpub.DecodeWithVersion(&key.data()[1]);
1259 if (!xpub.pubkey.IsFullyValid()) {
1260 throw std::ios_base::failure("Invalid pubkey");
1261 }
1262 if (global_xpubs.count(xpub) > 0) {
1263 throw std::ios_base::failure("Duplicate key, global xpub already provided");
1264 }
1265 global_xpubs.insert(xpub);
1266 // Read in the keypath from stream
1267 KeyOriginInfo keypath;
1268 DeserializeHDKeypath(s, keypath);
1269
1270 // Note that we store these swapped to make searches faster.
1271 // Serialization uses xpub -> keypath to enqure key uniqueness
1272 if (m_xpubs.count(keypath) == 0) {
1273 // Make a new set to put the xpub in
1274 m_xpubs[keypath] = {xpub};
1275 } else {
1276 // Insert xpub into existing set
1277 m_xpubs[keypath].insert(xpub);
1278 }
1279 break;
1280 }
1282 {
1283 if (m_version) {
1284 throw std::ios_base::failure("Duplicate Key, version already provided");
1285 } else if (key.size() != 1) {
1286 throw std::ios_base::failure("Global version key is more than one byte type");
1287 }
1288 uint32_t v;
1290 m_version = v;
1292 throw std::ios_base::failure("Unsupported version number");
1293 }
1294 break;
1295 }
1297 {
1298 PSBTProprietary this_prop;
1299 skey >> this_prop.identifier;
1300 this_prop.subtype = ReadCompactSize(skey);
1301 this_prop.key = key;
1302
1303 if (m_proprietary.count(this_prop) > 0) {
1304 throw std::ios_base::failure("Duplicate Key, proprietary key already found");
1305 }
1306 s >> this_prop.value;
1307 m_proprietary.insert(this_prop);
1308 break;
1309 }
1310 // Unknown stuff
1311 default: {
1312 if (unknown.count(key) > 0) {
1313 throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
1314 }
1315 // Read in the value
1316 std::vector<unsigned char> val_bytes;
1317 s >> val_bytes;
1318 unknown.emplace(std::move(key), std::move(val_bytes));
1319 }
1320 }
1321 }
1322
1323 if (!found_sep) {
1324 throw std::ios_base::failure("Separator is missing at the end of the global map");
1325 }
1326
1327 // Make sure that we got an unsigned tx
1328 if (!tx) {
1329 throw std::ios_base::failure("No unsigned transaction was provided");
1330 }
1331
1332 // Read input data
1333 unsigned int i = 0;
1334 while (!s.empty() && i < tx->vin.size()) {
1335 PSBTInput input;
1336 s >> input;
1337 inputs.push_back(input);
1338
1339 // Make sure the non-witness utxo matches the outpoint
1340 if (input.non_witness_utxo) {
1341 if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
1342 throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1343 }
1344 if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
1345 throw std::ios_base::failure("Input specifies output index that does not exist");
1346 }
1347 }
1348 ++i;
1349 }
1350 // Make sure that the number of inputs matches the number of inputs in the transaction
1351 if (inputs.size() != tx->vin.size()) {
1352 throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
1353 }
1354
1355 // Read output data
1356 i = 0;
1357 while (!s.empty() && i < tx->vout.size()) {
1358 PSBTOutput output;
1359 s >> output;
1360 outputs.push_back(output);
1361 ++i;
1362 }
1363 // Make sure that the number of outputs matches the number of outputs in the transaction
1364 if (outputs.size() != tx->vout.size()) {
1365 throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
1366 }
1367 }
1368
1369 template <typename Stream>
1371 Unserialize(s);
1372 }
1373};
1374
1375enum class PSBTRole {
1376 CREATOR,
1377 UPDATER,
1378 SIGNER,
1379 FINALIZER,
1380 EXTRACTOR
1381};
1382
1383std::string PSBTRoleName(PSBTRole role);
1384
1387
1389bool PSBTInputSigned(const PSBTInput& input);
1390
1392bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
1393
1399bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, int sighash = SIGHASH_ALL, SignatureData* out_sigdata = nullptr, bool finalize = true);
1400
1402void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx, const int& sighash_type);
1403
1406
1411void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index);
1412
1420
1429
1437[[nodiscard]] bool CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs);
1438
1440[[nodiscard]] bool DecodeBase64PSBT(PartiallySignedTransaction& decoded_psbt, const std::string& base64_psbt, std::string& error);
1442[[nodiscard]] bool DecodeRawPSBT(PartiallySignedTransaction& decoded_psbt, std::span<const std::byte> raw_psbt, std::string& error);
1443
1444#endif // BITCOIN_PSBT_H
ArgsManager & args
Definition: bitcoind.cpp:277
static const size_t OUTPUT_SIZE
Definition: hash.h:53
static const size_t OUTPUT_SIZE
Definition: hash.h:28
An encapsulated public key.
Definition: pubkey.h:34
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:164
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:40
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:39
bool IsFullyValid() const
fully validate whether this is a valid public key (more expensive than IsValid())
Definition: pubkey.cpp:314
void Set(const T pbegin, const T pend)
Initialize a public key using begin/end iterators to byte data.
Definition: pubkey.h:89
static const size_t OUTPUT_SIZE
Definition: ripemd160.h:20
static const size_t OUTPUT_SIZE
Definition: sha256.h:21
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:415
An input of a transaction.
Definition: transaction.h:67
CScript scriptSig
Definition: transaction.h:70
CScriptWitness scriptWitness
Only serialized through CTransaction.
Definition: transaction.h:72
An output of a transaction.
Definition: transaction.h:150
bool IsNull() const
Definition: transaction.h:170
An interface to be implemented by keystores that support signing.
size_t size() const
Definition: serialize.h:1086
Minimal stream for reading from an existing byte array by std::span.
Definition: streams.h:101
Utility class to construct Taproot outputs from internal key and script tree.
bool IsComplete() const
Return whether there were either no leaves, or the leaves form a Huffman tree.
TaprootBuilder & Add(int depth, std::span< const unsigned char > script, int leaf_version, bool track=true)
Add a new script at a certain depth in the tree.
bool IsNull() const
Test whether this is the 0 key (the result of default construction).
Definition: pubkey.h:254
constexpr bool IsNull() const
Definition: uint256.h:48
constexpr void SetNull()
Definition: uint256.h:55
bool empty() const
Definition: prevector.h:298
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
static constexpr uint8_t TAPROOT_LEAF_MASK
Definition: interpreter.h:231
@ SIGHASH_ALL
Definition: interpreter.h:30
static constexpr size_t TAPROOT_CONTROL_MAX_NODE_COUNT
Definition: interpreter.h:235
Definition: messages.h:20
TransactionError
Definition: types.h:23
#define X(name)
Definition: net.cpp:619
static constexpr TransactionSerParams TX_NO_WITNESS
Definition: transaction.h:196
static constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:195
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
void SerializeToVector(Stream &s, const X &... args)
Definition: psbt.h:98
static constexpr uint8_t PSBT_IN_RIPEMD160
Definition: psbt.h:43
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:338
static constexpr uint8_t PSBT_IN_HASH256
Definition: psbt.h:46
static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX
Definition: psbt.h:28
static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO
Definition: psbt.h:34
bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData *txdata)
Checks whether a PSBTInput is already signed by doing script verification using final fields.
Definition: psbt.cpp:298
static constexpr uint8_t PSBT_IN_TAP_KEY_SIG
Definition: psbt.h:47
void UnserializeFromVector(Stream &s, X &&... args)
Definition: psbt.h:108
static constexpr uint8_t PSBT_IN_SCRIPTSIG
Definition: psbt.h:41
static constexpr uint8_t PSBT_IN_WITNESSSCRIPT
Definition: psbt.h:39
std::string PSBTRoleName(PSBTRole role)
Definition: psbt.cpp:524
static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT
Definition: psbt.h:59
static constexpr uint8_t PSBT_GLOBAL_VERSION
Definition: psbt.h:30
static constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT
Definition: psbt.h:49
bool CombinePSBTs(PartiallySignedTransaction &out, const std::vector< PartiallySignedTransaction > &psbtxs)
Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial sign...
Definition: psbt.cpp:511
static constexpr uint8_t PSBT_OUT_PROPRIETARY
Definition: psbt.h:66
static constexpr uint8_t PSBT_MAGIC_BYTES[5]
Definition: psbt.h:25
static constexpr uint32_t PSBT_HIGHEST_VERSION
Definition: psbt.h:77
static constexpr uint8_t PSBT_SEPARATOR
Definition: psbt.h:70
static constexpr uint8_t PSBT_IN_BIP32_DERIVATION
Definition: psbt.h:40
void DeserializeMuSig2ParticipantPubkeys(Stream &s, SpanReader &skey, std::map< CPubKey, std::vector< CPubKey > > &out, std::string context)
Definition: psbt.h:202
static constexpr uint8_t PSBT_IN_SCRIPTWITNESS
Definition: psbt.h:42
static constexpr uint8_t PSBT_OUT_TAP_TREE
Definition: psbt.h:63
static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION
Definition: psbt.h:61
PSBTRole
Definition: psbt.h:1375
static constexpr uint8_t PSBT_GLOBAL_PROPRIETARY
Definition: psbt.h:31
static constexpr uint8_t PSBT_IN_PROPRIETARY
Definition: psbt.h:56
KeyOriginInfo DeserializeKeyOrigin(Stream &s, uint64_t length)
Definition: psbt.h:121
void DeserializeMuSig2ParticipantDataIdentifier(Stream &skey, CPubKey &agg_pub, CPubKey &part_pub, uint256 &leaf_hash)
Definition: psbt.h:227
static constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG
Definition: psbt.h:48
static constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE
Definition: psbt.h:54
void SerializeHDKeypaths(Stream &s, const std::map< CPubKey, KeyOriginInfo > &hd_keypaths, CompactSizeWriter type)
Definition: psbt.h:189
static constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION
Definition: psbt.h:50
static constexpr uint8_t PSBT_IN_HASH160
Definition: psbt.h:45
static constexpr uint8_t PSBT_IN_REDEEMSCRIPT
Definition: psbt.h:38
bool DecodeBase64PSBT(PartiallySignedTransaction &decoded_psbt, const std::string &base64_psbt, std::string &error)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:536
static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT
Definition: psbt.h:60
static constexpr uint8_t PSBT_GLOBAL_XPUB
Definition: psbt.h:29
static constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS
Definition: psbt.h:65
bool SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, int sighash=SIGHASH_ALL, SignatureData *out_sigdata=nullptr, bool finalize=true)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:375
static constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION
Definition: psbt.h:64
static constexpr uint8_t PSBT_IN_PARTIAL_SIG
Definition: psbt.h:36
static constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY
Definition: psbt.h:51
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction &psbt)
Counts the unsigned inputs of a PSBT.
Definition: psbt.cpp:327
bool FinalizeAndExtractPSBT(PartiallySignedTransaction &psbtx, CMutableTransaction &result)
Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
Definition: psbt.cpp:495
static constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY
Definition: psbt.h:62
bool DecodeRawPSBT(PartiallySignedTransaction &decoded_psbt, std::span< const std::byte > raw_psbt, std::string &error)
Decode a raw (binary blob) PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:546
void RemoveUnnecessaryTransactions(PartiallySignedTransaction &psbtx, const int &sighash_type)
Reduces the size of the PSBT by dropping unnecessary non_witness_utxos (i.e.
Definition: psbt.cpp:448
static constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT
Definition: psbt.h:52
void SerializeKeyOrigin(Stream &s, KeyOriginInfo hd_keypath)
Definition: psbt.h:171
void DeserializeHDKeypaths(Stream &s, const std::vector< unsigned char > &key, std::map< CPubKey, KeyOriginInfo > &hd_keypaths)
Definition: psbt.h:147
static constexpr uint8_t PSBT_IN_SIGHASH
Definition: psbt.h:37
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
Definition: psbt.cpp:293
static constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS
Definition: psbt.h:53
void SerializeHDKeypath(Stream &s, KeyOriginInfo hd_keypath)
Definition: psbt.h:181
PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:358
void DeserializeHDKeypath(Stream &s, KeyOriginInfo &hd_keypath)
Definition: psbt.h:140
bool FinalizePSBT(PartiallySignedTransaction &psbtx)
Finalizes a PSBT if possible, combining partial signatures.
Definition: psbt.cpp:480
const std::streamsize MAX_FILE_SIZE_PSBT
Definition: psbt.h:74
static constexpr uint8_t PSBT_IN_WITNESS_UTXO
Definition: psbt.h:35
static constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG
Definition: psbt.h:55
static constexpr uint8_t PSBT_IN_SHA256
Definition: psbt.h:44
const unsigned int BIP32_EXTKEY_WITH_VERSION_SIZE
Definition: pubkey.h:20
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:67
void SerializeMany(Stream &s, const Args &... args)
Support for (un)serializing many things at once.
Definition: serialize.h:994
void UnserializeMany(Stream &s, Args &&... args)
Definition: serialize.h:1000
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1097
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:339
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:63
void DecodeWithVersion(const unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE])
Definition: pubkey.cpp:400
CPubKey pubkey
Definition: pubkey.h:348
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< std::vector< unsigned char > > stack
Definition: script.h:588
bool IsNull() const
Definition: script.h:593
unsigned char fingerprint[4]
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:13
std::vector< uint32_t > path
Definition: keyorigin.h:14
A structure for PSBTs which contain per-input information.
Definition: psbt.h:245
std::vector< unsigned char > m_tap_key_sig
Definition: psbt.h:260
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:252
PSBTInput(deserialize_type, Stream &s)
Definition: psbt.h:846
std::map< uint256, std::vector< unsigned char > > hash256_preimages
Definition: psbt.h:257
CScriptWitness final_script_witness
Definition: psbt.h:251
std::map< std::pair< CPubKey, uint256 >, std::map< CPubKey, std::vector< uint8_t > > > m_musig2_pubnonces
Definition: psbt.h:270
std::map< std::pair< std::vector< unsigned char >, int >, std::set< std::vector< unsigned char >, ShortestVectorFirstComparator > > m_tap_scripts
Definition: psbt.h:262
CTransactionRef non_witness_utxo
Definition: psbt.h:246
std::map< CKeyID, SigPair > partial_sigs
Definition: psbt.h:253
std::optional< int > sighash_type
Definition: psbt.h:276
std::map< std::pair< XOnlyPubKey, uint256 >, std::vector< unsigned char > > m_tap_script_sigs
Definition: psbt.h:261
void Serialize(Stream &s) const
Definition: psbt.h:285
uint256 m_tap_merkle_root
Definition: psbt.h:265
std::map< uint256, std::vector< unsigned char > > sha256_preimages
Definition: psbt.h:255
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:94
std::map< std::pair< CPubKey, uint256 >, std::map< CPubKey, uint256 > > m_musig2_partial_sigs
Definition: psbt.h:272
std::map< uint160, std::vector< unsigned char > > hash160_preimages
Definition: psbt.h:256
bool IsNull() const
Definition: psbt.cpp:89
void Merge(const PSBTInput &input)
Definition: psbt.cpp:198
void Unserialize(Stream &s)
Definition: psbt.h:461
PSBTInput()=default
std::map< CPubKey, std::vector< CPubKey > > m_musig2_participants
Definition: psbt.h:268
std::set< PSBTProprietary > m_proprietary
Definition: psbt.h:275
CScript redeem_script
Definition: psbt.h:248
CScript final_script_sig
Definition: psbt.h:250
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:151
XOnlyPubKey m_tap_internal_key
Definition: psbt.h:264
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > m_tap_bip32_paths
Definition: psbt.h:263
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:274
std::map< uint160, std::vector< unsigned char > > ripemd160_preimages
Definition: psbt.h:254
CTxOut witness_utxo
Definition: psbt.h:247
CScript witness_script
Definition: psbt.h:249
A structure for PSBTs which contains per output information.
Definition: psbt.h:853
std::map< CPubKey, std::vector< CPubKey > > m_musig2_participants
Definition: psbt.h:860
XOnlyPubKey m_tap_internal_key
Definition: psbt.h:857
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > m_tap_bip32_paths
Definition: psbt.h:859
CScript witness_script
Definition: psbt.h:855
bool IsNull() const
Definition: psbt.cpp:276
void Merge(const PSBTOutput &output)
Definition: psbt.cpp:281
std::set< PSBTProprietary > m_proprietary
Definition: psbt.h:862
CScript redeem_script
Definition: psbt.h:854
void Serialize(Stream &s) const
Definition: psbt.h:871
PSBTOutput(deserialize_type, Stream &s)
Definition: psbt.h:1104
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:856
PSBTOutput()=default
std::vector< std::tuple< uint8_t, uint8_t, std::vector< unsigned char > > > m_tap_tree
Definition: psbt.h:858
void Unserialize(Stream &s)
Definition: psbt.h:945
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:861
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:225
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:254
A structure for PSBT proprietary types.
Definition: psbt.h:81
std::vector< unsigned char > value
Definition: psbt.h:85
bool operator<(const PSBTProprietary &b) const
Definition: psbt.h:87
uint64_t subtype
Definition: psbt.h:82
std::vector< unsigned char > identifier
Definition: psbt.h:83
std::vector< unsigned char > key
Definition: psbt.h:84
bool operator==(const PSBTProprietary &b) const
Definition: psbt.h:90
A version of CTransaction with the PSBT format.
Definition: psbt.h:1111
uint32_t GetVersion() const
Definition: psbt.cpp:562
bool Merge(const PartiallySignedTransaction &psbt)
Merge psbt into this.
Definition: psbt.cpp:24
std::map< KeyOriginInfo, std::set< CExtPubKey > > m_xpubs
Definition: psbt.h:1115
std::optional< uint32_t > m_version
Definition: psbt.h:1119
bool IsNull() const
Definition: psbt.cpp:19
bool GetInputUTXO(CTxOut &utxo, int input_index) const
Finds the UTXO for a given input index.
Definition: psbt.cpp:69
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:1118
bool AddOutput(const CTxOut &txout, const PSBTOutput &psbtout)
Definition: psbt.cpp:62
std::vector< PSBTInput > inputs
Definition: psbt.h:1116
PartiallySignedTransaction()=default
std::optional< CMutableTransaction > tx
Definition: psbt.h:1112
bool AddInput(const CTxIn &txin, PSBTInput &psbtin)
Definition: psbt.cpp:49
std::vector< PSBTOutput > outputs
Definition: psbt.h:1117
std::set< PSBTProprietary > m_proprietary
Definition: psbt.h:1120
void Serialize(Stream &s) const
Definition: psbt.h:1142
PartiallySignedTransaction(deserialize_type, Stream &s)
Definition: psbt.h:1370
void Unserialize(Stream &s)
Definition: psbt.h:1198
Dummy data type to identify deserializing constructors.
Definition: serialize.h:48