Bitcoin Core 31.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#include <uint256.h>
19#include <util/result.h>
20
21#include <optional>
22#include <bitset>
23
24namespace node {
25enum class TransactionError;
26} // namespace node
27
29
30// Magic bytes
31static constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff};
32
33// Global types
34static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00;
35static constexpr uint8_t PSBT_GLOBAL_XPUB = 0x01;
36static constexpr uint8_t PSBT_GLOBAL_TX_VERSION = 0x02;
37static constexpr uint8_t PSBT_GLOBAL_FALLBACK_LOCKTIME = 0x03;
38static constexpr uint8_t PSBT_GLOBAL_INPUT_COUNT = 0x04;
39static constexpr uint8_t PSBT_GLOBAL_OUTPUT_COUNT = 0x05;
40static constexpr uint8_t PSBT_GLOBAL_TX_MODIFIABLE = 0x06;
41static constexpr uint8_t PSBT_GLOBAL_VERSION = 0xFB;
42static constexpr uint8_t PSBT_GLOBAL_PROPRIETARY = 0xFC;
43
44// Input types
45static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00;
46static constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01;
47static constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02;
48static constexpr uint8_t PSBT_IN_SIGHASH = 0x03;
49static constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04;
50static constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05;
51static constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06;
52static constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07;
53static constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08;
54static constexpr uint8_t PSBT_IN_RIPEMD160 = 0x0A;
55static constexpr uint8_t PSBT_IN_SHA256 = 0x0B;
56static constexpr uint8_t PSBT_IN_HASH160 = 0x0C;
57static constexpr uint8_t PSBT_IN_HASH256 = 0x0D;
58static constexpr uint8_t PSBT_IN_PREVIOUS_TXID = 0x0e;
59static constexpr uint8_t PSBT_IN_OUTPUT_INDEX = 0x0f;
60static constexpr uint8_t PSBT_IN_SEQUENCE = 0x10;
61static constexpr uint8_t PSBT_IN_REQUIRED_TIME_LOCKTIME = 0x11;
62static constexpr uint8_t PSBT_IN_REQUIRED_HEIGHT_LOCKTIME = 0x12;
63static constexpr uint8_t PSBT_IN_TAP_KEY_SIG = 0x13;
64static constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG = 0x14;
65static constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT = 0x15;
66static constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
67static constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY = 0x17;
68static constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT = 0x18;
69static constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS = 0x1a;
70static constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE = 0x1b;
71static constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG = 0x1c;
72static constexpr uint8_t PSBT_IN_PROPRIETARY = 0xFC;
73
74// Output types
75static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00;
76static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01;
77static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02;
78static constexpr uint8_t PSBT_OUT_AMOUNT = 0x03;
79static constexpr uint8_t PSBT_OUT_SCRIPT = 0x04;
80static constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
81static constexpr uint8_t PSBT_OUT_TAP_TREE = 0x06;
82static constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
83static constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS = 0x08;
84static constexpr uint8_t PSBT_OUT_PROPRIETARY = 0xFC;
85
86// The separator is 0x00. Reading this in means that the unserializer can interpret it
87// as a 0 length key which indicates that this is the separator. The separator has no value.
88static constexpr uint8_t PSBT_SEPARATOR = 0x00;
89
90// BIP 174 does not specify a maximum file size, but we set a limit anyway
91// to prevent reading a stream indefinitely and running out of memory.
92const std::streamsize MAX_FILE_SIZE_PSBT = 100000000; // 100 MB
93
94// PSBT version number
95static constexpr uint32_t PSBT_HIGHEST_VERSION = 2;
96
99{
100 uint64_t subtype;
101 std::vector<unsigned char> identifier;
102 std::vector<unsigned char> key;
103 std::vector<unsigned char> value;
104
105 bool operator<(const PSBTProprietary &b) const {
106 return key < b.key;
107 }
108 bool operator==(const PSBTProprietary &b) const {
109 return key == b.key;
110 }
111};
112
113// Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
114// The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
115template<typename Stream, typename... X>
116void SerializeToVector(Stream& s, const X&... args)
117{
118 SizeComputer sizecomp;
119 SerializeMany(sizecomp, args...);
120 WriteCompactSize(s, sizecomp.size());
121 SerializeMany(s, args...);
122}
123
124// Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
125template<typename Stream, typename... X>
126void UnserializeFromVector(Stream& s, X&&... args)
127{
128 size_t expected_size = ReadCompactSize(s);
129 size_t remaining_before = s.size();
131 size_t remaining_after = s.size();
132 if (remaining_after + expected_size != remaining_before) {
133 throw std::ios_base::failure("Size of value was not the stated size");
134 }
135}
136
137// Deserialize bytes of given length from the stream as a KeyOriginInfo
138template<typename Stream>
139KeyOriginInfo DeserializeKeyOrigin(Stream& s, uint64_t length)
140{
141 // Read in key path
142 if (length % 4 || length == 0) {
143 throw std::ios_base::failure("Invalid length for HD key path");
144 }
145
146 KeyOriginInfo hd_keypath;
147 s >> hd_keypath.fingerprint;
148 for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
149 uint32_t index;
150 s >> index;
151 hd_keypath.path.push_back(index);
152 }
153 return hd_keypath;
154}
155
156// Deserialize a length prefixed KeyOriginInfo from a stream
157template<typename Stream>
158void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
159{
160 hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
161}
162
163// Deserialize HD keypaths into a map
164template<typename Stream>
165void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
166{
167 // Make sure that the key is the size of pubkey + 1
168 if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
169 throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
170 }
171 // Read in the pubkey from key
172 CPubKey pubkey(key.begin() + 1, key.end());
173 if (!pubkey.IsFullyValid()) {
174 throw std::ios_base::failure("Invalid pubkey");
175 }
176
177 KeyOriginInfo keypath;
178 DeserializeHDKeypath(s, keypath);
179
180 // Add to map
181 hd_keypaths.emplace(pubkey, std::move(keypath));
182}
183
184// Serialize a KeyOriginInfo to a stream
185template<typename Stream>
186void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
187{
188 s << hd_keypath.fingerprint;
189 for (const auto& path : hd_keypath.path) {
190 s << path;
191 }
192}
193
194// Serialize a length prefixed KeyOriginInfo to a stream
195template<typename Stream>
196void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
197{
198 WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
199 SerializeKeyOrigin(s, hd_keypath);
200}
201
202// Serialize HD keypaths to a stream from a map
203template<typename Stream>
204void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
205{
206 for (const auto& keypath_pair : hd_keypaths) {
207 if (!keypath_pair.first.IsValid()) {
208 throw std::ios_base::failure("Invalid CPubKey being serialized");
209 }
210 SerializeToVector(s, type, std::span{keypath_pair.first});
211 SerializeHDKeypath(s, keypath_pair.second);
212 }
213}
214
215// Deserialize a PSBT_{IN/OUT}_MUSIG2_PARTICIPANT_PUBKEYS field
216template<typename Stream>
217void DeserializeMuSig2ParticipantPubkeys(Stream& s, SpanReader& skey, std::map<CPubKey, std::vector<CPubKey>>& out, std::string context)
218{
219 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
220 skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
221 CPubKey agg_pubkey(agg_pubkey_bytes);
222 if (!agg_pubkey.IsFullyValid()) {
223 throw std::ios_base::failure(context + " musig2 aggregate pubkey is invalid");
224 }
225
226 std::vector<CPubKey> participants;
227 std::vector<unsigned char> val;
228 s >> val;
229 SpanReader s_val{val};
230 while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
231 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
232 s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
233 CPubKey participant(part_pubkey_bytes);
234 if (!participant.IsFullyValid()) {
235 throw std::ios_base::failure(context + " musig2 participant pubkey is invalid");
236 }
237 participants.push_back(participant);
238 }
239 if (!s_val.empty()) {
240 throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
241 }
242
243 out.emplace(agg_pubkey, participants);
244}
245
246// Deserialize the MuSig2 participant identifiers from PSBT_MUSIG2_{PUBNONCE/PARTIAL_SIG} fields
247// Both fields contain the same data after the type byte - aggregate pubkey | participant pubkey | leaf script hash
248template<typename Stream>
249void DeserializeMuSig2ParticipantDataIdentifier(Stream& skey, CPubKey& agg_pub, CPubKey& part_pub, uint256& leaf_hash)
250{
251 leaf_hash.SetNull();
252
253 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
254 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
255
256 skey >> std::as_writable_bytes(std::span{part_pubkey_bytes}) >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
257 agg_pub.Set(agg_pubkey_bytes.begin(), agg_pubkey_bytes.end());
258 if (!agg_pub.IsFullyValid()) {
259 throw std::ios_base::failure("musig2 aggregate pubkey is invalid");
260 }
261
262 part_pub.Set(part_pubkey_bytes.begin(), part_pubkey_bytes.end());
263 if (!part_pub.IsFullyValid()) {
264 throw std::ios_base::failure("musig2 participant pubkey is invalid");
265 }
266
267 if (!skey.empty()) {
268 skey >> leaf_hash;
269 }
270}
271
272static inline void ExpectedKeySize(const std::string& key_name, const std::vector<unsigned char>& key, uint64_t expected_size) {
273 if (key.size() != expected_size) {
274 throw std::ios_base::failure(tfm::format("Size of key was not %d for the type %s", expected_size, key_name));
275 }
276}
277
280{
281private:
283
284public:
291 std::map<CPubKey, KeyOriginInfo> hd_keypaths;
292 std::map<CKeyID, SigPair> partial_sigs;
293 std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
294 std::map<uint256, std::vector<unsigned char>> sha256_preimages;
295 std::map<uint160, std::vector<unsigned char>> hash160_preimages;
296 std::map<uint256, std::vector<unsigned char>> hash256_preimages;
297
299 uint32_t prev_out;
300 std::optional<uint32_t> sequence;
301 std::optional<uint32_t> time_locktime;
302 std::optional<uint32_t> height_locktime;
303
304 // Taproot fields
305 std::vector<unsigned char> m_tap_key_sig;
306 std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
307 std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
308 std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
311
312 // MuSig2 fields
313 std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
314 // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to pubnonce
315 std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, std::vector<uint8_t>>> m_musig2_pubnonces;
316 // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to partial_sig
317 std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, uint256>> m_musig2_partial_sigs;
318
319 std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
320 std::set<PSBTProprietary> m_proprietary;
321 std::optional<int> sighash_type;
322
323 bool IsNull() const;
324 void FillSignatureData(SignatureData& sigdata) const;
325 void FromSignatureData(const SignatureData& sigdata);
326 [[nodiscard]] bool Merge(const PSBTInput& input);
327 uint32_t GetVersion() const { return m_psbt_version; }
328 COutPoint GetOutPoint() const;
335 bool GetUTXO(CTxOut& utxo) const;
336 bool HasSignatures() const;
337
338 explicit PSBTInput(uint32_t psbt_version, const Txid& prev_txid, uint32_t prev_out, std::optional<uint32_t> sequence = std::nullopt)
339 : m_psbt_version(psbt_version),
343 {
345 }
346
347 // Construct a PSBTInput when the previous txid and output index are expected to be serialized
348 template <typename Stream>
349 explicit PSBTInput(deserialize_type, Stream& s, uint32_t psbt_version)
350 : m_psbt_version(psbt_version)
351 {
353 Unserialize(s);
354 }
355
356 bool operator==(const PSBTInput&) const = default;
357
358 template <typename Stream>
359 inline void Serialize(Stream& s) const {
360 // Write the utxo
361 if (non_witness_utxo) {
364 }
365 if (!witness_utxo.IsNull()) {
368 }
369
371 // Write any partial signatures
372 for (const auto& sig_pair : partial_sigs) {
373 SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
374 s << sig_pair.second.second;
375 }
376
377 // Write the sighash type
378 if (sighash_type != std::nullopt) {
381 }
382
383 // Write the redeem script
384 if (!redeem_script.empty()) {
386 s << redeem_script;
387 }
388
389 // Write the witness script
390 if (!witness_script.empty()) {
392 s << witness_script;
393 }
394
395 // Write any hd keypaths
397
398 // Write any ripemd160 preimage
399 for (const auto& [hash, preimage] : ripemd160_preimages) {
401 s << preimage;
402 }
403
404 // Write any sha256 preimage
405 for (const auto& [hash, preimage] : sha256_preimages) {
407 s << preimage;
408 }
409
410 // Write any hash160 preimage
411 for (const auto& [hash, preimage] : hash160_preimages) {
413 s << preimage;
414 }
415
416 // Write any hash256 preimage
417 for (const auto& [hash, preimage] : hash256_preimages) {
419 s << preimage;
420 }
421
422 // Write taproot key sig
423 if (!m_tap_key_sig.empty()) {
425 s << m_tap_key_sig;
426 }
427
428 // Write taproot script sigs
429 for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
430 const auto& [xonly, leaf_hash] = pubkey_leaf;
431 SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
432 s << sig;
433 }
434
435 // Write taproot leaf scripts
436 for (const auto& [leaf, control_blocks] : m_tap_scripts) {
437 const auto& [script, leaf_ver] = leaf;
438 for (const auto& control_block : control_blocks) {
439 SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, std::span{control_block});
440 std::vector<unsigned char> value_v(script.begin(), script.end());
441 value_v.push_back((uint8_t)leaf_ver);
442 s << value_v;
443 }
444 }
445
446 // Write taproot bip32 keypaths
447 for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
448 const auto& [leaf_hashes, origin] = leaf_origin;
450 std::vector<unsigned char> value;
451 VectorWriter s_value{value, 0};
452 s_value << leaf_hashes;
453 SerializeKeyOrigin(s_value, origin);
454 s << value;
455 }
456
457 // Write taproot internal key
458 if (!m_tap_internal_key.IsNull()) {
461 }
462
463 // Write taproot merkle root
464 if (!m_tap_merkle_root.IsNull()) {
467 }
468
469 // Write MuSig2 Participants
470 for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
472 std::vector<unsigned char> value;
473 VectorWriter s_value{value, 0};
474 for (auto& pk : part_pubs) {
475 s_value << std::span{pk};
476 }
477 s << value;
478 }
479
480 // Write MuSig2 pubnonces
481 for (const auto& [agg_pubkey_leaf_hash, pubnonces] : m_musig2_pubnonces) {
482 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
483 for (const auto& [part_pubkey, pubnonce] : pubnonces) {
484 if (leaf_hash.IsNull()) {
485 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey});
486 } else {
487 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey}, leaf_hash);
488 }
489 s << pubnonce;
490 }
491 }
492
493 // Write MuSig2 partial signatures
494 for (const auto& [agg_pubkey_leaf_hash, psigs] : m_musig2_partial_sigs) {
495 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
496 for (const auto& [pubkey, psig] : psigs) {
497 if (leaf_hash.IsNull()) {
498 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey});
499 } else {
500 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey}, leaf_hash);
501 }
502 SerializeToVector(s, psig);
503 }
504 }
505 }
506
507 // Write script sig
508 if (!final_script_sig.empty()) {
511 }
512 // write script witness
516 }
517
518 // Write PSBTv2 fields
519 if (m_psbt_version >= 2) {
520 // Write prev txid, vout, sequence, and lock times
523
526
527 if (sequence != std::nullopt) {
530 }
531 if (time_locktime != std::nullopt) {
534 }
535 if (height_locktime != std::nullopt) {
538 }
539 }
540
541 // Write proprietary things
542 for (const auto& entry : m_proprietary) {
543 s << entry.key;
544 s << entry.value;
545 }
546
547 // Write unknown things
548 for (auto& entry : unknown) {
549 s << entry.first;
550 s << entry.second;
551 }
552
553 s << PSBT_SEPARATOR;
554 }
555
556
557 template <typename Stream>
558 inline void Unserialize(Stream& s) {
559 // Used for duplicate key detection
560 std::set<std::vector<unsigned char>> key_lookup;
561 // Cache whether PSBTv2 required fields were seen
562 bool found_prev_txid = false;
563 bool found_prev_out = false;
564
565 // Read loop
566 bool found_sep = false;
567 while(!s.empty()) {
568 // Read the key of format "<keylen><keytype><keydata>" after which
569 // "key" will contain "<keytype><keydata>"
570 std::vector<unsigned char> key;
571 s >> key;
572
573 // the key is empty if that was actually a separator byte
574 // This is a special case for key lengths 0 as those are not allowed (except for separator)
575 if (key.empty()) {
576 found_sep = true;
577 break;
578 }
579
580 // Duplicate keys are not permitted
581 if (!key_lookup.emplace(key).second) {
582 throw std::ios_base::failure(tfm::format("Duplicate Key, input key \"%s\" already provided", HexStr(key)));
583 }
584
585 // "skey" is used so that "key" is unchanged after reading keytype below
586 SpanReader skey{key};
587 // keytype is of the format compact size uint at the beginning of "key"
588 uint64_t type = ReadCompactSize(skey);
589
590 // Do stuff based on keytype "type", i.e., key checks, reading values of the
591 // format "<valuelen><valuedata>" from the stream "s", and value checks
592 switch(type) {
594 {
595 ExpectedKeySize("Input Non-witness UTXO", key, 1);
596 // Set the stream to unserialize with witness since this is always a valid network transaction
598 break;
599 }
601 ExpectedKeySize("Input Witness UTXO", key, 1);
603 break;
605 {
606 // Make sure that the key is the size of pubkey + 1
607 if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
608 throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
609 }
610 // Read in the pubkey from key
611 CPubKey pubkey(key.begin() + 1, key.end());
612 if (!pubkey.IsFullyValid()) {
613 throw std::ios_base::failure("Invalid pubkey");
614 }
615
616 // Read in the signature from value
617 std::vector<unsigned char> sig;
618 s >> sig;
619
620 // Check that the signature is validly encoded
621 if (sig.empty() || !CheckSignatureEncoding(sig, SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC, nullptr)) {
622 throw std::ios_base::failure("Signature is not a valid encoding");
623 }
624
625 // Add to list
626 partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
627 break;
628 }
629 case PSBT_IN_SIGHASH:
630 ExpectedKeySize("Input Sighash Type", key, 1);
631 int sighash;
632 UnserializeFromVector(s, sighash);
633 sighash_type = sighash;
634 break;
636 {
637 ExpectedKeySize("Input redeemScript", key, 1);
638 s >> redeem_script;
639 break;
640 }
642 {
643 ExpectedKeySize("Input witnessScript", key, 1);
644 s >> witness_script;
645 break;
646 }
648 {
650 break;
651 }
653 {
654 ExpectedKeySize("Input Final scriptSig", key, 1);
656 break;
657 }
659 {
660 ExpectedKeySize("Input Final scriptWitness", key, 1);
662 break;
663 }
665 {
666 ExpectedKeySize("Input RIPEMD160 Preimage", key, CRIPEMD160::OUTPUT_SIZE + 1);
667 // Read in the hash from key
668 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
669 uint160 hash(hash_vec);
670
671 // Read in the preimage from value
672 std::vector<unsigned char> preimage;
673 s >> preimage;
674
675 // Add to preimages list
676 ripemd160_preimages.emplace(hash, std::move(preimage));
677 break;
678 }
679 case PSBT_IN_SHA256:
680 {
681 ExpectedKeySize("Input SHA256 Preimage", key, CSHA256::OUTPUT_SIZE + 1);
682 // Read in the hash from key
683 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
684 uint256 hash(hash_vec);
685
686 // Read in the preimage from value
687 std::vector<unsigned char> preimage;
688 s >> preimage;
689
690 // Add to preimages list
691 sha256_preimages.emplace(hash, std::move(preimage));
692 break;
693 }
694 case PSBT_IN_HASH160:
695 {
696 ExpectedKeySize("Input Hash160 Preimage", key, CHash160::OUTPUT_SIZE + 1);
697 // Read in the hash from key
698 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
699 uint160 hash(hash_vec);
700
701 // Read in the preimage from value
702 std::vector<unsigned char> preimage;
703 s >> preimage;
704
705 // Add to preimages list
706 hash160_preimages.emplace(hash, std::move(preimage));
707 break;
708 }
709 case PSBT_IN_HASH256:
710 {
711 ExpectedKeySize("Input Hash256 Preimage", key, CHash256::OUTPUT_SIZE + 1);
712 // Read in the hash from key
713 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
714 uint256 hash(hash_vec);
715
716 // Read in the preimage from value
717 std::vector<unsigned char> preimage;
718 s >> preimage;
719
720 // Add to preimages list
721 hash256_preimages.emplace(hash, std::move(preimage));
722 break;
723 }
725 {
726 ExpectedKeySize("Input Previous TXID", key, 1);
727 if (m_psbt_version < 2) {
728 throw std::ios_base::failure("Previous txid is not allowed in PSBTv0");
729 }
731 found_prev_txid = true;
732 break;
733 }
735 {
736 ExpectedKeySize("Input Previous Output's Index", key, 1);
737 if (m_psbt_version < 2) {
738 throw std::ios_base::failure("Previous output's index is not allowed in PSBTv0");
739 }
741 found_prev_out = true;
742 break;
743 }
744 case PSBT_IN_SEQUENCE:
745 {
746 ExpectedKeySize("Input Sequence", key, 1);
747 if (m_psbt_version < 2) {
748 throw std::ios_base::failure("Sequence is not allowed in PSBTv0");
749 }
750 sequence.emplace();
752 break;
753 }
755 {
756 ExpectedKeySize("Input Required Time Based Locktime", key, 1);
757 if (m_psbt_version < 2) {
758 throw std::ios_base::failure("Required time based locktime is not allowed in PSBTv0");
759 }
760 time_locktime.emplace();
763 throw std::ios_base::failure("Required time based locktime is invalid (less than 500000000)");
764 }
765 break;
766 }
768 {
769 ExpectedKeySize("Input Required Height Based Locktime", key, 1);
770 if (m_psbt_version < 2) {
771 throw std::ios_base::failure("Required height based locktime is not allowed in PSBTv0");
772 }
773 height_locktime.emplace();
776 throw std::ios_base::failure("Required height based locktime is invalid (greater than or equal to 500000000)");
777 } else if (*height_locktime == 0) {
778 throw std::ios_base::failure("Required height based locktime is invalid (0)");
779 }
780 break;
781 }
783 {
784 ExpectedKeySize("Input Taproot Key Path Signature", key, 1);
785 s >> m_tap_key_sig;
786 if (m_tap_key_sig.size() < 64) {
787 throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
788 } else if (m_tap_key_sig.size() > 65) {
789 throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
790 }
791 break;
792 }
794 {
795 ExpectedKeySize("Input Taproot Script Path Signature", key, 65);
796 SpanReader s_key{std::span{key}.subspan(1)};
797 XOnlyPubKey xonly;
798 uint256 hash;
799 s_key >> xonly;
800 s_key >> hash;
801 std::vector<unsigned char> sig;
802 s >> sig;
803 if (sig.size() < 64) {
804 throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
805 } else if (sig.size() > 65) {
806 throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
807 }
808 m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
809 break;
810 }
812 {
813 if (key.size() < 34) {
814 throw std::ios_base::failure("Input Taproot leaf script key is not at least 34 bytes");
815 } else if ((key.size() - 2) % 32 != 0) {
816 throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
817 }
818 std::vector<unsigned char> script_v;
819 s >> script_v;
820 if (script_v.empty()) {
821 throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
822 }
823 uint8_t leaf_ver = script_v.back();
824 script_v.pop_back();
825 const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
826 m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
827 break;
828 }
830 {
831 ExpectedKeySize("Input Taproot BIP32 Keypath", key, 33);
832 SpanReader s_key{std::span{key}.subspan(1)};
833 XOnlyPubKey xonly;
834 s_key >> xonly;
835 std::set<uint256> leaf_hashes;
836 uint64_t value_len = ReadCompactSize(s);
837 size_t before_hashes = s.size();
838 s >> leaf_hashes;
839 size_t after_hashes = s.size();
840 size_t hashes_len = before_hashes - after_hashes;
841 if (hashes_len > value_len) {
842 throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
843 }
844 size_t origin_len = value_len - hashes_len;
845 m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
846 break;
847 }
849 {
850 ExpectedKeySize("Input Taproot Internal Key", key, 1);
852 break;
853 }
855 {
856 ExpectedKeySize("Input Taproot Merkle Root", key, 1);
858 break;
859 }
861 {
862 ExpectedKeySize("Input MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
863 DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
864 break;
865 }
867 {
868 if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
869 throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
870 }
871 CPubKey agg_pub, part_pub;
872 uint256 leaf_hash;
873 DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
874
875 std::vector<uint8_t> pubnonce;
876 s >> pubnonce;
877 if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) {
878 throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
879 }
880
881 m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
882 break;
883 }
885 {
886 if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
887 throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
888 }
889 CPubKey agg_pub, part_pub;
890 uint256 leaf_hash;
891 DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
892
893 uint256 partial_sig;
894 UnserializeFromVector(s, partial_sig);
895
896 m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
897 break;
898 }
900 {
901 PSBTProprietary this_prop;
902 skey >> this_prop.identifier;
903 this_prop.subtype = ReadCompactSize(skey);
904 this_prop.key = key;
905
906 s >> this_prop.value;
907 m_proprietary.insert(this_prop);
908 break;
909 }
910 // Unknown stuff
911 default:
912 // Read in the value
913 std::vector<unsigned char> val_bytes;
914 s >> val_bytes;
915 unknown.emplace(std::move(key), std::move(val_bytes));
916 break;
917 }
918 }
919
920 if (!found_sep) {
921 throw std::ios_base::failure("Separator is missing at the end of an input map");
922 }
923
924 // Make sure required PSBTv2 fields are present
925 if (m_psbt_version >= 2) {
926 if (!found_prev_txid) {
927 throw std::ios_base::failure("Previous TXID is required in PSBTv2");
928 }
929 if (!found_prev_out) {
930 throw std::ios_base::failure("Previous output's index is required in PSBTv2");
931 }
932 }
933 }
934};
935
938{
939private:
941
942public:
945 std::map<CPubKey, KeyOriginInfo> hd_keypaths;
946
948 std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
949 std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
950 std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
951
952 std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
953 std::set<PSBTProprietary> m_proprietary;
954
957
958 bool IsNull() const;
959 void FillSignatureData(SignatureData& sigdata) const;
960 void FromSignatureData(const SignatureData& sigdata);
961 [[nodiscard]] bool Merge(const PSBTOutput& output);
962 uint32_t GetVersion() const { return m_psbt_version; }
963
964 explicit PSBTOutput(uint32_t psbt_version, CAmount amount, const CScript& script)
965 : m_psbt_version(psbt_version),
966 amount(amount),
968 {
970 }
971
972 // Construct a PSBTOutput when the amount and script are expected to be serialized
973 template <typename Stream>
974 explicit PSBTOutput(deserialize_type, Stream& s, uint32_t psbt_version)
975 : m_psbt_version(psbt_version)
976 {
978 Unserialize(s);
979 }
980
981 bool operator==(const PSBTOutput&) const = default;
982
983 template <typename Stream>
984 inline void Serialize(Stream& s) const {
985 // Write the redeem script
986 if (!redeem_script.empty()) {
988 s << redeem_script;
989 }
990
991 // Write the witness script
992 if (!witness_script.empty()) {
994 s << witness_script;
995 }
996
997 // Write any hd keypaths
999
1000 if (m_psbt_version >= 2) {
1001 // Write amount and spk
1004
1006 s << script;
1007 }
1008
1009 // Write proprietary things
1010 for (const auto& entry : m_proprietary) {
1011 s << entry.key;
1012 s << entry.value;
1013 }
1014
1015 // Write taproot internal key
1016 if (!m_tap_internal_key.IsNull()) {
1019 }
1020
1021 // Write taproot tree
1022 if (!m_tap_tree.empty()) {
1024 std::vector<unsigned char> value;
1025 VectorWriter s_value{value, 0};
1026 for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
1027 s_value << depth;
1028 s_value << leaf_ver;
1029 s_value << script;
1030 }
1031 s << value;
1032 }
1033
1034 // Write taproot bip32 keypaths
1035 for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
1036 const auto& [leaf_hashes, origin] = leaf;
1038 std::vector<unsigned char> value;
1039 VectorWriter s_value{value, 0};
1040 s_value << leaf_hashes;
1041 SerializeKeyOrigin(s_value, origin);
1042 s << value;
1043 }
1044
1045 // Write MuSig2 Participants
1046 for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
1048 std::vector<unsigned char> value;
1049 VectorWriter s_value{value, 0};
1050 for (auto& pk : part_pubs) {
1051 s_value << std::span{pk};
1052 }
1053 s << value;
1054 }
1055
1056 // Write unknown things
1057 for (auto& entry : unknown) {
1058 s << entry.first;
1059 s << entry.second;
1060 }
1061
1062 s << PSBT_SEPARATOR;
1063 }
1064
1065
1066 template <typename Stream>
1067 inline void Unserialize(Stream& s) {
1068 // Used for duplicate key detection
1069 std::set<std::vector<unsigned char>> key_lookup;
1070 // Cache whether PSBTv2 required fields are found
1071 bool found_amount = false;
1072 bool found_script = false;
1073
1074 // Read loop
1075 bool found_sep = false;
1076 while(!s.empty()) {
1077 // Read the key of format "<keylen><keytype><keydata>" after which
1078 // "key" will contain "<keytype><keydata>"
1079 std::vector<unsigned char> key;
1080 s >> key;
1081
1082 // the key is empty if that was actually a separator byte
1083 // This is a special case for key lengths 0 as those are not allowed (except for separator)
1084 if (key.empty()) {
1085 found_sep = true;
1086 break;
1087 }
1088
1089 // Duplicate keys are not permitted
1090 if (!key_lookup.emplace(key).second) {
1091 throw std::ios_base::failure(tfm::format("Duplicate Key, output key \"%s\" already provided", HexStr(key)));
1092 }
1093
1094 // "skey" is used so that "key" is unchanged after reading keytype below
1095 SpanReader skey{key};
1096 // keytype is of the format compact size uint at the beginning of "key"
1097 uint64_t type = ReadCompactSize(skey);
1098
1099 // Do stuff based on keytype "type", i.e., key checks, reading values of the
1100 // format "<valuelen><valuedata>" from the stream "s", and value checks
1101 switch(type) {
1103 {
1104 ExpectedKeySize("Output redeemScript", key, 1);
1105 s >> redeem_script;
1106 break;
1107 }
1109 {
1110 ExpectedKeySize("Output witnessScript", key, 1);
1111 s >> witness_script;
1112 break;
1113 }
1115 {
1117 break;
1118 }
1119 case PSBT_OUT_AMOUNT:
1120 {
1121 ExpectedKeySize("Output Amount", key, 1);
1122 if (m_psbt_version < 2) {
1123 throw std::ios_base::failure("Output amount is not allowed in PSBTv0");
1124 }
1126 found_amount = true;
1127 break;
1128 }
1129 case PSBT_OUT_SCRIPT:
1130 {
1131 ExpectedKeySize("Output Script", key, 1);
1132 if (m_psbt_version < 2) {
1133 throw std::ios_base::failure("Output script is not allowed in PSBTv0");
1134 }
1135 s >> script;
1136 found_script = true;
1137 break;
1138 }
1140 {
1141 ExpectedKeySize("Output Taproot Internal Key", key, 1);
1143 break;
1144 }
1145 case PSBT_OUT_TAP_TREE:
1146 {
1147 ExpectedKeySize("Output Taproot Tree Key", key, 1);
1148 std::vector<unsigned char> tree_v;
1149 s >> tree_v;
1150 SpanReader s_tree{tree_v};
1151 if (s_tree.empty()) {
1152 throw std::ios_base::failure("Output Taproot tree must not be empty");
1153 }
1154 TaprootBuilder builder;
1155 while (!s_tree.empty()) {
1156 uint8_t depth;
1157 uint8_t leaf_ver;
1158 std::vector<unsigned char> script;
1159 s_tree >> depth;
1160 s_tree >> leaf_ver;
1161 s_tree >> script;
1162 if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1163 throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
1164 }
1165 if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
1166 throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
1167 }
1168 m_tap_tree.emplace_back(depth, leaf_ver, script);
1169 builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
1170 }
1171 if (!builder.IsComplete()) {
1172 throw std::ios_base::failure("Output Taproot tree is malformed");
1173 }
1174 break;
1175 }
1177 {
1178 ExpectedKeySize("Output Taproot BIP32 Keypath", key, 33);
1179 XOnlyPubKey xonly(uint256(std::span<uint8_t>(key).last(32)));
1180 std::set<uint256> leaf_hashes;
1181 uint64_t value_len = ReadCompactSize(s);
1182 size_t before_hashes = s.size();
1183 s >> leaf_hashes;
1184 size_t after_hashes = s.size();
1185 size_t hashes_len = before_hashes - after_hashes;
1186 if (hashes_len > value_len) {
1187 throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
1188 }
1189 size_t origin_len = value_len - hashes_len;
1190 m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
1191 break;
1192 }
1194 {
1195 ExpectedKeySize("Output MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
1196 DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Output"});
1197 break;
1198 }
1200 {
1201 PSBTProprietary this_prop;
1202 skey >> this_prop.identifier;
1203 this_prop.subtype = ReadCompactSize(skey);
1204 this_prop.key = key;
1205
1206 s >> this_prop.value;
1207 m_proprietary.insert(this_prop);
1208 break;
1209 }
1210 // Unknown stuff
1211 default: {
1212 // Read in the value
1213 std::vector<unsigned char> val_bytes;
1214 s >> val_bytes;
1215 unknown.emplace(std::move(key), std::move(val_bytes));
1216 break;
1217 }
1218 }
1219 }
1220
1221 if (!found_sep) {
1222 throw std::ios_base::failure("Separator is missing at the end of an output map");
1223 }
1224
1225 // Make sure required PSBTv2 fields are present
1226 if (m_psbt_version >= 2) {
1227 if (!found_amount) {
1228 throw std::ios_base::failure("Output amount is required in PSBTv2");
1229 }
1230 if (!found_script) {
1231 throw std::ios_base::failure("Output script is required in PSBTv2");
1232 }
1233 }
1234 }
1235};
1236
1239{
1240private:
1241 std::optional<uint32_t> m_version;
1242
1243public:
1244 // We use a vector of CExtPubKey in the event that there happens to be the same KeyOriginInfos for different CExtPubKeys
1245 // Note that this map swaps the key and values from the serialization
1246 std::map<KeyOriginInfo, std::set<CExtPubKey>> m_xpubs;
1247 std::optional<std::bitset<8>> m_tx_modifiable;
1248 std::vector<PSBTInput> inputs;
1249 std::vector<PSBTOutput> outputs;
1250 std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
1251 std::set<PSBTProprietary> m_proprietary;
1252
1253 uint32_t tx_version;
1254 std::optional<uint32_t> fallback_locktime;
1255
1256 bool IsNull() const;
1257 uint32_t GetVersion() const;
1258
1261 [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
1262 bool AddInput(const PSBTInput& psbtin);
1263 bool AddOutput(const PSBTOutput& psbtout);
1264 std::optional<uint32_t> ComputeTimeLock() const;
1265 std::optional<CMutableTransaction> GetUnsignedTx() const;
1266 std::optional<Txid> GetUniqueID() const;
1267 explicit PartiallySignedTransaction(const CMutableTransaction& tx, uint32_t version = 2);
1268
1269 template <typename Stream>
1270 inline void Serialize(Stream& s) const {
1271
1272 // magic bytes
1274
1275 if (GetVersion() < 2) {
1276 // unsigned tx flag
1278
1279 // Write serialized tx to a stream
1281 }
1282
1283 // Write xpubs
1284 for (const auto& xpub_pair : m_xpubs) {
1285 for (const auto& xpub : xpub_pair.second) {
1286 unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
1287 xpub.EncodeWithVersion(ser_xpub);
1288 // Note that the serialization swaps the key and value
1289 // The xpub is the key (for uniqueness) while the path is the value
1291 SerializeHDKeypath(s, xpub_pair.first);
1292 }
1293 }
1294
1295 if (GetVersion() >= 2) {
1296 // Write PSBTv2 tx version, locktime, counts, etc.
1299 if (fallback_locktime != std::nullopt) {
1302 }
1303
1308
1309 if (m_tx_modifiable != std::nullopt) {
1311 SerializeToVector(s, static_cast<uint8_t>(m_tx_modifiable->to_ulong()));
1312 }
1313 }
1314
1315 // PSBT version
1316 if (GetVersion() > 0) {
1319 }
1320
1321 // Write proprietary things
1322 for (const auto& entry : m_proprietary) {
1323 s << entry.key;
1324 s << entry.value;
1325 }
1326
1327 // Write the unknown things
1328 for (auto& entry : unknown) {
1329 s << entry.first;
1330 s << entry.second;
1331 }
1332
1333 // Separator
1334 s << PSBT_SEPARATOR;
1335
1336 // Write inputs
1337 for (const PSBTInput& input : inputs) {
1338 s << input;
1339 }
1340 // Write outputs
1341 for (const PSBTOutput& output : outputs) {
1342 s << output;
1343 }
1344 }
1345
1346
1347 template <typename Stream>
1348 inline void Unserialize(Stream& s) {
1349 // Read the magic bytes
1350 uint8_t magic[5];
1351 s >> magic;
1352 if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
1353 throw std::ios_base::failure("Invalid PSBT magic bytes");
1354 }
1355
1356 // Used for duplicate key detection
1357 std::set<std::vector<unsigned char>> key_lookup;
1358
1359 // Track the global xpubs we have already seen. Just for sanity checking
1360 std::set<CExtPubKey> global_xpubs;
1361
1362 // Read global data
1363 bool found_sep = false;
1364 std::optional<CMutableTransaction> tx;
1365 uint64_t input_count = 0;
1366 uint64_t output_count = 0;
1367 bool found_input_count = false;
1368 bool found_output_count = false;
1369 bool found_tx_version = false;
1370 bool found_fallback_locktime = false;
1371 while(!s.empty()) {
1372 // Read the key of format "<keylen><keytype><keydata>" after which
1373 // "key" will contain "<keytype><keydata>"
1374 std::vector<unsigned char> key;
1375 s >> key;
1376
1377 // the key is empty if that was actually a separator byte
1378 // This is a special case for key lengths 0 as those are not allowed (except for separator)
1379 if (key.empty()) {
1380 found_sep = true;
1381 break;
1382 }
1383
1384 // Duplicate keys are not permitted
1385 if (!key_lookup.emplace(key).second) {
1386 throw std::ios_base::failure(tfm::format("Duplicate Key, global key \"%s\" already provided", HexStr(key)));
1387 }
1388
1389 // "skey" is used so that "key" is unchanged after reading keytype below
1390 SpanReader skey{key};
1391 // keytype is of the format compact size uint at the beginning of "key"
1392 uint64_t type = ReadCompactSize(skey);
1393
1394 // Do stuff based on keytype "type", i.e., key checks, reading values of the
1395 // format "<valuelen><valuedata>" from the stream "s", and value checks
1396 switch(type) {
1398 {
1399 ExpectedKeySize("Global Unsigned TX", key, 1);
1400 // Set the stream to serialize with non-witness since this should always be non-witness
1401 tx.emplace();
1403 // Make sure that all scriptSigs and scriptWitnesses are empty
1404 for (const CTxIn& txin : tx->vin) {
1405 if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
1406 throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
1407 }
1408 }
1409 tx_version = tx->version;
1410 fallback_locktime = tx->nLockTime;
1411 // Set the input and output counts
1412 input_count = tx->vin.size();
1413 output_count = tx->vout.size();
1414 break;
1415 }
1417 {
1418 ExpectedKeySize("Global Transaction Version", key, 1);
1420 found_tx_version = true;
1421 break;
1422 }
1424 {
1425 ExpectedKeySize("Global Fallback Locktime", key, 1);
1426 fallback_locktime.emplace();
1428 found_fallback_locktime = true;
1429 break;
1430 }
1432 {
1433 ExpectedKeySize("Global Input Count", key, 1);
1434 CompactSizeReader reader(input_count);
1435 UnserializeFromVector(s, reader);
1436 found_input_count = true;
1437 break;
1438 }
1440 {
1441 ExpectedKeySize("Global Output Count", key, 1);
1442 CompactSizeReader reader(output_count);
1443 UnserializeFromVector(s, reader);
1444 found_output_count = true;
1445 break;
1446 }
1448 {
1449 ExpectedKeySize("Global TX Modifiable Flags", key, 1);
1450 uint8_t tx_mod;
1451 UnserializeFromVector(s, tx_mod);
1452 m_tx_modifiable.emplace(tx_mod);
1453 break;
1454 }
1455 case PSBT_GLOBAL_XPUB:
1456 {
1457 ExpectedKeySize("Global XPUB", key, BIP32_EXTKEY_WITH_VERSION_SIZE + 1);
1458 // Read in the xpub from key
1459 CExtPubKey xpub;
1460 xpub.DecodeWithVersion(&key.data()[1]);
1461 if (!xpub.pubkey.IsFullyValid()) {
1462 throw std::ios_base::failure("Invalid pubkey");
1463 }
1464 global_xpubs.insert(xpub);
1465 // Read in the keypath from stream
1466 KeyOriginInfo keypath;
1467 DeserializeHDKeypath(s, keypath);
1468
1469 // Note that we store these swapped to make searches faster.
1470 // Serialization uses xpub -> keypath to enqure key uniqueness
1471 if (!m_xpubs.contains(keypath)) {
1472 // Make a new set to put the xpub in
1473 m_xpubs[keypath] = {xpub};
1474 } else {
1475 // Insert xpub into existing set
1476 m_xpubs[keypath].insert(xpub);
1477 }
1478 break;
1479 }
1481 {
1482 ExpectedKeySize("Global PSBT Version", key, 1);
1483 uint32_t v;
1485 m_version = v;
1487 throw std::ios_base::failure("Unsupported version number");
1488 }
1489 break;
1490 }
1492 {
1493 PSBTProprietary this_prop;
1494 skey >> this_prop.identifier;
1495 this_prop.subtype = ReadCompactSize(skey);
1496 this_prop.key = key;
1497
1498 s >> this_prop.value;
1499 m_proprietary.insert(this_prop);
1500 break;
1501 }
1502 // Unknown stuff
1503 default: {
1504 // Read in the value
1505 std::vector<unsigned char> val_bytes;
1506 s >> val_bytes;
1507 unknown.emplace(std::move(key), std::move(val_bytes));
1508 }
1509 }
1510 }
1511
1512 if (!found_sep) {
1513 throw std::ios_base::failure("Separator is missing at the end of the global map");
1514 }
1515
1516 const uint32_t psbt_ver = GetVersion();
1517
1518 // Check PSBT version constraints
1519 if (psbt_ver == 0) {
1520 // Make sure that we got an unsigned tx for PSBTv0
1521 if (!tx) {
1522 throw std::ios_base::failure("No unsigned transaction was provided");
1523 }
1524 // Make sure no PSBTv2 fields are present
1525 if (found_tx_version) {
1526 throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is not allowed in PSBTv0");
1527 }
1528 if (found_fallback_locktime) {
1529 throw std::ios_base::failure("PSBT_GLOBAL_FALLBACK_LOCKTIME is not allowed in PSBTv0");
1530 }
1531 if (found_input_count) {
1532 throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is not allowed in PSBTv0");
1533 }
1534 if (found_output_count) {
1535 throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is not allowed in PSBTv0");
1536 }
1537 if (m_tx_modifiable != std::nullopt) {
1538 throw std::ios_base::failure("PSBT_GLOBAL_TX_MODIFIABLE is not allowed in PSBTv0");
1539 }
1540 }
1541 // Disallow v1
1542 if (psbt_ver == 1) {
1543 throw std::ios_base::failure("There is no PSBT version 1");
1544 }
1545 if (psbt_ver == 2) {
1546 // Tx version, input, and output counts are required
1547 if (!found_tx_version) {
1548 throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is required in PSBTv2");
1549 }
1550 if (!found_input_count) {
1551 throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is required in PSBTv2");
1552 }
1553 if (!found_output_count) {
1554 throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is required in PSBTv2");
1555 }
1556 // Unsigned tx is disallowed
1557 if (tx) {
1558 throw std::ios_base::failure("PSBT_GLOBAL_UNSIGNED_TX is not allowed in PSBTv2");
1559 }
1560 }
1561 if (psbt_ver > 2) {
1562 throw std::ios_base::failure("Unknown PSBT version");
1563 }
1564
1565 // Read input data
1566 unsigned int i = 0;
1567 while (!s.empty() && i < input_count) {
1568 if (psbt_ver < 2) {
1569 inputs.emplace_back(psbt_ver, tx->vin[i].prevout.hash, tx->vin[i].prevout.n, tx->vin[i].nSequence);
1570 s >> inputs.back();
1571 } else {
1572 inputs.emplace_back(deserialize, s, psbt_ver);
1573 }
1574
1575 // Make sure the non-witness utxo matches the outpoint
1576 const PSBTInput& input = inputs.back();
1577 if (input.non_witness_utxo) {
1578 if (psbt_ver < 2) {
1579 if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
1580 throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1581 }
1582 if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
1583 throw std::ios_base::failure("Input specifies output index that does not exist");
1584 }
1585 } else {
1586 if (input.non_witness_utxo->GetHash() != input.prev_txid) {
1587 throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1588 }
1589 if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1590 throw std::ios_base::failure("Input specifies output index that does not exist");
1591 }
1592 }
1593 }
1594 ++i;
1595 }
1596 // Make sure that the number of inputs matches the number of inputs in the transaction
1597 if (inputs.size() != input_count) {
1598 throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
1599 }
1600
1601 // Read output data
1602 i = 0;
1603 while (!s.empty() && i < output_count) {
1604 if (psbt_ver < 2) {
1605 outputs.emplace_back(psbt_ver, tx->vout[i].nValue, tx->vout[i].scriptPubKey);
1606 s >> outputs.back();
1607 } else {
1608 outputs.emplace_back(deserialize, s, psbt_ver);
1609 }
1610 ++i;
1611 }
1612 // Make sure that the number of outputs matches the number of outputs in the transaction
1613 if (outputs.size() != output_count) {
1614 throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
1615 }
1616 }
1617
1618 template <typename Stream>
1620 Unserialize(s);
1621 }
1622};
1623
1624enum class PSBTRole {
1625 CREATOR,
1626 UPDATER,
1627 SIGNER,
1628 FINALIZER,
1629 EXTRACTOR
1630};
1631
1632std::string PSBTRoleName(PSBTRole role);
1633
1635std::optional<PrecomputedTransactionData> PrecomputePSBTData(const PartiallySignedTransaction& psbt);
1636
1638bool PSBTInputSigned(const PSBTInput& input);
1639
1641bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
1642
1648[[nodiscard]] PSBTError SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options, SignatureData* out_sigdata = nullptr);
1649
1652
1655
1660void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index);
1661
1669
1678
1685[[nodiscard]] std::optional<PartiallySignedTransaction> CombinePSBTs(const std::vector<PartiallySignedTransaction>& psbtxs);
1686
1688[[nodiscard]] util::Result<PartiallySignedTransaction> DecodeBase64PSBT(const std::string& base64_tx);
1690[[nodiscard]] util::Result<PartiallySignedTransaction> DecodeRawPSBT(std::span<const std::byte> tx_data);
1691
1692#endif // BITCOIN_PSBT_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ArgsManager & args
Definition: bitcoind.cpp:278
static const size_t OUTPUT_SIZE
Definition: hash.h:53
static const size_t OUTPUT_SIZE
Definition: hash.h:28
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
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
A structure for PSBTs which contain per-input information.
Definition: psbt.h:280
std::vector< unsigned char > m_tap_key_sig
Definition: psbt.h:305
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:291
uint32_t m_psbt_version
Definition: psbt.h:282
std::map< uint256, std::vector< unsigned char > > hash256_preimages
Definition: psbt.h:296
bool Merge(const PSBTInput &input)
Definition: psbt.cpp:426
CScriptWitness final_script_witness
Definition: psbt.h:290
std::optional< uint32_t > sequence
Definition: psbt.h:300
std::map< std::pair< CPubKey, uint256 >, std::map< CPubKey, std::vector< uint8_t > > > m_musig2_pubnonces
Definition: psbt.h:315
bool HasSignatures() const
Definition: psbt.cpp:465
bool GetUTXO(CTxOut &utxo) const
Retrieves the UTXO for this input.
Definition: psbt.cpp:268
std::map< std::pair< std::vector< unsigned char >, int >, std::set< std::vector< unsigned char >, ShortestVectorFirstComparator > > m_tap_scripts
Definition: psbt.h:307
CTransactionRef non_witness_utxo
Definition: psbt.h:285
Txid prev_txid
Definition: psbt.h:298
std::map< CKeyID, SigPair > partial_sigs
Definition: psbt.h:292
std::optional< int > sighash_type
Definition: psbt.h:321
std::map< std::pair< XOnlyPubKey, uint256 >, std::vector< unsigned char > > m_tap_script_sigs
Definition: psbt.h:306
void Serialize(Stream &s) const
Definition: psbt.h:359
std::optional< uint32_t > time_locktime
Definition: psbt.h:301
uint256 m_tap_merkle_root
Definition: psbt.h:310
std::map< uint256, std::vector< unsigned char > > sha256_preimages
Definition: psbt.h:294
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:296
std::map< std::pair< CPubKey, uint256 >, std::map< CPubKey, uint256 > > m_musig2_partial_sigs
Definition: psbt.h:317
COutPoint GetOutPoint() const
Definition: psbt.cpp:286
std::map< uint160, std::vector< unsigned char > > hash160_preimages
Definition: psbt.h:295
bool operator==(const PSBTInput &) const =default
bool IsNull() const
Definition: psbt.cpp:291
uint32_t prev_out
Definition: psbt.h:299
PSBTInput(uint32_t psbt_version, const Txid &prev_txid, uint32_t prev_out, std::optional< uint32_t > sequence=std::nullopt)
Definition: psbt.h:338
void Unserialize(Stream &s)
Definition: psbt.h:558
std::map< CPubKey, std::vector< CPubKey > > m_musig2_participants
Definition: psbt.h:313
std::set< PSBTProprietary > m_proprietary
Definition: psbt.h:320
CScript redeem_script
Definition: psbt.h:287
CScript final_script_sig
Definition: psbt.h:289
PSBTInput(deserialize_type, Stream &s, uint32_t psbt_version)
Definition: psbt.h:349
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:360
uint32_t GetVersion() const
Definition: psbt.h:327
XOnlyPubKey m_tap_internal_key
Definition: psbt.h:309
std::optional< uint32_t > height_locktime
Definition: psbt.h:302
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > m_tap_bip32_paths
Definition: psbt.h:308
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:319
std::map< uint160, std::vector< unsigned char > > ripemd160_preimages
Definition: psbt.h:293
CTxOut witness_utxo
Definition: psbt.h:286
CScript witness_script
Definition: psbt.h:288
A structure for PSBTs which contains per output information.
Definition: psbt.h:938
std::map< CPubKey, std::vector< CPubKey > > m_musig2_participants
Definition: psbt.h:950
XOnlyPubKey m_tap_internal_key
Definition: psbt.h:947
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > m_tap_bip32_paths
Definition: psbt.h:949
bool operator==(const PSBTOutput &) const =default
CScript witness_script
Definition: psbt.h:944
bool IsNull() const
Definition: psbt.cpp:529
std::set< PSBTProprietary > m_proprietary
Definition: psbt.h:953
PSBTOutput(deserialize_type, Stream &s, uint32_t psbt_version)
Definition: psbt.h:974
CAmount amount
Definition: psbt.h:955
CScript redeem_script
Definition: psbt.h:943
void Serialize(Stream &s) const
Definition: psbt.h:984
CScript script
Definition: psbt.h:956
uint32_t GetVersion() const
Definition: psbt.h:962
uint32_t m_psbt_version
Definition: psbt.h:940
bool Merge(const PSBTOutput &output)
Definition: psbt.cpp:534
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:945
std::vector< std::tuple< uint8_t, uint8_t, std::vector< unsigned char > > > m_tap_tree
Definition: psbt.h:948
void Unserialize(Stream &s)
Definition: psbt.h:1067
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:952
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:475
PSBTOutput(uint32_t psbt_version, CAmount amount, const CScript &script)
Definition: psbt.h:964
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:506
A version of CTransaction with the PSBT format.
Definition: psbt.h:1239
std::optional< std::bitset< 8 > > m_tx_modifiable
Definition: psbt.h:1247
uint32_t GetVersion() const
Definition: psbt.cpp:884
bool Merge(const PartiallySignedTransaction &psbt)
Merge psbt into this.
Definition: psbt.cpp:39
std::map< KeyOriginInfo, std::set< CExtPubKey > > m_xpubs
Definition: psbt.h:1246
std::optional< uint32_t > m_version
Definition: psbt.h:1241
bool IsNull() const
Definition: psbt.cpp:34
std::optional< Txid > GetUniqueID() const
Definition: psbt.cpp:147
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:1250
std::vector< PSBTInput > inputs
Definition: psbt.h:1248
std::optional< CMutableTransaction > GetUnsignedTx() const
Definition: psbt.cpp:121
std::optional< uint32_t > ComputeTimeLock() const
Definition: psbt.cpp:87
std::vector< PSBTOutput > outputs
Definition: psbt.h:1249
std::set< PSBTProprietary > m_proprietary
Definition: psbt.h:1251
void Serialize(Stream &s) const
Definition: psbt.h:1270
bool AddOutput(const PSBTOutput &psbtout)
Definition: psbt.cpp:245
PartiallySignedTransaction(deserialize_type, Stream &s)
Definition: psbt.h:1619
std::optional< uint32_t > fallback_locktime
Definition: psbt.h:1254
void Unserialize(Stream &s)
Definition: psbt.h:1348
PartiallySignedTransaction(const CMutableTransaction &tx, uint32_t version=2)
Definition: psbt.cpp:18
bool AddInput(const PSBTInput &psbtin)
Definition: psbt.cpp:162
An interface to be implemented by keystores that support signing.
uint64_t size() const
Definition: serialize.h:1092
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:49
constexpr void SetNull()
Definition: uint256.h:56
bool empty() const
Definition: prevector.h:251
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
is a home for simple enum and struct type definitions that can be used internally by functions in the...
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
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:19
Definition: messages.h:21
TransactionError
Definition: types.h:28
void format(std::ostream &out, FormatStringCheck< sizeof...(Args)> fmt, const Args &... args)
Format list of arguments to the stream according to given format string.
Definition: tinyformat.h:1079
#define X(name)
Definition: net.cpp:616
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
static constexpr uint8_t PSBT_OUT_AMOUNT
Definition: psbt.h:78
PSBTError SignPSBTInput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index, const PrecomputedTransactionData *txdata, const common::PSBTFillOptions &options, SignatureData *out_sigdata=nullptr)
Signs a PSBTInput, verifying that all provided data matches what is being signed.
Definition: psbt.cpp:644
void SerializeToVector(Stream &s, const X &... args)
Definition: psbt.h:116
static constexpr uint8_t PSBT_IN_REQUIRED_HEIGHT_LOCKTIME
Definition: psbt.h:62
static constexpr uint8_t PSBT_IN_RIPEMD160
Definition: psbt.h:54
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:599
static constexpr uint8_t PSBT_IN_HASH256
Definition: psbt.h:57
static constexpr uint8_t PSBT_IN_REQUIRED_TIME_LOCKTIME
Definition: psbt.h:61
static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX
Definition: psbt.h:34
static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO
Definition: psbt.h:45
static constexpr uint8_t PSBT_IN_TAP_KEY_SIG
Definition: psbt.h:63
void UnserializeFromVector(Stream &s, X &&... args)
Definition: psbt.h:126
static constexpr uint8_t PSBT_IN_SCRIPTSIG
Definition: psbt.h:52
static constexpr uint8_t PSBT_IN_WITNESSSCRIPT
Definition: psbt.h:50
static constexpr uint8_t PSBT_IN_OUTPUT_INDEX
Definition: psbt.h:59
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:554
std::string PSBTRoleName(PSBTRole role)
Definition: psbt.cpp:850
util::Result< PartiallySignedTransaction > DecodeBase64PSBT(const std::string &base64_tx)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:861
static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT
Definition: psbt.h:75
static constexpr uint8_t PSBT_GLOBAL_VERSION
Definition: psbt.h:41
static constexpr uint8_t PSBT_GLOBAL_TX_VERSION
Definition: psbt.h:36
static constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT
Definition: psbt.h:65
static constexpr uint8_t PSBT_OUT_PROPRIETARY
Definition: psbt.h:84
static constexpr uint8_t PSBT_MAGIC_BYTES[5]
Definition: psbt.h:31
std::optional< PartiallySignedTransaction > CombinePSBTs(const std::vector< PartiallySignedTransaction > &psbtxs)
Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial sign...
Definition: psbt.cpp:837
static constexpr uint32_t PSBT_HIGHEST_VERSION
Definition: psbt.h:95
static constexpr uint8_t PSBT_SEPARATOR
Definition: psbt.h:88
static constexpr uint8_t PSBT_IN_BIP32_DERIVATION
Definition: psbt.h:51
void DeserializeMuSig2ParticipantPubkeys(Stream &s, SpanReader &skey, std::map< CPubKey, std::vector< CPubKey > > &out, std::string context)
Definition: psbt.h:217
static constexpr uint8_t PSBT_IN_SCRIPTWITNESS
Definition: psbt.h:53
static constexpr uint8_t PSBT_OUT_TAP_TREE
Definition: psbt.h:81
static constexpr uint8_t PSBT_IN_PREVIOUS_TXID
Definition: psbt.h:58
static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION
Definition: psbt.h:77
PSBTRole
Definition: psbt.h:1624
static constexpr uint8_t PSBT_GLOBAL_PROPRIETARY
Definition: psbt.h:42
void RemoveUnnecessaryTransactions(PartiallySignedTransaction &psbtx)
Reduces the size of the PSBT by dropping unnecessary non_witness_utxos (i.e.
Definition: psbt.cpp:760
std::optional< PrecomputedTransactionData > PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:623
static constexpr uint8_t PSBT_IN_PROPRIETARY
Definition: psbt.h:72
static constexpr uint8_t PSBT_GLOBAL_TX_MODIFIABLE
Definition: psbt.h:40
static constexpr uint8_t PSBT_IN_SEQUENCE
Definition: psbt.h:60
KeyOriginInfo DeserializeKeyOrigin(Stream &s, uint64_t length)
Definition: psbt.h:139
void DeserializeMuSig2ParticipantDataIdentifier(Stream &skey, CPubKey &agg_pub, CPubKey &part_pub, uint256 &leaf_hash)
Definition: psbt.h:249
static constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG
Definition: psbt.h:64
static constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE
Definition: psbt.h:70
void SerializeHDKeypaths(Stream &s, const std::map< CPubKey, KeyOriginInfo > &hd_keypaths, CompactSizeWriter type)
Definition: psbt.h:204
static void ExpectedKeySize(const std::string &key_name, const std::vector< unsigned char > &key, uint64_t expected_size)
Definition: psbt.h:272
static constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION
Definition: psbt.h:66
static constexpr uint8_t PSBT_IN_HASH160
Definition: psbt.h:56
static constexpr uint8_t PSBT_IN_REDEEMSCRIPT
Definition: psbt.h:49
static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT
Definition: psbt.h:76
static constexpr uint8_t PSBT_GLOBAL_XPUB
Definition: psbt.h:35
static constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS
Definition: psbt.h:83
static constexpr uint8_t PSBT_GLOBAL_OUTPUT_COUNT
Definition: psbt.h:39
static constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION
Definition: psbt.h:82
static constexpr uint8_t PSBT_IN_PARTIAL_SIG
Definition: psbt.h:47
static constexpr uint8_t PSBT_GLOBAL_FALLBACK_LOCKTIME
Definition: psbt.h:37
static constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY
Definition: psbt.h:67
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction &psbt)
Counts the unsigned inputs of a PSBT.
Definition: psbt.cpp:588
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:817
static constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY
Definition: psbt.h:80
static constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT
Definition: psbt.h:68
void SerializeKeyOrigin(Stream &s, KeyOriginInfo hd_keypath)
Definition: psbt.h:186
void DeserializeHDKeypaths(Stream &s, const std::vector< unsigned char > &key, std::map< CPubKey, KeyOriginInfo > &hd_keypaths)
Definition: psbt.h:165
static constexpr uint8_t PSBT_IN_SIGHASH
Definition: psbt.h:48
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
Definition: psbt.cpp:549
static constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS
Definition: psbt.h:69
void SerializeHDKeypath(Stream &s, KeyOriginInfo hd_keypath)
Definition: psbt.h:196
void DeserializeHDKeypath(Stream &s, KeyOriginInfo &hd_keypath)
Definition: psbt.h:158
bool FinalizePSBT(PartiallySignedTransaction &psbtx)
Finalizes a PSBT if possible, combining partial signatures.
Definition: psbt.cpp:797
static constexpr uint8_t PSBT_OUT_SCRIPT
Definition: psbt.h:79
util::Result< PartiallySignedTransaction > DecodeRawPSBT(std::span< const std::byte > tx_data)
Decode a raw (binary blob) PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:870
static constexpr uint8_t PSBT_GLOBAL_INPUT_COUNT
Definition: psbt.h:38
const std::streamsize MAX_FILE_SIZE_PSBT
Definition: psbt.h:92
static constexpr uint8_t PSBT_IN_WITNESS_UTXO
Definition: psbt.h:46
static constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG
Definition: psbt.h:71
static constexpr uint8_t PSBT_IN_SHA256
Definition: psbt.h:55
const unsigned int BIP32_EXTKEY_WITH_VERSION_SIZE
Definition: pubkey.h:20
static const unsigned int LOCKTIME_THRESHOLD
Definition: script.h:47
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:1000
constexpr deserialize_type deserialize
Definition: serialize.h:51
void UnserializeMany(Stream &s, Args &&... args)
Definition: serialize.h:1006
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1104
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:332
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:76
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 PSBT proprietary types.
Definition: psbt.h:99
std::vector< unsigned char > value
Definition: psbt.h:103
bool operator<(const PSBTProprietary &b) const
Definition: psbt.h:105
uint64_t subtype
Definition: psbt.h:100
std::vector< unsigned char > identifier
Definition: psbt.h:101
std::vector< unsigned char > key
Definition: psbt.h:102
bool operator==(const PSBTProprietary &b) const
Definition: psbt.h:108
Instructions for how a PSBT should be signed or filled with information.
Definition: types.h:32
Dummy data type to identify deserializing constructors.
Definition: serialize.h:50
assert(!tx.IsCoinBase())