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