LCOV - code coverage report
Current view: top level - src - psbt.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 99.7 % 677 675
Test Date: 2025-11-19 04:08:06 Functions: 97.7 % 43 42
Branches: 75.8 % 1008 764

             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                 :       70071 : 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                 :      421464 :     bool operator<(const PSBTProprietary &b) const {
      91                 :      421464 :         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                 :      373370 : void SerializeToVector(Stream& s, const X&... args)
     102                 :             : {
     103                 :      373370 :     SizeComputer sizecomp;
     104                 :      373370 :     SerializeMany(sizecomp, args...);
     105                 :      373370 :     WriteCompactSize(s, sizecomp.size());
     106                 :      373370 :     SerializeMany(s, args...);
     107                 :      373370 : }
     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                 :      156418 : void UnserializeFromVector(Stream& s, X&&... args)
     112                 :             : {
     113         [ -  + ]:      156418 :     size_t expected_size = ReadCompactSize(s);
     114                 :      156411 :     size_t remaining_before = s.size();
     115         [ -  + ]:      155520 :     UnserializeMany(s, args...);
     116                 :      155520 :     size_t remaining_after = s.size();
     117         [ +  + ]:      155520 :     if (remaining_after + expected_size != remaining_before) {
     118         [ +  - ]:        1304 :         throw std::ios_base::failure("Size of value was not the stated size");
     119                 :             :     }
     120                 :      154868 : }
     121                 :             : 
     122                 :             : // Deserialize bytes of given length from the stream as a KeyOriginInfo
     123                 :             : template<typename Stream>
     124                 :      107571 : KeyOriginInfo DeserializeKeyOrigin(Stream& s, uint64_t length)
     125                 :             : {
     126                 :             :     // Read in key path
     127   [ +  +  +  + ]:      107571 :     if (length % 4 || length == 0) {
     128         [ +  - ]:         222 :         throw std::ios_base::failure("Invalid length for HD key path");
     129                 :             :     }
     130                 :             : 
     131                 :      107460 :     KeyOriginInfo hd_keypath;
     132         [ +  + ]:      107460 :     s >> hd_keypath.fingerprint;
     133         [ +  + ]:     3046678 :     for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
     134                 :             :         uint32_t index;
     135                 :     2939258 :         s >> index;
     136         [ +  - ]:     2939258 :         hd_keypath.path.push_back(index);
     137                 :             :     }
     138                 :      107361 :     return hd_keypath;
     139                 :          99 : }
     140                 :             : 
     141                 :             : // Deserialize a length prefixed KeyOriginInfo from a stream
     142                 :             : template<typename Stream>
     143                 :       76774 : void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
     144                 :             : {
     145                 :       76774 :     hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
     146                 :       76565 : }
     147                 :             : 
     148                 :             : // Deserialize HD keypaths into a map
     149                 :             : template<typename Stream>
     150         [ -  + ]:       55885 : 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   [ +  +  +  + ]:       55885 :     if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
     154         [ +  - ]:       16390 :         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                 :       47690 :     CPubKey pubkey(key.begin() + 1, key.end());
     158         [ +  + ]:       47690 :     if (!pubkey.IsFullyValid()) {
     159         [ +  - ]:         362 :        throw std::ios_base::failure("Invalid pubkey");
     160                 :             :     }
     161         [ +  + ]:       47509 :     if (hd_keypaths.count(pubkey) > 0) {
     162         [ +  - ]:          46 :         throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided");
     163                 :             :     }
     164                 :             : 
     165                 :       47486 :     KeyOriginInfo keypath;
     166         [ +  + ]:       47486 :     DeserializeHDKeypath(s, keypath);
     167                 :             : 
     168                 :             :     // Add to map
     169         [ +  - ]:       47336 :     hd_keypaths.emplace(pubkey, std::move(keypath));
     170                 :       47336 : }
     171                 :             : 
     172                 :             : // Serialize a KeyOriginInfo to a stream
     173                 :             : template<typename Stream>
     174                 :       54782 : void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
     175                 :             : {
     176                 :       54782 :     s << hd_keypath.fingerprint;
     177         [ +  + ]:     2327738 :     for (const auto& path : hd_keypath.path) {
     178                 :     2272956 :         s << path;
     179                 :             :     }
     180                 :       54782 : }
     181                 :             : 
     182                 :             : // Serialize a length prefixed KeyOriginInfo to a stream
     183                 :             : template<typename Stream>
     184                 :       38663 : void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
     185                 :             : {
     186         [ -  + ]:       38663 :     WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
     187         [ +  - ]:       38663 :     SerializeKeyOrigin(s, hd_keypath);
     188                 :       38663 : }
     189                 :             : 
     190                 :             : // Serialize HD keypaths to a stream from a map
     191                 :             : template<typename Stream>
     192                 :      260807 : void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
     193                 :             : {
     194         [ +  + ]:      286592 :     for (const auto& keypath_pair : hd_keypaths) {
     195         [ +  + ]:       25935 :         if (!keypath_pair.first.IsValid()) {
     196         [ +  - ]:         300 :             throw std::ios_base::failure("Invalid CPubKey being serialized");
     197                 :             :         }
     198                 :       25785 :         SerializeToVector(s, type, std::span{keypath_pair.first});
     199         [ +  - ]:       51570 :         SerializeHDKeypath(s, keypath_pair.second);
     200                 :             :     }
     201                 :      260657 : }
     202                 :             : 
     203                 :             : // Deserialize a PSBT_{IN/OUT}_MUSIG2_PARTICIPANT_PUBKEYS field
     204                 :             : template<typename Stream>
     205                 :       31801 : 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                 :       31801 :     skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
     209                 :       31801 :     CPubKey agg_pubkey(agg_pubkey_bytes);
     210                 :             : 
     211                 :       31801 :     std::vector<CPubKey> participants;
     212         [ +  + ]:       31801 :     std::vector<unsigned char> val;
     213         [ -  + ]:       31754 :     s >> val;
     214                 :       31754 :     SpanReader s_val{val};
     215         [ +  + ]:      104405 :     while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
     216                 :             :         std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
     217   [ +  -  +  - ]:      145302 :         s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
     218         [ +  - ]:       72651 :         participants.emplace_back(std::span{part_pubkey_bytes});
     219                 :             :     }
     220         [ +  + ]:       31754 :     if (!s_val.empty()) {
     221   [ +  -  +  - ]:         200 :         throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
     222                 :             :     }
     223                 :             : 
     224         [ +  - ]:       31654 :     out.emplace(agg_pubkey, participants);
     225                 :       31801 : }
     226                 :             : 
     227                 :             : // Deserialize the MuSig2 participant identifiers from PSBT_MUSIG2_{PUBNONCE/PARTIAL_SIG} fields
     228                 :             : // Both fields contain the same data after the type byte - aggregate pubkey | participant pubkey | leaf script hash
     229                 :             : template<typename Stream>
     230                 :       42992 : void DeserializeMuSig2ParticipantDataIdentifier(Stream& skey, CPubKey& agg_pub, CPubKey& part_pub, uint256& leaf_hash)
     231                 :             : {
     232                 :       42992 :     leaf_hash.SetNull();
     233                 :             : 
     234                 :             :     std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
     235                 :             :     std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
     236                 :             : 
     237                 :       42992 :     skey >> std::as_writable_bytes(std::span{part_pubkey_bytes}) >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
     238                 :       42992 :     agg_pub.Set(agg_pubkey_bytes.begin(), agg_pubkey_bytes.end());
     239         [ +  + ]:       42992 :     part_pub.Set(part_pubkey_bytes.begin(), part_pubkey_bytes.end());
     240                 :             : 
     241         [ +  + ]:       42992 :     if (!skey.empty()) {
     242                 :       12753 :         skey >> leaf_hash;
     243                 :             :     }
     244                 :       42992 : }
     245                 :             : 
     246                 :             : /** A structure for PSBTs which contain per-input information */
     247                 :             : struct PSBTInput
     248                 :             : {
     249                 :             :     CTransactionRef non_witness_utxo;
     250                 :             :     CTxOut witness_utxo;
     251                 :             :     CScript redeem_script;
     252                 :             :     CScript witness_script;
     253                 :             :     CScript final_script_sig;
     254                 :             :     CScriptWitness final_script_witness;
     255                 :             :     std::map<CPubKey, KeyOriginInfo> hd_keypaths;
     256                 :             :     std::map<CKeyID, SigPair> partial_sigs;
     257                 :             :     std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
     258                 :             :     std::map<uint256, std::vector<unsigned char>> sha256_preimages;
     259                 :             :     std::map<uint160, std::vector<unsigned char>> hash160_preimages;
     260                 :             :     std::map<uint256, std::vector<unsigned char>> hash256_preimages;
     261                 :             : 
     262                 :             :     // Taproot fields
     263                 :             :     std::vector<unsigned char> m_tap_key_sig;
     264                 :             :     std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
     265                 :             :     std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
     266                 :             :     std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
     267                 :             :     XOnlyPubKey m_tap_internal_key;
     268                 :             :     uint256 m_tap_merkle_root;
     269                 :             : 
     270                 :             :     // MuSig2 fields
     271                 :             :     std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
     272                 :             :     // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to pubnonce
     273                 :             :     std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, std::vector<uint8_t>>> m_musig2_pubnonces;
     274                 :             :     // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to partial_sig
     275                 :             :     std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, uint256>> m_musig2_partial_sigs;
     276                 :             : 
     277                 :             :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
     278                 :             :     std::set<PSBTProprietary> m_proprietary;
     279                 :             :     std::optional<int> sighash_type;
     280                 :             : 
     281                 :             :     bool IsNull() const;
     282                 :             :     void FillSignatureData(SignatureData& sigdata) const;
     283                 :             :     void FromSignatureData(const SignatureData& sigdata);
     284                 :             :     void Merge(const PSBTInput& input);
     285                 :      171595 :     PSBTInput() = default;
     286                 :             : 
     287                 :             :     template <typename Stream>
     288                 :      109293 :     inline void Serialize(Stream& s) const {
     289                 :             :         // Write the utxo
     290         [ +  + ]:      109293 :         if (non_witness_utxo) {
     291                 :         489 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_NON_WITNESS_UTXO));
     292                 :         489 :             SerializeToVector(s, TX_NO_WITNESS(non_witness_utxo));
     293                 :             :         }
     294         [ +  + ]:      109293 :         if (!witness_utxo.IsNull()) {
     295                 :        6861 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESS_UTXO));
     296                 :        6861 :             SerializeToVector(s, witness_utxo);
     297                 :             :         }
     298                 :             : 
     299   [ +  +  +  +  :      111227 :         if (final_script_sig.empty() && final_script_witness.IsNull()) {
                   +  + ]
     300                 :             :             // Write any partial signatures
     301         [ +  + ]:      106216 :             for (const auto& sig_pair : partial_sigs) {
     302                 :        1062 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
     303                 :        1062 :                 s << sig_pair.second.second;
     304                 :             :             }
     305                 :             : 
     306                 :             :             // Write the sighash type
     307         [ +  + ]:      105154 :             if (sighash_type != std::nullopt) {
     308                 :         553 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_SIGHASH));
     309                 :         553 :                 SerializeToVector(s, *sighash_type);
     310                 :             :             }
     311                 :             : 
     312                 :             :             // Write the redeem script
     313   [ +  +  +  + ]:      106269 :             if (!redeem_script.empty()) {
     314                 :        1992 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_REDEEMSCRIPT));
     315                 :        1992 :                 s << redeem_script;
     316                 :             :             }
     317                 :             : 
     318                 :             :             // Write the witness script
     319   [ +  +  +  + ]:      105902 :             if (!witness_script.empty()) {
     320                 :        3282 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESSSCRIPT));
     321                 :        3282 :                 s << witness_script;
     322                 :             :             }
     323                 :             : 
     324                 :             :             // Write any hd keypaths
     325                 :      105154 :             SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_IN_BIP32_DERIVATION));
     326                 :             : 
     327                 :             :             // Write any ripemd160 preimage
     328         [ +  + ]:      114556 :             for (const auto& [hash, preimage] : ripemd160_preimages) {
     329                 :        9402 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_RIPEMD160), std::span{hash});
     330                 :        9402 :                 s << preimage;
     331                 :             :             }
     332                 :             : 
     333                 :             :             // Write any sha256 preimage
     334         [ +  + ]:      117896 :             for (const auto& [hash, preimage] : sha256_preimages) {
     335                 :       12742 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_SHA256), std::span{hash});
     336                 :       12742 :                 s << preimage;
     337                 :             :             }
     338                 :             : 
     339                 :             :             // Write any hash160 preimage
     340         [ +  + ]:      112799 :             for (const auto& [hash, preimage] : hash160_preimages) {
     341                 :        7645 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH160), std::span{hash});
     342                 :        7645 :                 s << preimage;
     343                 :             :             }
     344                 :             : 
     345                 :             :             // Write any hash256 preimage
     346         [ +  + ]:      112394 :             for (const auto& [hash, preimage] : hash256_preimages) {
     347                 :        7240 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH256), std::span{hash});
     348                 :        7240 :                 s << preimage;
     349                 :             :             }
     350                 :             : 
     351                 :             :             // Write taproot key sig
     352         [ +  + ]:      105154 :             if (!m_tap_key_sig.empty()) {
     353                 :         571 :                 SerializeToVector(s, PSBT_IN_TAP_KEY_SIG);
     354                 :         571 :                 s << m_tap_key_sig;
     355                 :             :             }
     356                 :             : 
     357                 :             :             // Write taproot script sigs
     358         [ +  + ]:      113260 :             for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
     359                 :        8106 :                 const auto& [xonly, leaf_hash] = pubkey_leaf;
     360                 :        8106 :                 SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
     361                 :        8106 :                 s << sig;
     362                 :             :             }
     363                 :             : 
     364                 :             :             // Write taproot leaf scripts
     365         [ +  + ]:      134289 :             for (const auto& [leaf, control_blocks] : m_tap_scripts) {
     366                 :       29135 :                 const auto& [script, leaf_ver] = leaf;
     367   [ -  +  +  + ]:       65220 :                 for (const auto& control_block : control_blocks) {
     368                 :       36085 :                     SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, std::span{control_block});
     369                 :       36085 :                     std::vector<unsigned char> value_v(script.begin(), script.end());
     370   [ +  -  +  - ]:       36085 :                     value_v.push_back((uint8_t)leaf_ver);
     371                 :       36085 :                     s << value_v;
     372                 :             :                 }
     373                 :             :             }
     374                 :             : 
     375                 :             :             // Write taproot bip32 keypaths
     376         [ +  + ]:      111512 :             for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
     377                 :        6358 :                 const auto& [leaf_hashes, origin] = leaf_origin;
     378                 :        6358 :                 SerializeToVector(s, PSBT_IN_TAP_BIP32_DERIVATION, xonly);
     379                 :        6358 :                 std::vector<unsigned char> value;
     380         [ +  - ]:        6358 :                 VectorWriter s_value{value, 0};
     381         [ +  - ]:        6358 :                 s_value << leaf_hashes;
     382   [ +  -  +  - ]:       12716 :                 SerializeKeyOrigin(s_value, origin);
     383                 :        6358 :                 s << value;
     384                 :             :             }
     385                 :             : 
     386                 :             :             // Write taproot internal key
     387         [ +  + ]:      210308 :             if (!m_tap_internal_key.IsNull()) {
     388                 :         696 :                 SerializeToVector(s, PSBT_IN_TAP_INTERNAL_KEY);
     389         [ +  - ]:        1392 :                 s << ToByteVector(m_tap_internal_key);
     390                 :             :             }
     391                 :             : 
     392                 :             :             // Write taproot merkle root
     393         [ +  + ]:      210308 :             if (!m_tap_merkle_root.IsNull()) {
     394                 :        3072 :                 SerializeToVector(s, PSBT_IN_TAP_MERKLE_ROOT);
     395                 :        3072 :                 SerializeToVector(s, m_tap_merkle_root);
     396                 :             :             }
     397                 :             : 
     398                 :             :             // Write MuSig2 Participants
     399         [ +  + ]:      110921 :             for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
     400                 :        5767 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
     401                 :        5767 :                 std::vector<unsigned char> value;
     402         [ +  - ]:        5767 :                 VectorWriter s_value{value, 0};
     403   [ +  -  +  + ]:       27961 :                 for (auto& pk : part_pubs) {
     404         [ +  - ]:       44388 :                     s_value << std::span{pk};
     405                 :             :                 }
     406                 :        5767 :                 s << value;
     407                 :             :             }
     408                 :             : 
     409                 :             :             // Write MuSig2 pubnonces
     410         [ +  + ]:      113838 :             for (const auto& [agg_pubkey_leaf_hash, pubnonces] : m_musig2_pubnonces) {
     411                 :        8684 :                 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
     412         [ +  + ]:       23321 :                 for (const auto& [part_pubkey, pubnonce] : pubnonces) {
     413         [ +  + ]:       29274 :                     if (leaf_hash.IsNull()) {
     414                 :       10084 :                         SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey});
     415                 :             :                     } else {
     416                 :        4553 :                         SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey}, leaf_hash);
     417                 :             :                     }
     418                 :       14637 :                     s << pubnonce;
     419                 :             :                 }
     420                 :             :             }
     421                 :             : 
     422                 :             :             // Write MuSig2 partial signatures
     423         [ +  + ]:      117465 :             for (const auto& [agg_pubkey_leaf_hash, psigs] : m_musig2_partial_sigs) {
     424                 :       12311 :                 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
     425         [ +  + ]:       30397 :                 for (const auto& [pubkey, psig] : psigs) {
     426         [ +  + ]:       36172 :                     if (leaf_hash.IsNull()) {
     427                 :       12230 :                         SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey});
     428                 :             :                     } else {
     429                 :        5856 :                         SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey}, leaf_hash);
     430                 :             :                     }
     431                 :       18086 :                     SerializeToVector(s, psig);
     432                 :             :                 }
     433                 :             :             }
     434                 :             :         }
     435                 :             : 
     436                 :             :         // Write script sig
     437   [ +  +  +  + ]:      111227 :         if (!final_script_sig.empty()) {
     438                 :        3280 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTSIG));
     439                 :        3280 :             s << final_script_sig;
     440                 :             :         }
     441                 :             :         // write script witness
     442         [ +  + ]:      109293 :         if (!final_script_witness.IsNull()) {
     443                 :         865 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTWITNESS));
     444                 :         865 :             SerializeToVector(s, final_script_witness.stack);
     445                 :             :         }
     446                 :             : 
     447                 :             :         // Write proprietary things
     448         [ +  + ]:      122809 :         for (const auto& entry : m_proprietary) {
     449                 :       13516 :             s << entry.key;
     450                 :       13516 :             s << entry.value;
     451                 :             :         }
     452                 :             : 
     453                 :             :         // Write unknown things
     454         [ +  + ]:      225763 :         for (auto& entry : unknown) {
     455                 :      116470 :             s << entry.first;
     456                 :      116470 :             s << entry.second;
     457                 :             :         }
     458                 :             : 
     459                 :      109293 :         s << PSBT_SEPARATOR;
     460                 :      109293 :     }
     461                 :             : 
     462                 :             : 
     463                 :             :     template <typename Stream>
     464                 :      155623 :     inline void Unserialize(Stream& s) {
     465                 :             :         // Used for duplicate key detection
     466                 :      155623 :         std::set<std::vector<unsigned char>> key_lookup;
     467                 :             : 
     468                 :             :         // Read loop
     469                 :      155623 :         bool found_sep = false;
     470   [ -  +  +  + ]:      797989 :         while(!s.empty()) {
     471                 :             :             // Read the key of format "<keylen><keytype><keydata>" after which
     472                 :             :             // "key" will contain "<keytype><keydata>"
     473         [ +  + ]:      642366 :             std::vector<unsigned char> key;
     474                 :      641900 :             s >> key;
     475                 :             : 
     476                 :             :             // the key is empty if that was actually a separator byte
     477                 :             :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
     478         [ +  + ]:      641900 :             if (key.empty()) {
     479                 :      151876 :                 found_sep = true;
     480                 :             :                 break;
     481                 :             :             }
     482                 :             : 
     483                 :             :             // "skey" is used so that "key" is unchanged after reading keytype below
     484                 :      490024 :             SpanReader skey{key};
     485                 :             :             // keytype is of the format compact size uint at the beginning of "key"
     486         [ +  + ]:      490024 :             uint64_t type = ReadCompactSize(skey);
     487                 :             : 
     488                 :             :             // Do stuff based on keytype "type", i.e., key checks, reading values of the
     489                 :             :             // format "<valuelen><valuedata>" from the stream "s", and value checks
     490   [ +  +  +  +  :      490002 :             switch(type) {
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
             +  +  +  +  
                      + ]
     491                 :        1590 :                 case PSBT_IN_NON_WITNESS_UTXO:
     492                 :             :                 {
     493   [ +  -  +  + ]:        1590 :                     if (!key_lookup.emplace(key).second) {
     494         [ +  - ]:          24 :                         throw std::ios_base::failure("Duplicate Key, input non-witness utxo already provided");
     495         [ +  + ]:        1578 :                     } else if (key.size() != 1) {
     496         [ +  - ]:         124 :                         throw std::ios_base::failure("Non-witness utxo key is more than one byte type");
     497                 :             :                     }
     498                 :             :                     // Set the stream to unserialize with witness since this is always a valid network transaction
     499         [ +  + ]:        1516 :                     UnserializeFromVector(s, TX_WITH_WITNESS(non_witness_utxo));
     500                 :             :                     break;
     501                 :             :                 }
     502                 :       17548 :                 case PSBT_IN_WITNESS_UTXO:
     503   [ +  -  +  + ]:       17548 :                     if (!key_lookup.emplace(key).second) {
     504         [ +  - ]:          28 :                         throw std::ios_base::failure("Duplicate Key, input witness utxo already provided");
     505         [ +  + ]:       17534 :                     } else if (key.size() != 1) {
     506         [ +  - ]:          46 :                         throw std::ios_base::failure("Witness utxo key is more than one byte type");
     507                 :             :                     }
     508         [ +  + ]:       17511 :                     UnserializeFromVector(s, witness_utxo);
     509                 :             :                     break;
     510         [ -  + ]:        4296 :                 case PSBT_IN_PARTIAL_SIG:
     511                 :             :                 {
     512                 :             :                     // Make sure that the key is the size of pubkey + 1
     513   [ +  +  +  + ]:        4296 :                     if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
     514         [ +  - ]:          52 :                         throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
     515                 :             :                     }
     516                 :             :                     // Read in the pubkey from key
     517                 :        4270 :                     CPubKey pubkey(key.begin() + 1, key.end());
     518   [ +  -  +  + ]:        4270 :                     if (!pubkey.IsFullyValid()) {
     519         [ +  - ]:         132 :                        throw std::ios_base::failure("Invalid pubkey");
     520                 :             :                     }
     521   [ +  -  +  + ]:        4204 :                     if (partial_sigs.count(pubkey.GetID()) > 0) {
     522         [ +  - ]:          24 :                         throw std::ios_base::failure("Duplicate Key, input partial signature for pubkey already provided");
     523                 :             :                     }
     524                 :             : 
     525                 :             :                     // Read in the signature from value
     526         [ +  + ]:        4192 :                     std::vector<unsigned char> sig;
     527                 :        3911 :                     s >> sig;
     528                 :             : 
     529                 :             :                     // Check that the signature is validly encoded
     530   [ +  +  +  -  :        3911 :                     if (sig.empty() || !CheckSignatureEncoding(sig, SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC, nullptr)) {
                   +  + ]
     531         [ +  - ]:         632 :                         throw std::ios_base::failure("Signature is not a valid encoding");
     532                 :             :                     }
     533                 :             : 
     534                 :             :                     // Add to list
     535   [ +  -  +  - ]:        7190 :                     partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
     536                 :             :                     break;
     537                 :        4192 :                 }
     538                 :        1015 :                 case PSBT_IN_SIGHASH:
     539   [ +  -  +  + ]:        1015 :                     if (!key_lookup.emplace(key).second) {
     540         [ +  - ]:          24 :                         throw std::ios_base::failure("Duplicate Key, input sighash type already provided");
     541         [ +  + ]:        1003 :                     } else if (key.size() != 1) {
     542         [ +  - ]:          54 :                         throw std::ios_base::failure("Sighash type key is more than one byte type");
     543                 :             :                     }
     544                 :             :                     int sighash;
     545         [ +  + ]:         976 :                     UnserializeFromVector(s, sighash);
     546                 :         961 :                     sighash_type = sighash;
     547                 :         961 :                     break;
     548                 :        3503 :                 case PSBT_IN_REDEEMSCRIPT:
     549                 :             :                 {
     550   [ +  -  +  + ]:        3503 :                     if (!key_lookup.emplace(key).second) {
     551         [ +  - ]:          34 :                         throw std::ios_base::failure("Duplicate Key, input redeemScript already provided");
     552         [ +  + ]:        3486 :                     } else if (key.size() != 1) {
     553         [ +  - ]:          52 :                         throw std::ios_base::failure("Input redeemScript key is more than one byte type");
     554                 :             :                     }
     555         [ +  + ]:        3460 :                     s >> redeem_script;
     556                 :             :                     break;
     557                 :             :                 }
     558                 :        5379 :                 case PSBT_IN_WITNESSSCRIPT:
     559                 :             :                 {
     560   [ +  -  +  + ]:        5379 :                     if (!key_lookup.emplace(key).second) {
     561         [ +  - ]:          22 :                         throw std::ios_base::failure("Duplicate Key, input witnessScript already provided");
     562         [ +  + ]:        5368 :                     } else if (key.size() != 1) {
     563         [ +  - ]:          34 :                         throw std::ios_base::failure("Input witnessScript key is more than one byte type");
     564                 :             :                     }
     565         [ +  + ]:        5351 :                     s >> witness_script;
     566                 :             :                     break;
     567                 :             :                 }
     568                 :        5637 :                 case PSBT_IN_BIP32_DERIVATION:
     569                 :             :                 {
     570         [ +  + ]:        5637 :                     DeserializeHDKeypaths(s, key, hd_keypaths);
     571                 :             :                     break;
     572                 :             :                 }
     573                 :        6906 :                 case PSBT_IN_SCRIPTSIG:
     574                 :             :                 {
     575   [ +  -  +  + ]:        6906 :                     if (!key_lookup.emplace(key).second) {
     576         [ +  - ]:          34 :                         throw std::ios_base::failure("Duplicate Key, input final scriptSig already provided");
     577         [ +  + ]:        6889 :                     } else if (key.size() != 1) {
     578         [ +  - ]:          28 :                         throw std::ios_base::failure("Final scriptSig key is more than one byte type");
     579                 :             :                     }
     580         [ +  + ]:      493726 :                     s >> final_script_sig;
     581                 :             :                     break;
     582                 :             :                 }
     583                 :        1893 :                 case PSBT_IN_SCRIPTWITNESS:
     584                 :             :                 {
     585   [ +  -  +  + ]:        1893 :                     if (!key_lookup.emplace(key).second) {
     586         [ +  - ]:          18 :                         throw std::ios_base::failure("Duplicate Key, input final scriptWitness already provided");
     587         [ +  + ]:        1884 :                     } else if (key.size() != 1) {
     588         [ +  - ]:          46 :                         throw std::ios_base::failure("Final scriptWitness key is more than one byte type");
     589                 :             :                     }
     590         [ +  + ]:        1861 :                     UnserializeFromVector(s, final_script_witness.stack);
     591                 :             :                     break;
     592                 :             :                 }
     593         [ -  + ]:       15247 :                 case PSBT_IN_RIPEMD160:
     594                 :             :                 {
     595                 :             :                     // Make sure that the key is the size of a ripemd160 hash + 1
     596         [ +  + ]:       15247 :                     if (key.size() != CRIPEMD160::OUTPUT_SIZE + 1) {
     597         [ +  - ]:          34 :                         throw std::ios_base::failure("Size of key was not the expected size for the type ripemd160 preimage");
     598                 :             :                     }
     599                 :             :                     // Read in the hash from key
     600         [ +  - ]:       15230 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     601                 :       15230 :                     uint160 hash(hash_vec);
     602         [ +  + ]:       15230 :                     if (ripemd160_preimages.count(hash) > 0) {
     603         [ +  - ]:          22 :                         throw std::ios_base::failure("Duplicate Key, input ripemd160 preimage already provided");
     604                 :             :                     }
     605                 :             : 
     606                 :             :                     // Read in the preimage from value
     607         [ +  + ]:       15219 :                     std::vector<unsigned char> preimage;
     608                 :       15175 :                     s >> preimage;
     609                 :             : 
     610                 :             :                     // Add to preimages list
     611         [ +  - ]:       15175 :                     ripemd160_preimages.emplace(hash, std::move(preimage));
     612                 :             :                     break;
     613                 :       15274 :                 }
     614         [ -  + ]:       25967 :                 case PSBT_IN_SHA256:
     615                 :             :                 {
     616                 :             :                     // Make sure that the key is the size of a sha256 hash + 1
     617         [ +  + ]:       25967 :                     if (key.size() != CSHA256::OUTPUT_SIZE + 1) {
     618         [ +  - ]:          30 :                         throw std::ios_base::failure("Size of key was not the expected size for the type sha256 preimage");
     619                 :             :                     }
     620                 :             :                     // Read in the hash from key
     621         [ +  - ]:       25952 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     622                 :       25952 :                     uint256 hash(hash_vec);
     623         [ +  + ]:       25952 :                     if (sha256_preimages.count(hash) > 0) {
     624         [ +  - ]:          24 :                         throw std::ios_base::failure("Duplicate Key, input sha256 preimage already provided");
     625                 :             :                     }
     626                 :             : 
     627                 :             :                     // Read in the preimage from value
     628         [ +  + ]:       25940 :                     std::vector<unsigned char> preimage;
     629                 :       25897 :                     s >> preimage;
     630                 :             : 
     631                 :             :                     // Add to preimages list
     632         [ +  - ]:       25897 :                     sha256_preimages.emplace(hash, std::move(preimage));
     633                 :             :                     break;
     634                 :       25995 :                 }
     635         [ -  + ]:       13862 :                 case PSBT_IN_HASH160:
     636                 :             :                 {
     637                 :             :                     // Make sure that the key is the size of a hash160 hash + 1
     638         [ +  + ]:       13862 :                     if (key.size() != CHash160::OUTPUT_SIZE + 1) {
     639         [ +  - ]:          44 :                         throw std::ios_base::failure("Size of key was not the expected size for the type hash160 preimage");
     640                 :             :                     }
     641                 :             :                     // Read in the hash from key
     642         [ +  - ]:       13840 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     643                 :       13840 :                     uint160 hash(hash_vec);
     644         [ +  + ]:       13840 :                     if (hash160_preimages.count(hash) > 0) {
     645         [ +  - ]:          26 :                         throw std::ios_base::failure("Duplicate Key, input hash160 preimage already provided");
     646                 :             :                     }
     647                 :             : 
     648                 :             :                     // Read in the preimage from value
     649         [ +  + ]:       13827 :                     std::vector<unsigned char> preimage;
     650                 :       13786 :                     s >> preimage;
     651                 :             : 
     652                 :             :                     // Add to preimages list
     653         [ +  - ]:       13786 :                     hash160_preimages.emplace(hash, std::move(preimage));
     654                 :             :                     break;
     655                 :       13881 :                 }
     656         [ -  + ]:       12684 :                 case PSBT_IN_HASH256:
     657                 :             :                 {
     658                 :             :                     // Make sure that the key is the size of a hash256 hash + 1
     659         [ +  + ]:       12684 :                     if (key.size() != CHash256::OUTPUT_SIZE + 1) {
     660         [ +  - ]:          34 :                         throw std::ios_base::failure("Size of key was not the expected size for the type hash256 preimage");
     661                 :             :                     }
     662                 :             :                     // Read in the hash from key
     663         [ +  - ]:       12667 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     664                 :       12667 :                     uint256 hash(hash_vec);
     665         [ +  + ]:       12667 :                     if (hash256_preimages.count(hash) > 0) {
     666         [ +  - ]:          28 :                         throw std::ios_base::failure("Duplicate Key, input hash256 preimage already provided");
     667                 :             :                     }
     668                 :             : 
     669                 :             :                     // Read in the preimage from value
     670         [ +  + ]:       12653 :                     std::vector<unsigned char> preimage;
     671                 :       12613 :                     s >> preimage;
     672                 :             : 
     673                 :             :                     // Add to preimages list
     674         [ +  - ]:       12613 :                     hash256_preimages.emplace(hash, std::move(preimage));
     675                 :             :                     break;
     676                 :       12707 :                 }
     677                 :        1289 :                 case PSBT_IN_TAP_KEY_SIG:
     678                 :             :                 {
     679   [ +  -  +  + ]:        1289 :                     if (!key_lookup.emplace(key).second) {
     680         [ +  - ]:          24 :                         throw std::ios_base::failure("Duplicate Key, input Taproot key signature already provided");
     681         [ +  + ]:        1277 :                     } else if (key.size() != 1) {
     682         [ +  - ]:          28 :                         throw std::ios_base::failure("Input Taproot key signature key is more than one byte type");
     683                 :             :                     }
     684         [ +  + ]:        1263 :                     s >> m_tap_key_sig;
     685   [ -  +  +  + ]:        1240 :                     if (m_tap_key_sig.size() < 64) {
     686         [ +  - ]:          30 :                         throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
     687         [ +  + ]:        1225 :                     } else if (m_tap_key_sig.size() > 65) {
     688         [ +  - ]:          22 :                         throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
     689                 :             :                     }
     690                 :             :                     break;
     691                 :             :                 }
     692                 :       15533 :                 case PSBT_IN_TAP_SCRIPT_SIG:
     693                 :             :                 {
     694   [ +  -  +  + ]:       15533 :                     if (!key_lookup.emplace(key).second) {
     695         [ +  - ]:          26 :                         throw std::ios_base::failure("Duplicate Key, input Taproot script signature already provided");
     696         [ +  + ]:       15520 :                     } else if (key.size() != 65) {
     697         [ +  - ]:          36 :                         throw std::ios_base::failure("Input Taproot script signature key is not 65 bytes");
     698                 :             :                     }
     699                 :       15502 :                     SpanReader s_key{std::span{key}.subspan(1)};
     700                 :       15502 :                     XOnlyPubKey xonly;
     701         [ +  - ]:       15502 :                     uint256 hash;
     702         [ +  - ]:       15502 :                     s_key >> xonly;
     703                 :       15502 :                     s_key >> hash;
     704         [ +  + ]:       15502 :                     std::vector<unsigned char> sig;
     705         [ -  + ]:       15465 :                     s >> sig;
     706         [ +  + ]:       15465 :                     if (sig.size() < 64) {
     707         [ +  - ]:          62 :                         throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
     708         [ +  + ]:       15434 :                     } else if (sig.size() > 65) {
     709         [ +  - ]:          34 :                         throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
     710                 :             :                     }
     711         [ +  - ]:       15417 :                     m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
     712                 :             :                     break;
     713                 :       15502 :                 }
     714                 :       66169 :                 case PSBT_IN_TAP_LEAF_SCRIPT:
     715                 :             :                 {
     716   [ +  -  +  + ]:       66169 :                     if (!key_lookup.emplace(key).second) {
     717         [ +  - ]:          32 :                         throw std::ios_base::failure("Duplicate Key, input Taproot leaf script already provided");
     718         [ +  + ]:       66153 :                     } else if (key.size() < 34) {
     719         [ +  - ]:          72 :                         throw std::ios_base::failure("Taproot leaf script key is not at least 34 bytes");
     720         [ +  + ]:       66117 :                     } else if ((key.size() - 2) % 32 != 0) {
     721         [ +  - ]:          32 :                         throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
     722                 :             :                     }
     723         [ +  + ]:       66101 :                     std::vector<unsigned char> script_v;
     724                 :       66053 :                     s >> script_v;
     725         [ +  + ]:       66053 :                     if (script_v.empty()) {
     726         [ +  - ]:          62 :                         throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
     727                 :             :                     }
     728         [ +  - ]:       66022 :                     uint8_t leaf_ver = script_v.back();
     729                 :       66022 :                     script_v.pop_back();
     730         [ +  - ]:       66022 :                     const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
     731   [ +  -  +  -  :      132044 :                     m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
                   +  - ]
     732                 :             :                     break;
     733                 :       66101 :                 }
     734                 :       10083 :                 case PSBT_IN_TAP_BIP32_DERIVATION:
     735                 :             :                 {
     736   [ +  -  +  + ]:       10083 :                     if (!key_lookup.emplace(key).second) {
     737         [ +  - ]:          28 :                         throw std::ios_base::failure("Duplicate Key, input Taproot BIP32 keypath already provided");
     738         [ +  + ]:       10069 :                     } else if (key.size() != 33) {
     739         [ +  - ]:          34 :                         throw std::ios_base::failure("Input Taproot BIP32 keypath key is not at 33 bytes");
     740                 :             :                     }
     741                 :       10052 :                     SpanReader s_key{std::span{key}.subspan(1)};
     742         [ +  - ]:       10052 :                     XOnlyPubKey xonly;
     743         [ +  + ]:       10052 :                     s_key >> xonly;
     744                 :       10052 :                     std::set<uint256> leaf_hashes;
     745   [ +  +  -  + ]:       10052 :                     uint64_t value_len = ReadCompactSize(s);
     746         [ +  + ]:       10039 :                     size_t before_hashes = s.size();
     747         [ -  + ]:        9947 :                     s >> leaf_hashes;
     748                 :        9947 :                     size_t after_hashes = s.size();
     749                 :        9947 :                     size_t hashes_len = before_hashes - after_hashes;
     750         [ +  + ]:        9947 :                     if (hashes_len > value_len) {
     751         [ +  - ]:          52 :                         throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
     752                 :             :                     }
     753                 :        9921 :                     size_t origin_len = value_len - hashes_len;
     754   [ +  +  +  - ]:       19820 :                     m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
     755                 :             :                     break;
     756                 :       10052 :                 }
     757                 :        1097 :                 case PSBT_IN_TAP_INTERNAL_KEY:
     758                 :             :                 {
     759   [ +  -  +  + ]:        1097 :                     if (!key_lookup.emplace(key).second) {
     760         [ +  - ]:          12 :                         throw std::ios_base::failure("Duplicate Key, input Taproot internal key already provided");
     761         [ +  + ]:        1091 :                     } else if (key.size() != 1) {
     762         [ +  - ]:          30 :                         throw std::ios_base::failure("Input Taproot internal key key is more than one byte type");
     763                 :             :                     }
     764         [ +  + ]:        1076 :                     UnserializeFromVector(s, m_tap_internal_key);
     765                 :             :                     break;
     766                 :             :                 }
     767                 :        3410 :                 case PSBT_IN_TAP_MERKLE_ROOT:
     768                 :             :                 {
     769   [ +  -  +  + ]:        3410 :                     if (!key_lookup.emplace(key).second) {
     770         [ +  - ]:          20 :                         throw std::ios_base::failure("Duplicate Key, input Taproot merkle root already provided");
     771         [ +  + ]:        3400 :                     } else if (key.size() != 1) {
     772         [ +  - ]:          36 :                         throw std::ios_base::failure("Input Taproot merkle root key is more than one byte type");
     773                 :             :                     }
     774         [ +  + ]:        3382 :                     UnserializeFromVector(s, m_tap_merkle_root);
     775                 :             :                     break;
     776                 :             :                 }
     777                 :        8010 :                 case PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS:
     778                 :             :                 {
     779   [ +  -  +  + ]:        8010 :                     if (!key_lookup.emplace(key).second) {
     780         [ +  - ]:          28 :                         throw std::ios_base::failure("Duplicate Key, input participant pubkeys for an aggregate key already provided");
     781         [ +  + ]:        7996 :                     } else if (key.size() != CPubKey::COMPRESSED_SIZE + 1) {
     782         [ +  - ]:          32 :                         throw std::ios_base::failure("Input musig2 participants pubkeys aggregate key is not 34 bytes");
     783                 :             :                     }
     784   [ +  -  +  + ]:       15960 :                     DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
     785                 :             :                     break;
     786                 :             :                 }
     787                 :       18559 :                 case PSBT_IN_MUSIG2_PUB_NONCE:
     788                 :             :                 {
     789   [ +  -  +  + ]:       18559 :                     if (!key_lookup.emplace(key).second) {
     790         [ +  - ]:          18 :                         throw std::ios_base::failure("Duplicate Key, input musig2 pubnonce already provided");
     791   [ +  +  +  + ]:       18550 :                     } else if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
     792         [ +  - ]:          48 :                         throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
     793                 :             :                     }
     794                 :       18526 :                     CPubKey agg_pub, part_pub;
     795                 :       18526 :                     uint256 leaf_hash;
     796         [ +  - ]:       18526 :                     DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
     797                 :             : 
     798         [ +  + ]:       18526 :                     std::vector<uint8_t> pubnonce;
     799         [ -  + ]:       18489 :                     s >> pubnonce;
     800         [ +  + ]:       18489 :                     if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) {
     801         [ +  - ]:          82 :                         throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
     802                 :             :                     }
     803                 :             : 
     804   [ +  -  +  - ]:       18448 :                     m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
     805                 :             :                     break;
     806                 :       18526 :                 }
     807                 :       24515 :                 case PSBT_IN_MUSIG2_PARTIAL_SIG:
     808                 :             :                 {
     809   [ +  -  +  + ]:       24515 :                     if (!key_lookup.emplace(key).second) {
     810         [ +  - ]:          24 :                         throw std::ios_base::failure("Duplicate Key, input musig2 partial sig already provided");
     811   [ +  +  +  + ]:       24503 :                     } else if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
     812         [ +  - ]:          74 :                         throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
     813                 :             :                     }
     814                 :       24466 :                     CPubKey agg_pub, part_pub;
     815                 :       24466 :                     uint256 leaf_hash;
     816         [ +  - ]:       24466 :                     DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
     817                 :             : 
     818                 :       24466 :                     uint256 partial_sig;
     819         [ +  + ]:       24466 :                     UnserializeFromVector(s, partial_sig);
     820                 :             : 
     821   [ +  -  +  - ]:       24424 :                     m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
     822                 :             :                     break;
     823                 :             :                 }
     824         [ +  + ]:       23920 :                 case PSBT_IN_PROPRIETARY:
     825                 :             :                 {
     826         [ +  + ]:       23920 :                     PSBTProprietary this_prop;
     827                 :       23894 :                     skey >> this_prop.identifier;
     828         [ +  + ]:       23894 :                     this_prop.subtype = ReadCompactSize(skey);
     829         [ +  - ]:       23891 :                     this_prop.key = key;
     830                 :             : 
     831         [ +  + ]:       23891 :                     if (m_proprietary.count(this_prop) > 0) {
     832         [ +  - ]:          44 :                         throw std::ios_base::failure("Duplicate Key, proprietary key already found");
     833                 :             :                     }
     834                 :       23827 :                     s >> this_prop.value;
     835         [ +  - ]:       23827 :                     m_proprietary.insert(this_prop);
     836                 :             :                     break;
     837                 :       23920 :                 }
     838                 :             :                 // Unknown stuff
     839                 :      201890 :                 default:
     840         [ +  + ]:      201890 :                     if (unknown.count(key) > 0) {
     841         [ +  - ]:          64 :                         throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
     842                 :             :                     }
     843                 :             :                     // Read in the value
     844         [ +  + ]:      201858 :                     std::vector<unsigned char> val_bytes;
     845                 :      201749 :                     s >> val_bytes;
     846         [ +  - ]:      201749 :                     unknown.emplace(std::move(key), std::move(val_bytes));
     847                 :             :                     break;
     848                 :      201858 :             }
     849                 :             :         }
     850                 :             : 
     851                 :             :         if (!found_sep) {
     852         [ +  - ]:         216 :             throw std::ios_base::failure("Separator is missing at the end of an input map");
     853                 :             :         }
     854                 :      151876 :     }
     855                 :             : 
     856                 :             :     template <typename Stream>
     857                 :             :     PSBTInput(deserialize_type, Stream& s) {
     858                 :             :         Unserialize(s);
     859                 :             :     }
     860                 :             : };
     861                 :             : 
     862                 :             : /** A structure for PSBTs which contains per output information */
     863                 :             : struct PSBTOutput
     864                 :             : {
     865                 :             :     CScript redeem_script;
     866                 :             :     CScript witness_script;
     867                 :             :     std::map<CPubKey, KeyOriginInfo> hd_keypaths;
     868                 :             :     XOnlyPubKey m_tap_internal_key;
     869                 :             :     std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
     870                 :             :     std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
     871                 :             :     std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
     872                 :             :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
     873                 :             :     std::set<PSBTProprietary> m_proprietary;
     874                 :             : 
     875                 :             :     bool IsNull() const;
     876                 :             :     void FillSignatureData(SignatureData& sigdata) const;
     877                 :             :     void FromSignatureData(const SignatureData& sigdata);
     878                 :             :     void Merge(const PSBTOutput& output);
     879                 :      235900 :     PSBTOutput() = default;
     880                 :             : 
     881                 :             :     template <typename Stream>
     882                 :      147281 :     inline void Serialize(Stream& s) const {
     883                 :             :         // Write the redeem script
     884   [ +  +  +  + ]:      149453 :         if (!redeem_script.empty()) {
     885                 :        3515 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_REDEEMSCRIPT));
     886                 :        3515 :             s << redeem_script;
     887                 :             :         }
     888                 :             : 
     889                 :             :         // Write the witness script
     890   [ +  +  +  + ]:      148457 :         if (!witness_script.empty()) {
     891                 :        2968 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_WITNESSSCRIPT));
     892                 :        2968 :             s << witness_script;
     893                 :             :         }
     894                 :             : 
     895                 :             :         // Write any hd keypaths
     896                 :      147281 :         SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_OUT_BIP32_DERIVATION));
     897                 :             : 
     898                 :             :         // Write proprietary things
     899         [ +  + ]:      159241 :         for (const auto& entry : m_proprietary) {
     900                 :       11960 :             s << entry.key;
     901                 :       11960 :             s << entry.value;
     902                 :             :         }
     903                 :             : 
     904                 :             :         // Write taproot internal key
     905         [ +  + ]:      294562 :         if (!m_tap_internal_key.IsNull()) {
     906                 :        4993 :             SerializeToVector(s, PSBT_OUT_TAP_INTERNAL_KEY);
     907         [ +  - ]:        9986 :             s << ToByteVector(m_tap_internal_key);
     908                 :             :         }
     909                 :             : 
     910                 :             :         // Write taproot tree
     911         [ +  + ]:      147281 :         if (!m_tap_tree.empty()) {
     912                 :        1573 :             SerializeToVector(s, PSBT_OUT_TAP_TREE);
     913                 :        1573 :             std::vector<unsigned char> value;
     914         [ +  - ]:        1573 :             VectorWriter s_value{value, 0};
     915   [ +  -  +  + ]:        9791 :             for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
     916         [ +  - ]:        8218 :                 s_value << depth;
     917         [ +  - ]:        8218 :                 s_value << leaf_ver;
     918                 :        8218 :                 s_value << script;
     919                 :             :             }
     920                 :        1573 :             s << value;
     921                 :        1573 :         }
     922                 :             : 
     923                 :             :         // Write taproot bip32 keypaths
     924         [ +  + ]:      157042 :         for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
     925                 :        9761 :             const auto& [leaf_hashes, origin] = leaf;
     926                 :        9761 :             SerializeToVector(s, PSBT_OUT_TAP_BIP32_DERIVATION, xonly);
     927                 :        9761 :             std::vector<unsigned char> value;
     928         [ +  - ]:        9761 :             VectorWriter s_value{value, 0};
     929         [ +  - ]:        9761 :             s_value << leaf_hashes;
     930   [ +  -  +  - ]:       19522 :             SerializeKeyOrigin(s_value, origin);
     931                 :        9761 :             s << value;
     932                 :             :         }
     933                 :             : 
     934                 :             :         // Write MuSig2 Participants
     935         [ +  + ]:      156063 :         for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
     936                 :        8782 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
     937                 :        8782 :             std::vector<unsigned char> value;
     938         [ +  - ]:        8782 :             VectorWriter s_value{value, 0};
     939   [ +  -  +  + ]:       28521 :             for (auto& pk : part_pubs) {
     940         [ +  - ]:       39478 :                 s_value << std::span{pk};
     941                 :             :             }
     942                 :        8782 :             s << value;
     943                 :             :         }
     944                 :             : 
     945                 :             :         // Write unknown things
     946         [ +  + ]:      227744 :         for (auto& entry : unknown) {
     947                 :       80463 :             s << entry.first;
     948                 :       80463 :             s << entry.second;
     949                 :             :         }
     950                 :             : 
     951                 :      147281 :         s << PSBT_SEPARATOR;
     952                 :      147281 :     }
     953                 :             : 
     954                 :             : 
     955                 :             :     template <typename Stream>
     956                 :      206563 :     inline void Unserialize(Stream& s) {
     957                 :             :         // Used for duplicate key detection
     958                 :      206563 :         std::set<std::vector<unsigned char>> key_lookup;
     959                 :             : 
     960                 :             :         // Read loop
     961                 :      206563 :         bool found_sep = false;
     962   [ -  +  +  + ]:      734867 :         while(!s.empty()) {
     963                 :             :             // Read the key of format "<keylen><keytype><keydata>" after which
     964                 :             :             // "key" will contain "<keytype><keydata>"
     965         [ +  + ]:      528304 :             std::vector<unsigned char> key;
     966                 :      527906 :             s >> key;
     967                 :             : 
     968                 :             :             // the key is empty if that was actually a separator byte
     969                 :             :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
     970         [ +  + ]:      527906 :             if (key.empty()) {
     971                 :      204341 :                 found_sep = true;
     972                 :             :                 break;
     973                 :             :             }
     974                 :             : 
     975                 :             :             // "skey" is used so that "key" is unchanged after reading keytype below
     976                 :      323565 :             SpanReader skey{key};
     977                 :             :             // keytype is of the format compact size uint at the beginning of "key"
     978         [ +  + ]:      323565 :             uint64_t type = ReadCompactSize(skey);
     979                 :             : 
     980                 :             :             // Do stuff based on keytype "type", i.e., key checks, reading values of the
     981                 :             :             // format "<valuelen><valuedata>" from the stream "s", and value checks
     982   [ +  +  +  +  :      323548 :             switch(type) {
             +  +  +  +  
                      + ]
     983                 :        8279 :                 case PSBT_OUT_REDEEMSCRIPT:
     984                 :             :                 {
     985   [ +  -  +  + ]:        8279 :                     if (!key_lookup.emplace(key).second) {
     986         [ +  - ]:          40 :                         throw std::ios_base::failure("Duplicate Key, output redeemScript already provided");
     987         [ +  + ]:        8259 :                     } else if (key.size() != 1) {
     988         [ +  - ]:         240 :                         throw std::ios_base::failure("Output redeemScript key is more than one byte type");
     989                 :             :                     }
     990         [ +  + ]:        8139 :                     s >> redeem_script;
     991                 :             :                     break;
     992                 :             :                 }
     993                 :        6634 :                 case PSBT_OUT_WITNESSSCRIPT:
     994                 :             :                 {
     995   [ +  -  +  + ]:        6634 :                     if (!key_lookup.emplace(key).second) {
     996         [ +  - ]:          32 :                         throw std::ios_base::failure("Duplicate Key, output witnessScript already provided");
     997         [ +  + ]:        6618 :                     } else if (key.size() != 1) {
     998         [ +  - ]:          48 :                         throw std::ios_base::failure("Output witnessScript key is more than one byte type");
     999                 :             :                     }
    1000         [ +  + ]:      328401 :                     s >> witness_script;
    1001                 :             :                     break;
    1002                 :             :                 }
    1003                 :       41876 :                 case PSBT_OUT_BIP32_DERIVATION:
    1004                 :             :                 {
    1005         [ +  + ]:       41876 :                     DeserializeHDKeypaths(s, key, hd_keypaths);
    1006                 :             :                     break;
    1007                 :             :                 }
    1008                 :        5942 :                 case PSBT_OUT_TAP_INTERNAL_KEY:
    1009                 :             :                 {
    1010   [ +  -  +  + ]:        5942 :                     if (!key_lookup.emplace(key).second) {
    1011         [ +  - ]:          26 :                         throw std::ios_base::failure("Duplicate Key, output Taproot internal key already provided");
    1012         [ +  + ]:        5929 :                     } else if (key.size() != 1) {
    1013         [ +  - ]:          36 :                         throw std::ios_base::failure("Output Taproot internal key key is more than one byte type");
    1014                 :             :                     }
    1015         [ +  + ]:        5911 :                     UnserializeFromVector(s, m_tap_internal_key);
    1016                 :             :                     break;
    1017                 :             :                 }
    1018                 :        4329 :                 case PSBT_OUT_TAP_TREE:
    1019                 :             :                 {
    1020   [ +  -  +  + ]:        4329 :                     if (!key_lookup.emplace(key).second) {
    1021         [ +  - ]:          24 :                         throw std::ios_base::failure("Duplicate Key, output Taproot tree already provided");
    1022         [ +  + ]:        4317 :                     } else if (key.size() != 1) {
    1023         [ +  - ]:          44 :                         throw std::ios_base::failure("Output Taproot tree key is more than one byte type");
    1024                 :             :                     }
    1025         [ +  + ]:        4295 :                     std::vector<unsigned char> tree_v;
    1026         [ -  + ]:        4262 :                     s >> tree_v;
    1027         [ +  + ]:        4262 :                     SpanReader s_tree{tree_v};
    1028         [ +  + ]:        4262 :                     if (s_tree.empty()) {
    1029         [ +  - ]:          30 :                         throw std::ios_base::failure("Output Taproot tree must not be empty");
    1030                 :             :                     }
    1031                 :        4247 :                     TaprootBuilder builder;
    1032         [ +  + ]:      154194 :                     while (!s_tree.empty()) {
    1033                 :             :                         uint8_t depth;
    1034                 :             :                         uint8_t leaf_ver;
    1035         [ +  - ]:      149947 :                         std::vector<unsigned char> script;
    1036         [ +  + ]:      149947 :                         s_tree >> depth;
    1037         [ +  + ]:      149891 :                         s_tree >> leaf_ver;
    1038                 :      149627 :                         s_tree >> script;
    1039         [ +  + ]:      149627 :                         if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    1040         [ +  - ]:          90 :                             throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
    1041                 :             :                         }
    1042         [ +  + ]:      149582 :                         if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
    1043         [ +  - ]:         142 :                             throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
    1044                 :             :                         }
    1045         [ +  - ]:      149511 :                         m_tap_tree.emplace_back(depth, leaf_ver, script);
    1046   [ -  +  +  - ]:      149511 :                         builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
    1047                 :             :                     }
    1048         [ +  + ]:        3811 :                     if (!builder.IsComplete()) {
    1049         [ +  - ]:         194 :                         throw std::ios_base::failure("Output Taproot tree is malformed");
    1050                 :             :                     }
    1051                 :             :                     break;
    1052                 :        4828 :                 }
    1053                 :       21127 :                 case PSBT_OUT_TAP_BIP32_DERIVATION:
    1054                 :             :                 {
    1055   [ +  -  +  + ]:       21127 :                     if (!key_lookup.emplace(key).second) {
    1056         [ +  - ]:          34 :                         throw std::ios_base::failure("Duplicate Key, output Taproot BIP32 keypath already provided");
    1057         [ +  + ]:       21110 :                     } else if (key.size() != 33) {
    1058         [ +  - ]:          56 :                         throw std::ios_base::failure("Output Taproot BIP32 keypath key is not at 33 bytes");
    1059                 :             :                     }
    1060         [ +  + ]:       21082 :                     XOnlyPubKey xonly(uint256(std::span<uint8_t>(key).last(32)));
    1061                 :       21082 :                     std::set<uint256> leaf_hashes;
    1062   [ +  +  -  + ]:       21082 :                     uint64_t value_len = ReadCompactSize(s);
    1063         [ +  + ]:       21067 :                     size_t before_hashes = s.size();
    1064         [ -  + ]:       20953 :                     s >> leaf_hashes;
    1065                 :       20953 :                     size_t after_hashes = s.size();
    1066                 :       20953 :                     size_t hashes_len = before_hashes - after_hashes;
    1067         [ +  + ]:       20953 :                     if (hashes_len > value_len) {
    1068         [ +  - ]:          56 :                         throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
    1069                 :             :                     }
    1070                 :       20925 :                     size_t origin_len = value_len - hashes_len;
    1071   [ +  +  +  - ]:       41822 :                     m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
    1072                 :             :                     break;
    1073                 :       21082 :                 }
    1074                 :       23865 :                 case PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS:
    1075                 :             :                 {
    1076   [ +  -  +  + ]:       23865 :                     if (!key_lookup.emplace(key).second) {
    1077         [ +  - ]:          32 :                         throw std::ios_base::failure("Duplicate Key, output participant pubkeys for an aggregate key already provided");
    1078         [ +  + ]:       23849 :                     } else if (key.size() != CPubKey::COMPRESSED_SIZE + 1) {
    1079         [ +  - ]:          56 :                         throw std::ios_base::failure("Output musig2 participants pubkeys aggregate key is not 34 bytes");
    1080                 :             :                     }
    1081   [ +  -  +  + ]:       47642 :                     DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Output"});
    1082                 :             :                     break;
    1083                 :             :                 }
    1084         [ +  + ]:       34651 :                 case PSBT_OUT_PROPRIETARY:
    1085                 :             :                 {
    1086         [ +  + ]:       34651 :                     PSBTProprietary this_prop;
    1087                 :       34621 :                     skey >> this_prop.identifier;
    1088         [ +  + ]:       34621 :                     this_prop.subtype = ReadCompactSize(skey);
    1089         [ +  - ]:       34617 :                     this_prop.key = key;
    1090                 :             : 
    1091         [ +  + ]:       34617 :                     if (m_proprietary.count(this_prop) > 0) {
    1092         [ +  - ]:          46 :                         throw std::ios_base::failure("Duplicate Key, proprietary key already found");
    1093                 :             :                     }
    1094                 :       34559 :                     s >> this_prop.value;
    1095         [ +  - ]:       34559 :                     m_proprietary.insert(this_prop);
    1096                 :             :                     break;
    1097                 :       34651 :                 }
    1098                 :             :                 // Unknown stuff
    1099                 :      176845 :                 default: {
    1100         [ +  + ]:      176845 :                     if (unknown.count(key) > 0) {
    1101         [ +  - ]:          66 :                         throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
    1102                 :             :                     }
    1103                 :             :                     // Read in the value
    1104         [ +  + ]:      176812 :                     std::vector<unsigned char> val_bytes;
    1105                 :      176664 :                     s >> val_bytes;
    1106         [ +  - ]:      176664 :                     unknown.emplace(std::move(key), std::move(val_bytes));
    1107                 :             :                     break;
    1108                 :      176812 :                 }
    1109                 :             :             }
    1110                 :             :         }
    1111                 :             : 
    1112                 :             :         if (!found_sep) {
    1113         [ +  - ]:         132 :             throw std::ios_base::failure("Separator is missing at the end of an output map");
    1114                 :             :         }
    1115                 :      204341 :     }
    1116                 :             : 
    1117                 :             :     template <typename Stream>
    1118                 :             :     PSBTOutput(deserialize_type, Stream& s) {
    1119                 :             :         Unserialize(s);
    1120                 :             :     }
    1121                 :             : };
    1122                 :             : 
    1123                 :             : /** A version of CTransaction with the PSBT format*/
    1124                 :             : struct PartiallySignedTransaction
    1125                 :             : {
    1126                 :             :     std::optional<CMutableTransaction> tx;
    1127                 :             :     // We use a vector of CExtPubKey in the event that there happens to be the same KeyOriginInfos for different CExtPubKeys
    1128                 :             :     // Note that this map swaps the key and values from the serialization
    1129                 :             :     std::map<KeyOriginInfo, std::set<CExtPubKey>> m_xpubs;
    1130                 :             :     std::vector<PSBTInput> inputs;
    1131                 :             :     std::vector<PSBTOutput> outputs;
    1132                 :             :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
    1133                 :             :     std::optional<uint32_t> m_version;
    1134                 :             :     std::set<PSBTProprietary> m_proprietary;
    1135                 :             : 
    1136                 :             :     bool IsNull() const;
    1137                 :             :     uint32_t GetVersion() const;
    1138                 :             : 
    1139                 :             :     /** Merge psbt into this. The two psbts must have the same underlying CTransaction (i.e. the
    1140                 :             :       * same actual Bitcoin transaction.) Returns true if the merge succeeded, false otherwise. */
    1141                 :             :     [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
    1142                 :             :     bool AddInput(const CTxIn& txin, PSBTInput& psbtin);
    1143                 :             :     bool AddOutput(const CTxOut& txout, const PSBTOutput& psbtout);
    1144                 :      104983 :     PartiallySignedTransaction() = default;
    1145                 :             :     explicit PartiallySignedTransaction(const CMutableTransaction& tx);
    1146                 :             :     /**
    1147                 :             :      * Finds the UTXO for a given input index
    1148                 :             :      *
    1149                 :             :      * @param[out] utxo The UTXO of the input if found
    1150                 :             :      * @param[in] input_index Index of the input to retrieve the UTXO of
    1151                 :             :      * @return Whether the UTXO for the specified input was found
    1152                 :             :      */
    1153                 :             :     bool GetInputUTXO(CTxOut& utxo, int input_index) const;
    1154                 :             : 
    1155                 :             :     template <typename Stream>
    1156                 :       62199 :     inline void Serialize(Stream& s) const {
    1157                 :             : 
    1158                 :             :         // magic bytes
    1159                 :       62199 :         s << PSBT_MAGIC_BYTES;
    1160                 :             : 
    1161                 :             :         // unsigned tx flag
    1162                 :       62199 :         SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_UNSIGNED_TX));
    1163                 :             : 
    1164                 :             :         // Write serialized tx to a stream
    1165                 :       62199 :         SerializeToVector(s, TX_NO_WITNESS(*tx));
    1166                 :             : 
    1167                 :             :         // Write xpubs
    1168         [ +  + ]:       72867 :         for (const auto& xpub_pair : m_xpubs) {
    1169         [ +  + ]:       23546 :             for (const auto& xpub : xpub_pair.second) {
    1170                 :             :                 unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
    1171                 :       12878 :                 xpub.EncodeWithVersion(ser_xpub);
    1172                 :             :                 // Note that the serialization swaps the key and value
    1173                 :             :                 // The xpub is the key (for uniqueness) while the path is the value
    1174                 :       12878 :                 SerializeToVector(s, PSBT_GLOBAL_XPUB, ser_xpub);
    1175         [ +  - ]:       25756 :                 SerializeHDKeypath(s, xpub_pair.first);
    1176                 :             :             }
    1177                 :             :         }
    1178                 :             : 
    1179                 :             :         // PSBT version
    1180         [ -  + ]:       62199 :         if (GetVersion() > 0) {
    1181                 :           0 :             SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_VERSION));
    1182                 :           0 :             SerializeToVector(s, *m_version);
    1183                 :             :         }
    1184                 :             : 
    1185                 :             :         // Write proprietary things
    1186         [ +  + ]:       67389 :         for (const auto& entry : m_proprietary) {
    1187                 :        5190 :             s << entry.key;
    1188                 :        5190 :             s << entry.value;
    1189                 :             :         }
    1190                 :             : 
    1191                 :             :         // Write the unknown things
    1192         [ +  + ]:      120376 :         for (auto& entry : unknown) {
    1193                 :       58177 :             s << entry.first;
    1194                 :       58177 :             s << entry.second;
    1195                 :             :         }
    1196                 :             : 
    1197                 :             :         // Separator
    1198                 :       62199 :         s << PSBT_SEPARATOR;
    1199                 :             : 
    1200                 :             :         // Write inputs
    1201         [ +  + ]:      170846 :         for (const PSBTInput& input : inputs) {
    1202                 :      108647 :             s << input;
    1203                 :             :         }
    1204                 :             :         // Write outputs
    1205         [ +  + ]:      209241 :         for (const PSBTOutput& output : outputs) {
    1206                 :      147042 :             s << output;
    1207                 :             :         }
    1208                 :       62199 :     }
    1209                 :             : 
    1210                 :             : 
    1211                 :             :     template <typename Stream>
    1212                 :      103781 :     inline void Unserialize(Stream& s) {
    1213                 :             :         // Read the magic bytes
    1214                 :             :         uint8_t magic[5];
    1215                 :      100816 :         s >> magic;
    1216         [ +  + ]:      100816 :         if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
    1217         [ +  - ]:        1168 :             throw std::ios_base::failure("Invalid PSBT magic bytes");
    1218                 :             :         }
    1219                 :             : 
    1220                 :             :         // Used for duplicate key detection
    1221                 :      100232 :         std::set<std::vector<unsigned char>> key_lookup;
    1222                 :             : 
    1223                 :             :         // Track the global xpubs we have already seen. Just for sanity checking
    1224                 :      100232 :         std::set<CExtPubKey> global_xpubs;
    1225                 :             : 
    1226                 :             :         // Read global data
    1227                 :      100232 :         bool found_sep = false;
    1228   [ -  +  +  + ]:      339655 :         while(!s.empty()) {
    1229                 :             :             // Read the key of format "<keylen><keytype><keydata>" after which
    1230                 :             :             // "key" will contain "<keytype><keydata>"
    1231         [ +  + ]:      338035 :             std::vector<unsigned char> key;
    1232                 :      337835 :             s >> key;
    1233                 :             : 
    1234                 :             :             // the key is empty if that was actually a separator byte
    1235                 :             :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
    1236         [ +  + ]:      337835 :             if (key.empty()) {
    1237                 :       98612 :                 found_sep = true;
    1238                 :             :                 break;
    1239                 :             :             }
    1240                 :             : 
    1241                 :             :             // "skey" is used so that "key" is unchanged after reading keytype below
    1242                 :      239223 :             SpanReader skey{key};
    1243                 :             :             // keytype is of the format compact size uint at the beginning of "key"
    1244         [ +  + ]:      239223 :             uint64_t type = ReadCompactSize(skey);
    1245                 :             : 
    1246                 :             :             // Do stuff based on keytype "type", i.e., key checks, reading values of the
    1247                 :             :             // format "<valuelen><valuedata>" from the stream "s", and value checks
    1248   [ +  +  +  +  :      239197 :             switch(type) {
                      + ]
    1249                 :       99569 :                 case PSBT_GLOBAL_UNSIGNED_TX:
    1250                 :             :                 {
    1251   [ +  -  +  + ]:       99569 :                     if (!key_lookup.emplace(key).second) {
    1252         [ +  - ]:          34 :                         throw std::ios_base::failure("Duplicate Key, unsigned tx already provided");
    1253         [ +  + ]:       99552 :                     } else if (key.size() != 1) {
    1254         [ +  - ]:          84 :                         throw std::ios_base::failure("Global unsigned tx key is more than one byte type");
    1255                 :             :                     }
    1256         [ +  - ]:       99510 :                     CMutableTransaction mtx;
    1257                 :             :                     // Set the stream to serialize with non-witness since this should always be non-witness
    1258         [ +  + ]:       99510 :                     UnserializeFromVector(s, TX_NO_WITNESS(mtx));
    1259                 :       98762 :                     tx = std::move(mtx);
    1260                 :             :                     // Make sure that all scriptSigs and scriptWitnesses are empty
    1261         [ +  + ]:      254603 :                     for (const CTxIn& txin : tx->vin) {
    1262   [ +  +  +  +  :      155887 :                         if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
                   -  + ]
    1263         [ +  - ]:          56 :                             throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
    1264                 :             :                         }
    1265                 :             :                     }
    1266                 :             :                     break;
    1267                 :       99510 :                 }
    1268         [ -  + ]:       29449 :                 case PSBT_GLOBAL_XPUB:
    1269                 :             :                 {
    1270         [ +  + ]:       29449 :                     if (key.size() != BIP32_EXTKEY_WITH_VERSION_SIZE + 1) {
    1271         [ +  - ]:          68 :                         throw std::ios_base::failure("Size of key was not the expected size for the type global xpub");
    1272                 :             :                     }
    1273                 :             :                     // Read in the xpub from key
    1274                 :       29415 :                     CExtPubKey xpub;
    1275         [ +  - ]:       29415 :                     xpub.DecodeWithVersion(&key.data()[1]);
    1276   [ +  -  +  + ]:       29415 :                     if (!xpub.pubkey.IsFullyValid()) {
    1277         [ +  - ]:         218 :                        throw std::ios_base::failure("Invalid pubkey");
    1278                 :             :                     }
    1279         [ +  + ]:       29306 :                     if (global_xpubs.count(xpub) > 0) {
    1280         [ +  - ]:          36 :                        throw std::ios_base::failure("Duplicate key, global xpub already provided");
    1281                 :             :                     }
    1282         [ +  - ]:       29288 :                     global_xpubs.insert(xpub);
    1283                 :             :                     // Read in the keypath from stream
    1284                 :       29288 :                     KeyOriginInfo keypath;
    1285         [ +  + ]:       29288 :                     DeserializeHDKeypath(s, keypath);
    1286                 :             : 
    1287                 :             :                     // Note that we store these swapped to make searches faster.
    1288                 :             :                     // Serialization uses xpub -> keypath to enqure key uniqueness
    1289         [ +  + ]:       29229 :                     if (m_xpubs.count(keypath) == 0) {
    1290                 :             :                         // Make a new set to put the xpub in
    1291   [ +  -  +  - ]:       53103 :                         m_xpubs[keypath] = {xpub};
    1292                 :             :                     } else {
    1293                 :             :                         // Insert xpub into existing set
    1294   [ +  -  +  - ]:        5355 :                         m_xpubs[keypath].insert(xpub);
    1295                 :             :                     }
    1296                 :             :                     break;
    1297                 :       29288 :                 }
    1298                 :         229 :                 case PSBT_GLOBAL_VERSION:
    1299                 :             :                 {
    1300         [ +  + ]:         229 :                     if (m_version) {
    1301         [ +  - ]:          20 :                         throw std::ios_base::failure("Duplicate Key, version already provided");
    1302         [ +  + ]:         219 :                     } else if (key.size() != 1) {
    1303         [ +  - ]:          20 :                         throw std::ios_base::failure("Global version key is more than one byte type");
    1304                 :             :                     }
    1305                 :             :                     uint32_t v;
    1306         [ +  + ]:         209 :                     UnserializeFromVector(s, v);
    1307                 :         195 :                     m_version = v;
    1308         [ +  + ]:         195 :                     if (*m_version > PSBT_HIGHEST_VERSION) {
    1309         [ +  - ]:          28 :                         throw std::ios_base::failure("Unsupported version number");
    1310                 :             :                     }
    1311                 :             :                     break;
    1312                 :             :                 }
    1313         [ +  + ]:       11500 :                 case PSBT_GLOBAL_PROPRIETARY:
    1314                 :             :                 {
    1315         [ +  + ]:       11500 :                     PSBTProprietary this_prop;
    1316                 :       11470 :                     skey >> this_prop.identifier;
    1317         [ +  + ]:       11470 :                     this_prop.subtype = ReadCompactSize(skey);
    1318         [ +  - ]:       11467 :                     this_prop.key = key;
    1319                 :             : 
    1320         [ +  + ]:       11467 :                     if (m_proprietary.count(this_prop) > 0) {
    1321         [ +  - ]:          44 :                         throw std::ios_base::failure("Duplicate Key, proprietary key already found");
    1322                 :             :                     }
    1323                 :       11408 :                     s >> this_prop.value;
    1324         [ +  - ]:       11408 :                     m_proprietary.insert(this_prop);
    1325                 :             :                     break;
    1326                 :       11500 :                 }
    1327                 :             :                 // Unknown stuff
    1328                 :       98450 :                 default: {
    1329         [ +  + ]:       98450 :                     if (unknown.count(key) > 0) {
    1330         [ +  - ]:          32 :                         throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
    1331                 :             :                     }
    1332                 :             :                     // Read in the value
    1333         [ +  + ]:       98434 :                     std::vector<unsigned char> val_bytes;
    1334                 :       98311 :                     s >> val_bytes;
    1335         [ +  - ]:       98311 :                     unknown.emplace(std::move(key), std::move(val_bytes));
    1336                 :       98434 :                 }
    1337                 :             :             }
    1338                 :             :         }
    1339                 :             : 
    1340                 :             :         if (!found_sep) {
    1341         [ +  - ]:         120 :             throw std::ios_base::failure("Separator is missing at the end of the global map");
    1342                 :             :         }
    1343                 :             : 
    1344                 :             :         // Make sure that we got an unsigned tx
    1345         [ +  + ]:       98612 :         if (!tx) {
    1346         [ +  - ]:         228 :             throw std::ios_base::failure("No unsigned transaction was provided");
    1347                 :             :         }
    1348                 :             : 
    1349                 :             :         // Read input data
    1350                 :             :         unsigned int i = 0;
    1351   [ -  +  +  +  :      252751 :         while (!s.empty() && i < tx->vin.size()) {
             -  +  +  + ]
    1352         [ +  + ]:      154253 :             PSBTInput input;
    1353                 :      151230 :             s >> input;
    1354         [ +  - ]:      151230 :             inputs.push_back(input);
    1355                 :             : 
    1356                 :             :             // Make sure the non-witness utxo matches the outpoint
    1357         [ +  + ]:      151230 :             if (input.non_witness_utxo) {
    1358         [ +  + ]:         890 :                 if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
    1359         [ +  - ]:         156 :                     throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
    1360                 :             :                 }
    1361   [ -  +  +  + ]:         812 :                 if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
    1362         [ +  - ]:          22 :                     throw std::ios_base::failure("Input specifies output index that does not exist");
    1363                 :             :                 }
    1364                 :             :             }
    1365                 :      151141 :             ++i;
    1366                 :             :         }
    1367                 :             :         // Make sure that the number of inputs matches the number of inputs in the transaction
    1368   [ -  +  -  +  :       95386 :         if (inputs.size() != tx->vin.size()) {
                   +  + ]
    1369         [ +  - ]:          98 :             throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
    1370                 :             :         }
    1371                 :             : 
    1372                 :             :         // Read output data
    1373                 :             :         i = 0;
    1374   [ -  +  +  +  :      301348 :         while (!s.empty() && i < tx->vout.size()) {
             -  +  +  + ]
    1375         [ +  + ]:      206011 :             PSBTOutput output;
    1376                 :      204102 :             s >> output;
    1377         [ +  - ]:      204102 :             outputs.push_back(output);
    1378                 :      204102 :             ++i;
    1379                 :             :         }
    1380                 :             :         // Make sure that the number of outputs matches the number of outputs in the transaction
    1381   [ -  +  -  +  :       93428 :         if (outputs.size() != tx->vout.size()) {
                   +  + ]
    1382         [ +  - ]:         182 :             throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
    1383                 :             :         }
    1384                 :      100232 :     }
    1385                 :             : 
    1386                 :             :     template <typename Stream>
    1387                 :             :     PartiallySignedTransaction(deserialize_type, Stream& s) {
    1388                 :             :         Unserialize(s);
    1389                 :             :     }
    1390                 :             : };
    1391                 :             : 
    1392                 :             : enum class PSBTRole {
    1393                 :             :     CREATOR,
    1394                 :             :     UPDATER,
    1395                 :             :     SIGNER,
    1396                 :             :     FINALIZER,
    1397                 :             :     EXTRACTOR
    1398                 :             : };
    1399                 :             : 
    1400                 :             : std::string PSBTRoleName(PSBTRole role);
    1401                 :             : 
    1402                 :             : /** Compute a PrecomputedTransactionData object from a psbt. */
    1403                 :             : PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt);
    1404                 :             : 
    1405                 :             : /** Checks whether a PSBTInput is already signed by checking for non-null finalized fields. */
    1406                 :             : bool PSBTInputSigned(const PSBTInput& input);
    1407                 :             : 
    1408                 :             : /** Checks whether a PSBTInput is already signed by doing script verification using final fields. */
    1409                 :             : bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
    1410                 :             : 
    1411                 :             : /** Signs a PSBTInput, verifying that all provided data matches what is being signed.
    1412                 :             :  *
    1413                 :             :  * txdata should be the output of PrecomputePSBTData (which can be shared across
    1414                 :             :  * multiple SignPSBTInput calls). If it is nullptr, a dummy signature will be created.
    1415                 :             :  **/
    1416                 :             : [[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);
    1417                 :             : 
    1418                 :             : /**  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. */
    1419                 :             : void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx);
    1420                 :             : 
    1421                 :             : /** Counts the unsigned inputs of a PSBT. */
    1422                 :             : size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt);
    1423                 :             : 
    1424                 :             : /** Updates a PSBTOutput with information from provider.
    1425                 :             :  *
    1426                 :             :  * This fills in the redeem_script, witness_script, and hd_keypaths where possible.
    1427                 :             :  */
    1428                 :             : void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index);
    1429                 :             : 
    1430                 :             : /**
    1431                 :             :  * Finalizes a PSBT if possible, combining partial signatures.
    1432                 :             :  *
    1433                 :             :  * @param[in,out] psbtx PartiallySignedTransaction to finalize
    1434                 :             :  * return True if the PSBT is now complete, false otherwise
    1435                 :             :  */
    1436                 :             : bool FinalizePSBT(PartiallySignedTransaction& psbtx);
    1437                 :             : 
    1438                 :             : /**
    1439                 :             :  * Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
    1440                 :             :  *
    1441                 :             :  * @param[in]  psbtx PartiallySignedTransaction
    1442                 :             :  * @param[out] result CMutableTransaction representing the complete transaction, if successful
    1443                 :             :  * @return True if we successfully extracted the transaction, false otherwise
    1444                 :             :  */
    1445                 :             : bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result);
    1446                 :             : 
    1447                 :             : /**
    1448                 :             :  * Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial signatures from each input.
    1449                 :             :  *
    1450                 :             :  * @param[out] out   the combined PSBT, if successful
    1451                 :             :  * @param[in]  psbtxs the PSBTs to combine
    1452                 :             :  * @return True if we successfully combined the transactions, false if they were not compatible
    1453                 :             :  */
    1454                 :             : [[nodiscard]] bool CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs);
    1455                 :             : 
    1456                 :             : //! Decode a base64ed PSBT into a PartiallySignedTransaction
    1457                 :             : [[nodiscard]] bool DecodeBase64PSBT(PartiallySignedTransaction& decoded_psbt, const std::string& base64_psbt, std::string& error);
    1458                 :             : //! Decode a raw (binary blob) PSBT into a PartiallySignedTransaction
    1459                 :             : [[nodiscard]] bool DecodeRawPSBT(PartiallySignedTransaction& decoded_psbt, std::span<const std::byte> raw_psbt, std::string& error);
    1460                 :             : 
    1461                 :             : #endif // BITCOIN_PSBT_H
        

Generated by: LCOV version 2.0-1