LCOV - code coverage report
Current view: top level - src - psbt.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 91.9 % 675 620
Test Date: 2025-04-25 04:10:03 Functions: 90.7 % 43 39
Branches: 72.0 % 978 704

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

Generated by: LCOV version 2.0-1