psbt.h raw

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