LCOV - code coverage report
Current view: top level - src - psbt.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 99.4 % 682 678
Test Date: 2026-01-07 04:18:29 Functions: 97.7 % 43 42
Branches: 75.1 % 1020 766

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

Generated by: LCOV version 2.0-1