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 <musig.h>
10#include <node/transaction.h>
11#include <policy/feerate.h>
13#include <pubkey.h>
14#include <script/keyorigin.h>
15#include <script/sign.h>
17#include <span.h>
18#include <streams.h>
19#include <uint256.h>
20#include <util/result.h>
21#include <util/expected.h>
22
23#include <optional>
24#include <bitset>
25
26namespace node {
27enum class TransactionError;
28} // namespace node
29
31
32// Magic bytes
33inline constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff};
34
35// Global types
36inline constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00;
37inline constexpr uint8_t PSBT_GLOBAL_XPUB = 0x01;
38inline constexpr uint8_t PSBT_GLOBAL_TX_VERSION = 0x02;
39inline constexpr uint8_t PSBT_GLOBAL_FALLBACK_LOCKTIME = 0x03;
40inline constexpr uint8_t PSBT_GLOBAL_INPUT_COUNT = 0x04;
41inline constexpr uint8_t PSBT_GLOBAL_OUTPUT_COUNT = 0x05;
42inline constexpr uint8_t PSBT_GLOBAL_TX_MODIFIABLE = 0x06;
43inline constexpr uint8_t PSBT_GLOBAL_VERSION = 0xFB;
44inline constexpr uint8_t PSBT_GLOBAL_PROPRIETARY = 0xFC;
45
46// Input types
47inline constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00;
48inline constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01;
49inline constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02;
50inline constexpr uint8_t PSBT_IN_SIGHASH = 0x03;
51inline constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04;
52inline constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05;
53inline constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06;
54inline constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07;
55inline constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08;
56inline constexpr uint8_t PSBT_IN_RIPEMD160 = 0x0A;
57inline constexpr uint8_t PSBT_IN_SHA256 = 0x0B;
58inline constexpr uint8_t PSBT_IN_HASH160 = 0x0C;
59inline constexpr uint8_t PSBT_IN_HASH256 = 0x0D;
60inline constexpr uint8_t PSBT_IN_PREVIOUS_TXID = 0x0e;
61inline constexpr uint8_t PSBT_IN_OUTPUT_INDEX = 0x0f;
62inline constexpr uint8_t PSBT_IN_SEQUENCE = 0x10;
63inline constexpr uint8_t PSBT_IN_REQUIRED_TIME_LOCKTIME = 0x11;
64inline constexpr uint8_t PSBT_IN_REQUIRED_HEIGHT_LOCKTIME = 0x12;
65inline constexpr uint8_t PSBT_IN_TAP_KEY_SIG = 0x13;
66inline constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG = 0x14;
67inline constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT = 0x15;
68inline constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
69inline constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY = 0x17;
70inline constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT = 0x18;
71inline constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS = 0x1a;
72inline constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE = 0x1b;
73inline constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG = 0x1c;
74inline constexpr uint8_t PSBT_IN_PROPRIETARY = 0xFC;
75
76// Output types
77inline constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00;
78inline constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01;
79inline constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02;
80inline constexpr uint8_t PSBT_OUT_AMOUNT = 0x03;
81inline constexpr uint8_t PSBT_OUT_SCRIPT = 0x04;
82inline constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
83inline constexpr uint8_t PSBT_OUT_TAP_TREE = 0x06;
84inline constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
85inline constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS = 0x08;
86inline constexpr uint8_t PSBT_OUT_PROPRIETARY = 0xFC;
87
88// The separator is 0x00. Reading this in means that the unserializer can interpret it
89// as a 0 length key which indicates that this is the separator. The separator has no value.
90inline constexpr uint8_t PSBT_SEPARATOR = 0x00;
91
92// BIP 174 does not specify a maximum file size, but we set a limit anyway
93// to prevent reading a stream indefinitely and running out of memory.
94inline constexpr std::streamsize MAX_FILE_SIZE_PSBT{100'000'000}; // 100 MB
95
96// PSBT version number
97inline constexpr uint32_t PSBT_HIGHEST_VERSION = 2;
98
101{
102 uint64_t subtype;
103 std::vector<unsigned char> identifier;
104 std::vector<unsigned char> key;
105 std::vector<unsigned char> value;
106
107 bool operator<(const PSBTProprietary &b) const {
108 return key < b.key;
109 }
110 bool operator==(const PSBTProprietary &b) const {
111 return key == b.key;
112 }
113};
114
115// Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
116// The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
117template<typename Stream, typename... X>
118void SerializeToVector(Stream& s, const X&... args)
119{
120 SizeComputer sizecomp;
121 SerializeMany(sizecomp, args...);
122 WriteCompactSize(s, sizecomp.size());
123 SerializeMany(s, args...);
124}
125
126// Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
127template<typename Stream, typename... X>
129{
130 size_t expected_size = ReadCompactSize(s);
131 size_t remaining_before = s.size();
133 size_t remaining_after = s.size();
134 if (remaining_after + expected_size != remaining_before) {
135 throw std::ios_base::failure("Size of value was not the stated size");
136 }
137}
138
139// Deserialize bytes of given length from the stream as a KeyOriginInfo
140template<typename Stream>
142{
143 // Read in key path
144 if (length % 4 || length == 0) {
145 throw std::ios_base::failure("Invalid length for HD key path");
146 }
147
148 KeyOriginInfo hd_keypath;
149 s >> hd_keypath.fingerprint;
150 for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
151 uint32_t index;
152 s >> index;
153 hd_keypath.path.push_back(index);
154 }
155 return hd_keypath;
156}
157
158// Deserialize a length prefixed KeyOriginInfo from a stream
159template<typename Stream>
161{
162 hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
163}
164
165// Deserialize HD keypaths into a map
166template<typename Stream>
167void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
168{
169 // Make sure that the key is the size of pubkey + 1
170 if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
171 throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
172 }
173 // Read in the pubkey from key
174 CPubKey pubkey(key.begin() + 1, key.end());
175 if (!pubkey.IsFullyValid()) {
176 throw std::ios_base::failure("Invalid pubkey");
177 }
178
179 KeyOriginInfo keypath;
180 DeserializeHDKeypath(s, keypath);
181
182 // Add to map
183 hd_keypaths.emplace(pubkey, std::move(keypath));
184}
185
186// Serialize a KeyOriginInfo to a stream
187template<typename Stream>
189{
190 s << hd_keypath.fingerprint;
191 for (const auto& path : hd_keypath.path) {
192 s << path;
193 }
194}
195
196// Serialize a length prefixed KeyOriginInfo to a stream
197template<typename Stream>
199{
200 WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
201 SerializeKeyOrigin(s, hd_keypath);
202}
203
204// Serialize HD keypaths to a stream from a map
205template<typename Stream>
206void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
207{
208 for (const auto& keypath_pair : hd_keypaths) {
209 if (!keypath_pair.first.IsValid()) {
210 throw std::ios_base::failure("Invalid CPubKey being serialized");
211 }
212 SerializeToVector(s, type, std::span{keypath_pair.first});
213 SerializeHDKeypath(s, keypath_pair.second);
214 }
215}
216
217// Deserialize a PSBT_{IN/OUT}_MUSIG2_PARTICIPANT_PUBKEYS field
218template<typename Stream>
219void DeserializeMuSig2ParticipantPubkeys(Stream& s, SpanReader& skey, std::map<CPubKey, std::vector<CPubKey>>& out, std::string context)
220{
221 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
222 skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
223 CPubKey agg_pubkey(agg_pubkey_bytes);
224 if (!agg_pubkey.IsFullyValid()) {
225 throw std::ios_base::failure(context + " musig2 aggregate pubkey is invalid");
226 }
227
228 std::vector<CPubKey> participants;
229 std::vector<unsigned char> val;
230 s >> val;
231 SpanReader s_val{val};
232 while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
233 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
234 s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
235 CPubKey participant(part_pubkey_bytes);
236 if (!participant.IsFullyValid()) {
237 throw std::ios_base::failure(context + " musig2 participant pubkey is invalid");
238 }
239 participants.push_back(participant);
240 }
241 if (!s_val.empty()) {
242 throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
243 }
244
245 out.emplace(agg_pubkey, participants);
246}
247
248// Deserialize the MuSig2 participant identifiers from PSBT_MUSIG2_{PUBNONCE/PARTIAL_SIG} fields
249// Both fields contain the same data after the type byte - aggregate pubkey | participant pubkey | leaf script hash
250template<typename Stream>
251void DeserializeMuSig2ParticipantDataIdentifier(Stream& skey, CPubKey& agg_pub, CPubKey& part_pub, uint256& leaf_hash)
252{
253 leaf_hash.SetNull();
254
255 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
256 std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
257
258 skey >> std::as_writable_bytes(std::span{part_pubkey_bytes}) >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
259 agg_pub.Set(agg_pubkey_bytes.begin(), agg_pubkey_bytes.end());
260 if (!agg_pub.IsFullyValid()) {
261 throw std::ios_base::failure("musig2 aggregate pubkey is invalid");
262 }
263
264 part_pub.Set(part_pubkey_bytes.begin(), part_pubkey_bytes.end());
265 if (!part_pub.IsFullyValid()) {
266 throw std::ios_base::failure("musig2 participant pubkey is invalid");
267 }
268
269 if (!skey.empty()) {
270 skey >> leaf_hash;
271 }
272}
273
274static inline void ExpectedKeySize(const std::string& key_name, const std::vector<unsigned char>& key, uint64_t expected_size) {
275 if (key.size() != expected_size) {
276 throw std::ios_base::failure(tfm::format("Size of key was not %d for the type %s", expected_size, key_name));
277 }
278}
279
282{
283private:
285
286public:
293 std::map<CPubKey, KeyOriginInfo> hd_keypaths;
294 std::map<CKeyID, SigPair> partial_sigs;
295 std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
296 std::map<uint256, std::vector<unsigned char>> sha256_preimages;
297 std::map<uint160, std::vector<unsigned char>> hash160_preimages;
298 std::map<uint256, std::vector<unsigned char>> hash256_preimages;
299
301 uint32_t prev_out;
302 std::optional<uint32_t> sequence;
303 std::optional<uint32_t> time_locktime;
304 std::optional<uint32_t> height_locktime;
305
306 // Taproot fields
307 std::vector<unsigned char> m_tap_key_sig;
308 std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
309 std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
310 std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
313
314 // MuSig2 fields
315 std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
316 // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to pubnonce
317 std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, std::vector<uint8_t>>> m_musig2_pubnonces;
318 // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to partial_sig
319 std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, uint256>> m_musig2_partial_sigs;
320
321 std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
322 std::set<PSBTProprietary> m_proprietary;
323 std::optional<int> sighash_type;
324
325 void FillSignatureData(SignatureData& sigdata) const;
326 void FromSignatureData(const SignatureData& sigdata);
327 [[nodiscard]] bool Merge(const PSBTInput& input);
328 uint32_t GetVersion() const { return m_psbt_version; }
329 COutPoint GetOutPoint() const;
336 bool GetUTXO(CTxOut& utxo) const;
337 bool HasSignatures() const;
338
339 explicit PSBTInput(uint32_t psbt_version, const Txid& prev_txid, uint32_t prev_out, std::optional<uint32_t> sequence = std::nullopt)
340 : m_psbt_version(psbt_version),
344 {
346 }
347
348 // Construct a PSBTInput when the previous txid and output index are expected to be serialized
349 template <typename Stream>
350 explicit PSBTInput(deserialize_type, Stream& s, uint32_t psbt_version)
351 : m_psbt_version(psbt_version)
352 {
354 Unserialize(s);
355 }
356
357 bool operator==(const PSBTInput&) const = default;
358
359 template <typename Stream>
360 inline void Serialize(Stream& s) const {
361 // Write the utxo
362 if (non_witness_utxo) {
365 }
366 if (!witness_utxo.IsNull()) {
369 }
370
372 // Write any partial signatures
373 for (const auto& sig_pair : partial_sigs) {
374 SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
375 s << sig_pair.second.second;
376 }
377
378 // Write the sighash type
379 if (sighash_type != std::nullopt) {
382 }
383
384 // Write the redeem script
385 if (!redeem_script.empty()) {
387 s << redeem_script;
388 }
389
390 // Write the witness script
391 if (!witness_script.empty()) {
393 s << witness_script;
394 }
395
396 // Write any hd keypaths
398
399 // Write any ripemd160 preimage
400 for (const auto& [hash, preimage] : ripemd160_preimages) {
402 s << preimage;
403 }
404
405 // Write any sha256 preimage
406 for (const auto& [hash, preimage] : sha256_preimages) {
408 s << preimage;
409 }
410
411 // Write any hash160 preimage
412 for (const auto& [hash, preimage] : hash160_preimages) {
414 s << preimage;
415 }
416
417 // Write any hash256 preimage
418 for (const auto& [hash, preimage] : hash256_preimages) {
420 s << preimage;
421 }
422
423 // Write taproot key sig
424 if (!m_tap_key_sig.empty()) {
426 s << m_tap_key_sig;
427 }
428
429 // Write taproot script sigs
430 for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
431 const auto& [xonly, leaf_hash] = pubkey_leaf;
432 SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
433 s << sig;
434 }
435
436 // Write taproot leaf scripts
437 for (const auto& [leaf, control_blocks] : m_tap_scripts) {
438 const auto& [script, leaf_ver] = leaf;
439 for (const auto& control_block : control_blocks) {
440 SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, std::span{control_block});
441 std::vector<unsigned char> value_v(script.begin(), script.end());
442 value_v.push_back((uint8_t)leaf_ver);
443 s << value_v;
444 }
445 }
446
447 // Write taproot bip32 keypaths
448 for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
449 const auto& [leaf_hashes, origin] = leaf_origin;
451 std::vector<unsigned char> value;
452 VectorWriter s_value{value, 0};
453 s_value << leaf_hashes;
454 SerializeKeyOrigin(s_value, origin);
455 s << value;
456 }
457
458 // Write taproot internal key
459 if (!m_tap_internal_key.IsNull()) {
462 }
463
464 // Write taproot merkle root
465 if (!m_tap_merkle_root.IsNull()) {
468 }
469
470 // Write MuSig2 Participants
471 for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
473 std::vector<unsigned char> value;
474 VectorWriter s_value{value, 0};
475 for (auto& pk : part_pubs) {
476 s_value << std::span{pk};
477 }
478 s << value;
479 }
480
481 // Write MuSig2 pubnonces
482 for (const auto& [agg_pubkey_leaf_hash, pubnonces] : m_musig2_pubnonces) {
483 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
484 for (const auto& [part_pubkey, pubnonce] : pubnonces) {
485 if (leaf_hash.IsNull()) {
486 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey});
487 } else {
488 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey}, leaf_hash);
489 }
490 s << pubnonce;
491 }
492 }
493
494 // Write MuSig2 partial signatures
495 for (const auto& [agg_pubkey_leaf_hash, psigs] : m_musig2_partial_sigs) {
496 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
497 for (const auto& [pubkey, psig] : psigs) {
498 if (leaf_hash.IsNull()) {
499 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey});
500 } else {
501 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey}, leaf_hash);
502 }
503 SerializeToVector(s, psig);
504 }
505 }
506 }
507
508 // Write script sig
509 if (!final_script_sig.empty()) {
512 }
513 // write script witness
517 }
518
519 // Write PSBTv2 fields
520 if (m_psbt_version >= 2) {
521 // Write prev txid, vout, sequence, and lock times
524
527
528 if (sequence != std::nullopt) {
531 }
532 if (time_locktime != std::nullopt) {
535 }
536 if (height_locktime != std::nullopt) {
539 }
540 }
541
542 // Write proprietary things
543 for (const auto& entry : m_proprietary) {
544 s << entry.key;
545 s << entry.value;
546 }
547
548 // Write unknown things
549 for (auto& entry : unknown) {
550 s << entry.first;
551 s << entry.second;
552 }
553
554 s << PSBT_SEPARATOR;
555 }
556
557
558 template <typename Stream>
559 inline void Unserialize(Stream& s) {
560 // Used for duplicate key detection
561 std::set<std::vector<unsigned char>> key_lookup;
562 // Cache whether PSBTv2 required fields were seen
563 bool found_prev_txid = false;
564 bool found_prev_out = false;
565
566 // Read loop
567 bool found_sep = false;
568 while(!s.empty()) {
569 // Read the key of format "<keylen><keytype><keydata>" after which
570 // "key" will contain "<keytype><keydata>"
571 std::vector<unsigned char> key;
572 s >> key;
573
574 // the key is empty if that was actually a separator byte
575 // This is a special case for key lengths 0 as those are not allowed (except for separator)
576 if (key.empty()) {
577 found_sep = true;
578 break;
579 }
580
581 // Duplicate keys are not permitted
582 if (!key_lookup.emplace(key).second) {
583 throw std::ios_base::failure(tfm::format("Duplicate Key, input key \"%s\" already provided", HexStr(key)));
584 }
585
586 // "skey" is used so that "key" is unchanged after reading keytype below
587 SpanReader skey{key};
588 // keytype is of the format compact size uint at the beginning of "key"
589 uint64_t type = ReadCompactSize(skey);
590
591 // Do stuff based on keytype "type", i.e., key checks, reading values of the
592 // format "<valuelen><valuedata>" from the stream "s", and value checks
593 switch(type) {
595 {
596 ExpectedKeySize("Input Non-witness UTXO", key, 1);
597 // Set the stream to unserialize with witness since this is always a valid network transaction
599 break;
600 }
602 ExpectedKeySize("Input Witness UTXO", key, 1);
604 break;
606 {
607 // Make sure that the key is the size of pubkey + 1
608 if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
609 throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
610 }
611 // Read in the pubkey from key
612 CPubKey pubkey(key.begin() + 1, key.end());
613 if (!pubkey.IsFullyValid()) {
614 throw std::ios_base::failure("Invalid pubkey");
615 }
616
617 // Read in the signature from value
618 std::vector<unsigned char> sig;
619 s >> sig;
620
621 // Check that the signature is validly encoded
622 if (sig.empty() || !CheckSignatureEncoding(sig, SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC, nullptr)) {
623 throw std::ios_base::failure("Signature is not a valid encoding");
624 }
625
626 // Add to list
627 partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
628 break;
629 }
630 case PSBT_IN_SIGHASH:
631 ExpectedKeySize("Input Sighash Type", key, 1);
632 int sighash;
633 UnserializeFromVector(s, sighash);
634 sighash_type = sighash;
635 break;
637 {
638 ExpectedKeySize("Input redeemScript", key, 1);
639 s >> redeem_script;
640 break;
641 }
643 {
644 ExpectedKeySize("Input witnessScript", key, 1);
645 s >> witness_script;
646 break;
647 }
649 {
651 break;
652 }
654 {
655 ExpectedKeySize("Input Final scriptSig", key, 1);
657 break;
658 }
660 {
661 ExpectedKeySize("Input Final scriptWitness", key, 1);
663 break;
664 }
666 {
667 ExpectedKeySize("Input RIPEMD160 Preimage", key, CRIPEMD160::OUTPUT_SIZE + 1);
668 // Read in the hash from key
669 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
670 uint160 hash(hash_vec);
671
672 // Read in the preimage from value
673 std::vector<unsigned char> preimage;
674 s >> preimage;
675
676 // Add to preimages list
677 ripemd160_preimages.emplace(hash, std::move(preimage));
678 break;
679 }
680 case PSBT_IN_SHA256:
681 {
682 ExpectedKeySize("Input SHA256 Preimage", key, CSHA256::OUTPUT_SIZE + 1);
683 // Read in the hash from key
684 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
685 uint256 hash(hash_vec);
686
687 // Read in the preimage from value
688 std::vector<unsigned char> preimage;
689 s >> preimage;
690
691 // Add to preimages list
692 sha256_preimages.emplace(hash, std::move(preimage));
693 break;
694 }
695 case PSBT_IN_HASH160:
696 {
697 ExpectedKeySize("Input Hash160 Preimage", key, CHash160::OUTPUT_SIZE + 1);
698 // Read in the hash from key
699 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
700 uint160 hash(hash_vec);
701
702 // Read in the preimage from value
703 std::vector<unsigned char> preimage;
704 s >> preimage;
705
706 // Add to preimages list
707 hash160_preimages.emplace(hash, std::move(preimage));
708 break;
709 }
710 case PSBT_IN_HASH256:
711 {
712 ExpectedKeySize("Input Hash256 Preimage", key, CHash256::OUTPUT_SIZE + 1);
713 // Read in the hash from key
714 std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
715 uint256 hash(hash_vec);
716
717 // Read in the preimage from value
718 std::vector<unsigned char> preimage;
719 s >> preimage;
720
721 // Add to preimages list
722 hash256_preimages.emplace(hash, std::move(preimage));
723 break;
724 }
726 {
727 ExpectedKeySize("Input Previous TXID", key, 1);
728 if (m_psbt_version < 2) {
729 throw std::ios_base::failure("Previous txid is not allowed in PSBTv0");
730 }
732 found_prev_txid = true;
733 break;
734 }
736 {
737 ExpectedKeySize("Input Previous Output's Index", key, 1);
738 if (m_psbt_version < 2) {
739 throw std::ios_base::failure("Previous output's index is not allowed in PSBTv0");
740 }
742 found_prev_out = true;
743 break;
744 }
745 case PSBT_IN_SEQUENCE:
746 {
747 ExpectedKeySize("Input Sequence", key, 1);
748 if (m_psbt_version < 2) {
749 throw std::ios_base::failure("Sequence is not allowed in PSBTv0");
750 }
751 sequence.emplace();
753 break;
754 }
756 {
757 ExpectedKeySize("Input Required Time Based Locktime", key, 1);
758 if (m_psbt_version < 2) {
759 throw std::ios_base::failure("Required time based locktime is not allowed in PSBTv0");
760 }
761 time_locktime.emplace();
764 throw std::ios_base::failure("Required time based locktime is invalid (less than 500000000)");
765 }
766 break;
767 }
769 {
770 ExpectedKeySize("Input Required Height Based Locktime", key, 1);
771 if (m_psbt_version < 2) {
772 throw std::ios_base::failure("Required height based locktime is not allowed in PSBTv0");
773 }
774 height_locktime.emplace();
777 throw std::ios_base::failure("Required height based locktime is invalid (greater than or equal to 500000000)");
778 } else if (*height_locktime == 0) {
779 throw std::ios_base::failure("Required height based locktime is invalid (0)");
780 }
781 break;
782 }
784 {
785 ExpectedKeySize("Input Taproot Key Path Signature", key, 1);
786 s >> m_tap_key_sig;
787 if (m_tap_key_sig.size() < 64) {
788 throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
789 } else if (m_tap_key_sig.size() > 65) {
790 throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
791 }
792 break;
793 }
795 {
796 ExpectedKeySize("Input Taproot Script Path Signature", key, 65);
797 SpanReader s_key{std::span{key}.subspan(1)};
798 XOnlyPubKey xonly;
799 uint256 hash;
800 s_key >> xonly;
801 s_key >> hash;
802 std::vector<unsigned char> sig;
803 s >> sig;
804 if (sig.size() < 64) {
805 throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
806 } else if (sig.size() > 65) {
807 throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
808 }
809 m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
810 break;
811 }
813 {
814 if (key.size() < 34) {
815 throw std::ios_base::failure("Input Taproot leaf script key is not at least 34 bytes");
816 } else if ((key.size() - 2) % 32 != 0) {
817 throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
818 }
819 std::vector<unsigned char> script_v;
820 s >> script_v;
821 if (script_v.empty()) {
822 throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
823 }
824 uint8_t leaf_ver = script_v.back();
825 script_v.pop_back();
826 const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
827 m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
828 break;
829 }
831 {
832 ExpectedKeySize("Input Taproot BIP32 Keypath", key, 33);
833 SpanReader s_key{std::span{key}.subspan(1)};
834 XOnlyPubKey xonly;
835 s_key >> xonly;
836 std::set<uint256> leaf_hashes;
837 uint64_t value_len = ReadCompactSize(s);
838 size_t before_hashes = s.size();
839 s >> leaf_hashes;
840 size_t after_hashes = s.size();
841 size_t hashes_len = before_hashes - after_hashes;
842 if (hashes_len > value_len) {
843 throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
844 }
845 size_t origin_len = value_len - hashes_len;
846 m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
847 break;
848 }
850 {
851 ExpectedKeySize("Input Taproot Internal Key", key, 1);
853 break;
854 }
856 {
857 ExpectedKeySize("Input Taproot Merkle Root", key, 1);
859 break;
860 }
862 {
863 ExpectedKeySize("Input MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
864 DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
865 break;
866 }
868 {
869 if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
870 throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
871 }
872 CPubKey agg_pub, part_pub;
873 uint256 leaf_hash;
874 DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
875
876 std::vector<uint8_t> pubnonce;
877 s >> pubnonce;
878 if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) {
879 throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
880 }
881
882 m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
883 break;
884 }
886 {
887 if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
888 throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
889 }
890 CPubKey agg_pub, part_pub;
891 uint256 leaf_hash;
892 DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
893
894 uint256 partial_sig;
895 UnserializeFromVector(s, partial_sig);
896
897 m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
898 break;
899 }
901 {
902 PSBTProprietary this_prop;
903 skey >> this_prop.identifier;
904 this_prop.subtype = ReadCompactSize(skey);
905 this_prop.key = key;
906
907 s >> this_prop.value;
908 m_proprietary.insert(this_prop);
909 break;
910 }
911 // Unknown stuff
912 default:
913 // Read in the value
914 std::vector<unsigned char> val_bytes;
915 s >> val_bytes;
916 unknown.emplace(std::move(key), std::move(val_bytes));
917 break;
918 }
919 }
920
921 if (!found_sep) {
922 throw std::ios_base::failure("Separator is missing at the end of an input map");
923 }
924
925 // Make sure required PSBTv2 fields are present
926 if (m_psbt_version >= 2) {
927 if (!found_prev_txid) {
928 throw std::ios_base::failure("Previous TXID is required in PSBTv2");
929 }
930 if (!found_prev_out) {
931 throw std::ios_base::failure("Previous output's index is required in PSBTv2");
932 }
933 }
934 }
935};
936
939{
940private:
942
943public:
946 std::map<CPubKey, KeyOriginInfo> hd_keypaths;
947
949 std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
950 std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
951 std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
952
953 std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
954 std::set<PSBTProprietary> m_proprietary;
955
958
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 uint32_t GetVersion() const;
1257
1260 [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
1264 bool AddInput(const PSBTInput& psbtin);
1265 bool AddOutput(const PSBTOutput& psbtout);
1266 std::optional<uint32_t> ComputeTimeLock() const;
1267 std::optional<CMutableTransaction> GetUnsignedTx() const;
1268 std::optional<Txid> GetUniqueID() const;
1269 explicit PartiallySignedTransaction(const CMutableTransaction& tx, uint32_t version = 2);
1270
1271 template <typename Stream>
1272 inline void Serialize(Stream& s) const {
1273
1274 // magic bytes
1276
1277 if (GetVersion() < 2) {
1278 // unsigned tx flag
1280
1281 // Write serialized tx to a stream
1283 }
1284
1285 // Write xpubs
1286 for (const auto& xpub_pair : m_xpubs) {
1287 for (const auto& xpub : xpub_pair.second) {
1288 unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
1289 xpub.EncodeWithVersion(ser_xpub);
1290 // Note that the serialization swaps the key and value
1291 // The xpub is the key (for uniqueness) while the path is the value
1293 SerializeHDKeypath(s, xpub_pair.first);
1294 }
1295 }
1296
1297 if (GetVersion() >= 2) {
1298 // Write PSBTv2 tx version, locktime, counts, etc.
1301 if (fallback_locktime != std::nullopt) {
1304 }
1305
1310
1311 if (m_tx_modifiable != std::nullopt) {
1313 SerializeToVector(s, static_cast<uint8_t>(m_tx_modifiable->to_ulong()));
1314 }
1315 }
1316
1317 // PSBT version
1318 if (GetVersion() > 0) {
1321 }
1322
1323 // Write proprietary things
1324 for (const auto& entry : m_proprietary) {
1325 s << entry.key;
1326 s << entry.value;
1327 }
1328
1329 // Write the unknown things
1330 for (auto& entry : unknown) {
1331 s << entry.first;
1332 s << entry.second;
1333 }
1334
1335 // Separator
1336 s << PSBT_SEPARATOR;
1337
1338 // Write inputs
1339 for (const PSBTInput& input : inputs) {
1340 s << input;
1341 }
1342 // Write outputs
1343 for (const PSBTOutput& output : outputs) {
1344 s << output;
1345 }
1346 }
1347
1348
1349 template <typename Stream>
1350 inline void Unserialize(Stream& s) {
1351 // Read the magic bytes
1352 uint8_t magic[5];
1353 s >> magic;
1354 if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
1355 throw std::ios_base::failure("Invalid PSBT magic bytes");
1356 }
1357
1358 // Used for duplicate key detection
1359 std::set<std::vector<unsigned char>> key_lookup;
1360
1361 // Read global data
1362 bool found_sep = false;
1363 std::optional<CMutableTransaction> tx;
1364 uint64_t input_count = 0;
1365 uint64_t output_count = 0;
1366 bool found_input_count = false;
1367 bool found_output_count = false;
1368 bool found_tx_version = false;
1369 bool found_fallback_locktime = false;
1370 while(!s.empty()) {
1371 // Read the key of format "<keylen><keytype><keydata>" after which
1372 // "key" will contain "<keytype><keydata>"
1373 std::vector<unsigned char> key;
1374 s >> key;
1375
1376 // the key is empty if that was actually a separator byte
1377 // This is a special case for key lengths 0 as those are not allowed (except for separator)
1378 if (key.empty()) {
1379 found_sep = true;
1380 break;
1381 }
1382
1383 // Duplicate keys are not permitted
1384 if (!key_lookup.emplace(key).second) {
1385 throw std::ios_base::failure(tfm::format("Duplicate Key, global key \"%s\" already provided", HexStr(key)));
1386 }
1387
1388 // "skey" is used so that "key" is unchanged after reading keytype below
1389 SpanReader skey{key};
1390 // keytype is of the format compact size uint at the beginning of "key"
1391 uint64_t type = ReadCompactSize(skey);
1392
1393 // Do stuff based on keytype "type", i.e., key checks, reading values of the
1394 // format "<valuelen><valuedata>" from the stream "s", and value checks
1395 switch(type) {
1397 {
1398 ExpectedKeySize("Global Unsigned TX", key, 1);
1399 // Set the stream to serialize with non-witness since this should always be non-witness
1400 tx.emplace();
1402 // Make sure that all scriptSigs and scriptWitnesses are empty
1403 for (const CTxIn& txin : tx->vin) {
1404 if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
1405 throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
1406 }
1407 }
1408 tx_version = tx->version;
1409 fallback_locktime = tx->nLockTime;
1410 // Set the input and output counts
1411 input_count = tx->vin.size();
1412 output_count = tx->vout.size();
1413 break;
1414 }
1416 {
1417 ExpectedKeySize("Global Transaction Version", key, 1);
1419 found_tx_version = true;
1420 break;
1421 }
1423 {
1424 ExpectedKeySize("Global Fallback Locktime", key, 1);
1425 fallback_locktime.emplace();
1427 found_fallback_locktime = true;
1428 break;
1429 }
1431 {
1432 ExpectedKeySize("Global Input Count", key, 1);
1433 CompactSizeReader reader(input_count);
1435 found_input_count = true;
1436 break;
1437 }
1439 {
1440 ExpectedKeySize("Global Output Count", key, 1);
1441 CompactSizeReader reader(output_count);
1443 found_output_count = true;
1444 break;
1445 }
1447 {
1448 ExpectedKeySize("Global TX Modifiable Flags", key, 1);
1449 uint8_t tx_mod;
1450 UnserializeFromVector(s, tx_mod);
1451 m_tx_modifiable.emplace(tx_mod);
1452 break;
1453 }
1454 case PSBT_GLOBAL_XPUB:
1455 {
1456 ExpectedKeySize("Global XPUB", key, BIP32_EXTKEY_WITH_VERSION_SIZE + 1);
1457 // Read in the xpub from key
1458 CExtPubKey xpub;
1459 xpub.DecodeWithVersion(&key.data()[1]);
1460 if (!xpub.pubkey.IsFullyValid()) {
1461 throw std::ios_base::failure("Invalid pubkey");
1462 }
1463 // Read in the keypath from stream
1464 KeyOriginInfo keypath;
1465 DeserializeHDKeypath(s, keypath);
1466
1467 // Note that we store these swapped to make searches faster.
1468 // Serialization uses xpub -> keypath to enqure key uniqueness
1469 if (!m_xpubs.contains(keypath)) {
1470 // Make a new set to put the xpub in
1471 m_xpubs[keypath] = {xpub};
1472 } else {
1473 // Insert xpub into existing set
1474 m_xpubs[keypath].insert(xpub);
1475 }
1476 break;
1477 }
1479 {
1480 ExpectedKeySize("Global PSBT Version", key, 1);
1481 uint32_t v;
1483 m_version = v;
1485 throw std::ios_base::failure("Unsupported version number");
1486 }
1487 break;
1488 }
1490 {
1491 PSBTProprietary this_prop;
1492 skey >> this_prop.identifier;
1493 this_prop.subtype = ReadCompactSize(skey);
1494 this_prop.key = key;
1495
1496 s >> this_prop.value;
1497 m_proprietary.insert(this_prop);
1498 break;
1499 }
1500 // Unknown stuff
1501 default: {
1502 // Read in the value
1503 std::vector<unsigned char> val_bytes;
1504 s >> val_bytes;
1505 unknown.emplace(std::move(key), std::move(val_bytes));
1506 }
1507 }
1508 }
1509
1510 if (!found_sep) {
1511 throw std::ios_base::failure("Separator is missing at the end of the global map");
1512 }
1513
1514 const uint32_t psbt_ver = GetVersion();
1515
1516 // Check PSBT version constraints
1517 if (psbt_ver == 0) {
1518 // Make sure that we got an unsigned tx for PSBTv0
1519 if (!tx) {
1520 throw std::ios_base::failure("No unsigned transaction was provided");
1521 }
1522 // Make sure no PSBTv2 fields are present
1523 if (found_tx_version) {
1524 throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is not allowed in PSBTv0");
1525 }
1526 if (found_fallback_locktime) {
1527 throw std::ios_base::failure("PSBT_GLOBAL_FALLBACK_LOCKTIME is not allowed in PSBTv0");
1528 }
1529 if (found_input_count) {
1530 throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is not allowed in PSBTv0");
1531 }
1532 if (found_output_count) {
1533 throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is not allowed in PSBTv0");
1534 }
1535 if (m_tx_modifiable != std::nullopt) {
1536 throw std::ios_base::failure("PSBT_GLOBAL_TX_MODIFIABLE is not allowed in PSBTv0");
1537 }
1538 }
1539 // Disallow v1
1540 if (psbt_ver == 1) {
1541 throw std::ios_base::failure("There is no PSBT version 1");
1542 }
1543 if (psbt_ver == 2) {
1544 // Tx version, input, and output counts are required
1545 if (!found_tx_version) {
1546 throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is required in PSBTv2");
1547 }
1548 if (!found_input_count) {
1549 throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is required in PSBTv2");
1550 }
1551 if (!found_output_count) {
1552 throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is required in PSBTv2");
1553 }
1554 // Unsigned tx is disallowed
1555 if (tx) {
1556 throw std::ios_base::failure("PSBT_GLOBAL_UNSIGNED_TX is not allowed in PSBTv2");
1557 }
1558 }
1559 if (psbt_ver > 2) {
1560 throw std::ios_base::failure("Unknown PSBT version");
1561 }
1562
1563 // Read input data
1564 unsigned int i = 0;
1565 while (!s.empty() && i < input_count) {
1566 if (psbt_ver < 2) {
1567 inputs.emplace_back(psbt_ver, tx->vin[i].prevout.hash, tx->vin[i].prevout.n, tx->vin[i].nSequence);
1568 s >> inputs.back();
1569 } else {
1570 inputs.emplace_back(deserialize, s, psbt_ver);
1571 }
1572
1573 // Make sure the non-witness utxo matches the outpoint
1574 const PSBTInput& input = inputs.back();
1575 if (input.non_witness_utxo) {
1576 if (psbt_ver < 2) {
1577 if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
1578 throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1579 }
1580 if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
1581 throw std::ios_base::failure("Input specifies output index that does not exist");
1582 }
1583 } else {
1584 if (input.non_witness_utxo->GetHash() != input.prev_txid) {
1585 throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1586 }
1587 if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1588 throw std::ios_base::failure("Input specifies output index that does not exist");
1589 }
1590 }
1591 }
1592 ++i;
1593 }
1594 // Make sure that the number of inputs matches the number of inputs in the transaction
1595 if (inputs.size() != input_count) {
1596 throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
1597 }
1598
1599 // Read output data
1600 i = 0;
1601 while (!s.empty() && i < output_count) {
1602 if (psbt_ver < 2) {
1603 outputs.emplace_back(psbt_ver, tx->vout[i].nValue, tx->vout[i].scriptPubKey);
1604 s >> outputs.back();
1605 } else {
1606 outputs.emplace_back(deserialize, s, psbt_ver);
1607 }
1608 ++i;
1609 }
1610 // Make sure that the number of outputs matches the number of outputs in the transaction
1611 if (outputs.size() != output_count) {
1612 throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
1613 }
1614 }
1615
1616 template <typename Stream>
1618 Unserialize(s);
1619 }
1620};
1621
1622enum class PSBTRole {
1623 CREATOR,
1624 UPDATER,
1625 SIGNER,
1626 FINALIZER,
1627 EXTRACTOR
1628};
1629
1630std::string PSBTRoleName(PSBTRole role);
1631
1633std::optional<PrecomputedTransactionData> PrecomputePSBTData(const PartiallySignedTransaction& psbt);
1634
1636bool PSBTInputSigned(const PSBTInput& input);
1637
1639bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
1640
1646[[nodiscard]] util::Expected<void, PSBTError> SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options, SignatureData* out_sigdata = nullptr);
1647
1650
1653
1659
1667
1676
1683[[nodiscard]] std::optional<PartiallySignedTransaction> CombinePSBTs(const std::vector<PartiallySignedTransaction>& psbtxs);
1684
1686[[nodiscard]] util::Result<PartiallySignedTransaction> DecodeBase64PSBT(const std::string& base64_tx);
1688[[nodiscard]] util::Result<PartiallySignedTransaction> DecodeRawPSBT(std::span<const std::byte> tx_data);
1689
1690#endif // BITCOIN_PSBT_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
ArgsManager & args
Definition: bitcoind.cpp:280
static constexpr size_t OUTPUT_SIZE
Definition: hash.h:61
static constexpr size_t OUTPUT_SIZE
Definition: hash.h:36
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:40
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
Definition: pubkey.h:166
static constexpr unsigned int COMPRESSED_SIZE
Definition: pubkey.h:46
static constexpr unsigned int SIZE
secp256k1:
Definition: pubkey.h:45
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:95
static constexpr size_t OUTPUT_SIZE
Definition: ripemd160.h:20
static constexpr size_t OUTPUT_SIZE
Definition: sha256.h:21
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:406
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:282
std::vector< unsigned char > m_tap_key_sig
Definition: psbt.h:307
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:293
uint32_t m_psbt_version
Definition: psbt.h:284
std::map< uint256, std::vector< unsigned char > > hash256_preimages
Definition: psbt.h:298
bool Merge(const PSBTInput &input)
Definition: psbt.cpp:423
CScriptWitness final_script_witness
Definition: psbt.h:292
std::optional< uint32_t > sequence
Definition: psbt.h:302
std::map< std::pair< CPubKey, uint256 >, std::map< CPubKey, std::vector< uint8_t > > > m_musig2_pubnonces
Definition: psbt.h:317
bool HasSignatures() const
Definition: psbt.cpp:463
bool GetUTXO(CTxOut &utxo) const
Retrieves the UTXO for this input.
Definition: psbt.cpp:270
std::map< std::pair< std::vector< unsigned char >, int >, std::set< std::vector< unsigned char >, ShortestVectorFirstComparator > > m_tap_scripts
Definition: psbt.h:309
CTransactionRef non_witness_utxo
Definition: psbt.h:287
Txid prev_txid
Definition: psbt.h:300
std::map< CKeyID, SigPair > partial_sigs
Definition: psbt.h:294
std::optional< int > sighash_type
Definition: psbt.h:323
std::map< std::pair< XOnlyPubKey, uint256 >, std::vector< unsigned char > > m_tap_script_sigs
Definition: psbt.h:308
void Serialize(Stream &s) const
Definition: psbt.h:360
std::optional< uint32_t > time_locktime
Definition: psbt.h:303
uint256 m_tap_merkle_root
Definition: psbt.h:312
std::map< uint256, std::vector< unsigned char > > sha256_preimages
Definition: psbt.h:296
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:293
std::map< std::pair< CPubKey, uint256 >, std::map< CPubKey, uint256 > > m_musig2_partial_sigs
Definition: psbt.h:319
COutPoint GetOutPoint() const
Definition: psbt.cpp:288
std::map< uint160, std::vector< unsigned char > > hash160_preimages
Definition: psbt.h:297
bool operator==(const PSBTInput &) const =default
uint32_t prev_out
Definition: psbt.h:301
PSBTInput(uint32_t psbt_version, const Txid &prev_txid, uint32_t prev_out, std::optional< uint32_t > sequence=std::nullopt)
Definition: psbt.h:339
void Unserialize(Stream &s)
Definition: psbt.h:559
std::map< CPubKey, std::vector< CPubKey > > m_musig2_participants
Definition: psbt.h:315
std::set< PSBTProprietary > m_proprietary
Definition: psbt.h:322
CScript redeem_script
Definition: psbt.h:289
CScript final_script_sig
Definition: psbt.h:291
PSBTInput(deserialize_type, Stream &s, uint32_t psbt_version)
Definition: psbt.h:350
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:357
uint32_t GetVersion() const
Definition: psbt.h:328
XOnlyPubKey m_tap_internal_key
Definition: psbt.h:311
std::optional< uint32_t > height_locktime
Definition: psbt.h:304
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > m_tap_bip32_paths
Definition: psbt.h:310
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:321
std::map< uint160, std::vector< unsigned char > > ripemd160_preimages
Definition: psbt.h:295
CTxOut witness_utxo
Definition: psbt.h:288
CScript witness_script
Definition: psbt.h:290
A structure for PSBTs which contains per output information.
Definition: psbt.h:939
std::map< CPubKey, std::vector< CPubKey > > m_musig2_participants
Definition: psbt.h:951
XOnlyPubKey m_tap_internal_key
Definition: psbt.h:948
std::map< XOnlyPubKey, std::pair< std::set< uint256 >, KeyOriginInfo > > m_tap_bip32_paths
Definition: psbt.h:950
bool operator==(const PSBTOutput &) const =default
CScript witness_script
Definition: psbt.h:945
std::set< PSBTProprietary > m_proprietary
Definition: psbt.h:954
PSBTOutput(deserialize_type, Stream &s, uint32_t psbt_version)
Definition: psbt.h:974
CAmount amount
Definition: psbt.h:956
CScript redeem_script
Definition: psbt.h:944
void Serialize(Stream &s) const
Definition: psbt.h:984
CScript script
Definition: psbt.h:957
uint32_t GetVersion() const
Definition: psbt.h:962
uint32_t m_psbt_version
Definition: psbt.h:941
bool Merge(const PSBTOutput &output)
Definition: psbt.cpp:527
std::map< CPubKey, KeyOriginInfo > hd_keypaths
Definition: psbt.h:946
std::vector< std::tuple< uint8_t, uint8_t, std::vector< unsigned char > > > m_tap_tree
Definition: psbt.h:949
void Unserialize(Stream &s)
Definition: psbt.h:1067
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:953
void FillSignatureData(SignatureData &sigdata) const
Definition: psbt.cpp:473
PSBTOutput(uint32_t psbt_version, CAmount amount, const CScript &script)
Definition: psbt.h:964
void FromSignatureData(const SignatureData &sigdata)
Definition: psbt.cpp:504
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:881
bool Merge(const PartiallySignedTransaction &psbt)
Merge psbt into this.
Definition: psbt.cpp:36
std::map< KeyOriginInfo, std::set< CExtPubKey > > m_xpubs
Definition: psbt.h:1246
std::optional< uint32_t > m_version
Definition: psbt.h:1241
std::optional< Txid > GetUniqueID() const
Definition: psbt.cpp:149
std::map< std::vector< unsigned char >, std::vector< unsigned char > > unknown
Definition: psbt.h:1250
std::vector< PSBTInput > inputs
Definition: psbt.h:1248
void MergeGlobalXPubs(const PartiallySignedTransaction &psbt)
Merge the global xpubs of psbt into this, keeping the existing origin for an xpub seen again with a d...
Definition: psbt.cpp:79
std::optional< CMutableTransaction > GetUnsignedTx() const
Definition: psbt.cpp:123
std::optional< uint32_t > ComputeTimeLock() const
Definition: psbt.cpp:89
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:1272
bool AddOutput(const PSBTOutput &psbtout)
Definition: psbt.cpp:247
PartiallySignedTransaction(deserialize_type, Stream &s)
Definition: psbt.h:1617
std::optional< uint32_t > fallback_locktime
Definition: psbt.h:1254
void Unserialize(Stream &s)
Definition: psbt.h:1350
PartiallySignedTransaction(const CMutableTransaction &tx, uint32_t version=2)
Definition: psbt.cpp:20
bool AddInput(const PSBTInput &psbtin)
Definition: psbt.cpp:164
An interface to be implemented by keystores that support signing.
uint64_t size() const
Definition: serialize.h:1139
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:256
constexpr bool IsNull() const
Definition: uint256.h:50
constexpr void SetNull()
Definition: uint256.h:57
bool empty() const
Definition: prevector.h:251
160-bit opaque blob.
Definition: uint256.h:184
256-bit opaque blob.
Definition: uint256.h:196
The util::Expected class provides a standard way for low-level functions to return either error value...
Definition: expected.h:44
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
util::LineReader reader
bool CheckSignatureEncoding(const std::vector< unsigned char > &vchSig, script_verify_flags flags, ScriptError *serror)
constexpr uint8_t TAPROOT_LEAF_MASK
Definition: interpreter.h:242
constexpr size_t TAPROOT_CONTROL_MAX_NODE_COUNT
Definition: interpreter.h:246
constexpr size_t MUSIG2_PUBNONCE_SIZE
Definition: musig.h:18
PSBTError
Definition: types.h:19
SocketId Stream
Definition: util.h:30
Definition: messages.h:21
TransactionError
Definition: types.h:19
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:621
constexpr TransactionSerParams TX_NO_WITNESS
Definition: transaction.h:181
constexpr TransactionSerParams TX_WITH_WITNESS
Definition: transaction.h:180
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
constexpr uint8_t PSBT_OUT_AMOUNT
Definition: psbt.h:80
void SerializeToVector(Stream &s, const X &... args)
Definition: psbt.h:118
constexpr uint8_t PSBT_IN_REQUIRED_HEIGHT_LOCKTIME
Definition: psbt.h:64
constexpr uint8_t PSBT_IN_RIPEMD160
Definition: psbt.h:56
void UpdatePSBTOutput(const SigningProvider &provider, PartiallySignedTransaction &psbt, int index)
Updates a PSBTOutput with information from provider.
Definition: psbt.cpp:593
constexpr uint8_t PSBT_IN_HASH256
Definition: psbt.h:59
constexpr uint8_t PSBT_IN_REQUIRED_TIME_LOCKTIME
Definition: psbt.h:63
constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX
Definition: psbt.h:36
constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO
Definition: psbt.h:47
util::Expected< void, 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:639
constexpr uint8_t PSBT_IN_TAP_KEY_SIG
Definition: psbt.h:65
void UnserializeFromVector(Stream &s, X &&... args)
Definition: psbt.h:128
constexpr uint8_t PSBT_IN_SCRIPTSIG
Definition: psbt.h:54
constexpr uint8_t PSBT_IN_WITNESSSCRIPT
Definition: psbt.h:52
constexpr uint8_t PSBT_IN_OUTPUT_INDEX
Definition: psbt.h:61
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:548
std::string PSBTRoleName(PSBTRole role)
Definition: psbt.cpp:847
util::Result< PartiallySignedTransaction > DecodeBase64PSBT(const std::string &base64_tx)
Decode a base64ed PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:858
constexpr uint8_t PSBT_OUT_REDEEMSCRIPT
Definition: psbt.h:77
constexpr uint8_t PSBT_GLOBAL_VERSION
Definition: psbt.h:43
constexpr uint8_t PSBT_GLOBAL_TX_VERSION
Definition: psbt.h:38
constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT
Definition: psbt.h:67
constexpr uint8_t PSBT_OUT_PROPRIETARY
Definition: psbt.h:86
constexpr uint8_t PSBT_MAGIC_BYTES[5]
Definition: psbt.h:33
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:834
constexpr uint32_t PSBT_HIGHEST_VERSION
Definition: psbt.h:97
constexpr uint8_t PSBT_SEPARATOR
Definition: psbt.h:90
constexpr uint8_t PSBT_IN_BIP32_DERIVATION
Definition: psbt.h:53
void DeserializeMuSig2ParticipantPubkeys(Stream &s, SpanReader &skey, std::map< CPubKey, std::vector< CPubKey > > &out, std::string context)
Definition: psbt.h:219
constexpr uint8_t PSBT_IN_SCRIPTWITNESS
Definition: psbt.h:55
constexpr uint8_t PSBT_OUT_TAP_TREE
Definition: psbt.h:83
constexpr uint8_t PSBT_IN_PREVIOUS_TXID
Definition: psbt.h:60
constexpr uint8_t PSBT_OUT_BIP32_DERIVATION
Definition: psbt.h:79
PSBTRole
Definition: psbt.h:1622
constexpr uint8_t PSBT_GLOBAL_PROPRIETARY
Definition: psbt.h:44
void RemoveUnnecessaryTransactions(PartiallySignedTransaction &psbtx)
Reduces the size of the PSBT by dropping unnecessary non_witness_utxos (i.e.
Definition: psbt.cpp:756
std::optional< PrecomputedTransactionData > PrecomputePSBTData(const PartiallySignedTransaction &psbt)
Compute a PrecomputedTransactionData object from a psbt.
Definition: psbt.cpp:618
constexpr uint8_t PSBT_IN_PROPRIETARY
Definition: psbt.h:74
constexpr uint8_t PSBT_GLOBAL_TX_MODIFIABLE
Definition: psbt.h:42
constexpr uint8_t PSBT_IN_SEQUENCE
Definition: psbt.h:62
KeyOriginInfo DeserializeKeyOrigin(Stream &s, uint64_t length)
Definition: psbt.h:141
void DeserializeMuSig2ParticipantDataIdentifier(Stream &skey, CPubKey &agg_pub, CPubKey &part_pub, uint256 &leaf_hash)
Definition: psbt.h:251
constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG
Definition: psbt.h:66
constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE
Definition: psbt.h:72
void SerializeHDKeypaths(Stream &s, const std::map< CPubKey, KeyOriginInfo > &hd_keypaths, CompactSizeWriter type)
Definition: psbt.h:206
static void ExpectedKeySize(const std::string &key_name, const std::vector< unsigned char > &key, uint64_t expected_size)
Definition: psbt.h:274
constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION
Definition: psbt.h:68
constexpr uint8_t PSBT_IN_HASH160
Definition: psbt.h:58
constexpr uint8_t PSBT_IN_REDEEMSCRIPT
Definition: psbt.h:51
constexpr uint8_t PSBT_OUT_WITNESSSCRIPT
Definition: psbt.h:78
constexpr uint8_t PSBT_GLOBAL_XPUB
Definition: psbt.h:37
constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS
Definition: psbt.h:85
constexpr uint8_t PSBT_GLOBAL_OUTPUT_COUNT
Definition: psbt.h:41
constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION
Definition: psbt.h:84
constexpr uint8_t PSBT_IN_PARTIAL_SIG
Definition: psbt.h:49
constexpr uint8_t PSBT_GLOBAL_FALLBACK_LOCKTIME
Definition: psbt.h:39
constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY
Definition: psbt.h:69
constexpr std::streamsize MAX_FILE_SIZE_PSBT
Definition: psbt.h:94
size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction &psbt)
Counts the unsigned inputs of a PSBT.
Definition: psbt.cpp:582
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:814
constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY
Definition: psbt.h:82
constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT
Definition: psbt.h:70
void SerializeKeyOrigin(Stream &s, KeyOriginInfo hd_keypath)
Definition: psbt.h:188
void DeserializeHDKeypaths(Stream &s, const std::vector< unsigned char > &key, std::map< CPubKey, KeyOriginInfo > &hd_keypaths)
Definition: psbt.h:167
constexpr uint8_t PSBT_IN_SIGHASH
Definition: psbt.h:50
bool PSBTInputSigned(const PSBTInput &input)
Checks whether a PSBTInput is already signed by checking for non-null finalized fields.
Definition: psbt.cpp:543
constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS
Definition: psbt.h:71
void SerializeHDKeypath(Stream &s, KeyOriginInfo hd_keypath)
Definition: psbt.h:198
void DeserializeHDKeypath(Stream &s, KeyOriginInfo &hd_keypath)
Definition: psbt.h:160
bool FinalizePSBT(PartiallySignedTransaction &psbtx)
Finalizes a PSBT if possible, combining partial signatures.
Definition: psbt.cpp:793
constexpr uint8_t PSBT_OUT_SCRIPT
Definition: psbt.h:81
util::Result< PartiallySignedTransaction > DecodeRawPSBT(std::span< const std::byte > tx_data)
Decode a raw (binary blob) PSBT into a PartiallySignedTransaction.
Definition: psbt.cpp:867
constexpr uint8_t PSBT_GLOBAL_INPUT_COUNT
Definition: psbt.h:40
constexpr uint8_t PSBT_IN_WITNESS_UTXO
Definition: psbt.h:48
constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG
Definition: psbt.h:73
constexpr uint8_t PSBT_IN_SHA256
Definition: psbt.h:57
constexpr unsigned int BIP32_EXTKEY_WITH_VERSION_SIZE
Definition: pubkey.h:20
constexpr unsigned int LOCKTIME_THRESHOLD
Definition: script.h:48
std::vector< unsigned char > ToByteVector(const T &in)
Definition: script.h:68
void SerializeMany(Stream &s, const Args &... args)
Support for (un)serializing many things at once.
Definition: serialize.h:1047
constexpr deserialize_type deserialize
Definition: serialize.h:52
void UnserializeMany(Stream &s, Args &&... args)
Definition: serialize.h:1053
void WriteCompactSize(SizeComputer &os, uint64_t nSize)
Definition: serialize.h:1151
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:333
std::pair< CPubKey, std::vector< unsigned char > > SigPair
Definition: sign.h:82
void DecodeWithVersion(const unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE])
Definition: pubkey.cpp:409
CPubKey pubkey
Definition: pubkey.h:348
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< std::vector< unsigned char > > stack
Definition: script.h:581
bool IsNull() const
Definition: script.h:586
KeyFingerprint fingerprint
First 32 bits of the Hash160 of the public key at the root of the path.
Definition: keyorigin.h:14
std::vector< uint32_t > path
Definition: keyorigin.h:15
A structure for PSBT proprietary types.
Definition: psbt.h:101
std::vector< unsigned char > value
Definition: psbt.h:105
bool operator<(const PSBTProprietary &b) const
Definition: psbt.h:107
uint64_t subtype
Definition: psbt.h:102
std::vector< unsigned char > identifier
Definition: psbt.h:103
std::vector< unsigned char > key
Definition: psbt.h:104
bool operator==(const PSBTProprietary &b) const
Definition: psbt.h:110
Instructions for how a PSBT should be signed or filled with information.
Definition: types.h:31
Dummy data type to identify deserializing constructors.
Definition: serialize.h:51
FuzzedDataProvider provider
Definition: dbwrapper.cpp:366
assert(!tx.IsCoinBase())