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