LCOV - code coverage report
Current view: top level - src - psbt.h (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 85.7 % 676 579
Test Date: 2025-06-01 06:26:32 Functions: 90.7 % 43 39
Branches: 56.0 % 984 551

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

Generated by: LCOV version 2.0-1