LCOV - code coverage report
Current view: top level - src - psbt.h (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 92.6 % 812 752
Test Date: 2026-05-15 07:20:25 Functions: 91.2 % 80 73
Branches: 67.6 % 1240 838

             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                 :             : #include <uint256.h>
      19                 :             : #include <util/result.h>
      20                 :             : 
      21                 :             : #include <optional>
      22                 :             : #include <bitset>
      23                 :             : 
      24                 :             : namespace node {
      25                 :             : enum class TransactionError;
      26                 :             : } // namespace node
      27                 :             : 
      28                 :             : using common::PSBTError;
      29                 :             : 
      30                 :             : // Magic bytes
      31                 :             : static constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff};
      32                 :             : 
      33                 :             : // Global types
      34                 :             : static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00;
      35                 :             : static constexpr uint8_t PSBT_GLOBAL_XPUB = 0x01;
      36                 :             : static constexpr uint8_t PSBT_GLOBAL_TX_VERSION = 0x02;
      37                 :             : static constexpr uint8_t PSBT_GLOBAL_FALLBACK_LOCKTIME = 0x03;
      38                 :             : static constexpr uint8_t PSBT_GLOBAL_INPUT_COUNT = 0x04;
      39                 :             : static constexpr uint8_t PSBT_GLOBAL_OUTPUT_COUNT = 0x05;
      40                 :             : static constexpr uint8_t PSBT_GLOBAL_TX_MODIFIABLE = 0x06;
      41                 :             : static constexpr uint8_t PSBT_GLOBAL_VERSION = 0xFB;
      42                 :             : static constexpr uint8_t PSBT_GLOBAL_PROPRIETARY = 0xFC;
      43                 :             : 
      44                 :             : // Input types
      45                 :             : static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00;
      46                 :             : static constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01;
      47                 :             : static constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02;
      48                 :             : static constexpr uint8_t PSBT_IN_SIGHASH = 0x03;
      49                 :             : static constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04;
      50                 :             : static constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05;
      51                 :             : static constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06;
      52                 :             : static constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07;
      53                 :             : static constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08;
      54                 :             : static constexpr uint8_t PSBT_IN_RIPEMD160 = 0x0A;
      55                 :             : static constexpr uint8_t PSBT_IN_SHA256 = 0x0B;
      56                 :             : static constexpr uint8_t PSBT_IN_HASH160 = 0x0C;
      57                 :             : static constexpr uint8_t PSBT_IN_HASH256 = 0x0D;
      58                 :             : static constexpr uint8_t PSBT_IN_PREVIOUS_TXID = 0x0e;
      59                 :             : static constexpr uint8_t PSBT_IN_OUTPUT_INDEX = 0x0f;
      60                 :             : static constexpr uint8_t PSBT_IN_SEQUENCE = 0x10;
      61                 :             : static constexpr uint8_t PSBT_IN_REQUIRED_TIME_LOCKTIME = 0x11;
      62                 :             : static constexpr uint8_t PSBT_IN_REQUIRED_HEIGHT_LOCKTIME = 0x12;
      63                 :             : static constexpr uint8_t PSBT_IN_TAP_KEY_SIG = 0x13;
      64                 :             : static constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG = 0x14;
      65                 :             : static constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT = 0x15;
      66                 :             : static constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
      67                 :             : static constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY = 0x17;
      68                 :             : static constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT = 0x18;
      69                 :             : static constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS = 0x1a;
      70                 :             : static constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE = 0x1b;
      71                 :             : static constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG = 0x1c;
      72                 :             : static constexpr uint8_t PSBT_IN_PROPRIETARY = 0xFC;
      73                 :             : 
      74                 :             : // Output types
      75                 :             : static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00;
      76                 :             : static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01;
      77                 :             : static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02;
      78                 :             : static constexpr uint8_t PSBT_OUT_AMOUNT = 0x03;
      79                 :             : static constexpr uint8_t PSBT_OUT_SCRIPT = 0x04;
      80                 :             : static constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
      81                 :             : static constexpr uint8_t PSBT_OUT_TAP_TREE = 0x06;
      82                 :             : static constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
      83                 :             : static constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS = 0x08;
      84                 :             : static constexpr uint8_t PSBT_OUT_PROPRIETARY = 0xFC;
      85                 :             : 
      86                 :             : // The separator is 0x00. Reading this in means that the unserializer can interpret it
      87                 :             : // as a 0 length key which indicates that this is the separator. The separator has no value.
      88                 :             : static constexpr uint8_t PSBT_SEPARATOR = 0x00;
      89                 :             : 
      90                 :             : // BIP 174 does not specify a maximum file size, but we set a limit anyway
      91                 :             : // to prevent reading a stream indefinitely and running out of memory.
      92                 :             : const std::streamsize MAX_FILE_SIZE_PSBT = 100000000; // 100 MB
      93                 :             : 
      94                 :             : // PSBT version number
      95                 :             : static constexpr uint32_t PSBT_HIGHEST_VERSION = 2;
      96                 :             : 
      97                 :             : /** A structure for PSBT proprietary types */
      98                 :       26308 : struct PSBTProprietary
      99                 :             : {
     100                 :             :     uint64_t subtype;
     101                 :             :     std::vector<unsigned char> identifier;
     102                 :             :     std::vector<unsigned char> key;
     103                 :             :     std::vector<unsigned char> value;
     104                 :             : 
     105                 :       95348 :     bool operator<(const PSBTProprietary &b) const {
     106                 :       95348 :         return key < b.key;
     107                 :             :     }
     108                 :           0 :     bool operator==(const PSBTProprietary &b) const {
     109         [ #  # ]:           0 :         return key == b.key;
     110                 :             :     }
     111                 :             : };
     112                 :             : 
     113                 :             : // Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
     114                 :             : // The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
     115                 :             : template<typename Stream, typename... X>
     116                 :      229565 : void SerializeToVector(Stream& s, const X&... args)
     117                 :             : {
     118                 :      229565 :     SizeComputer sizecomp;
     119                 :      229565 :     SerializeMany(sizecomp, args...);
     120                 :      229565 :     WriteCompactSize(s, sizecomp.size());
     121                 :      229565 :     SerializeMany(s, args...);
     122                 :      229565 : }
     123                 :             : 
     124                 :             : // Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
     125                 :             : template<typename Stream, typename... X>
     126                 :       85267 : void UnserializeFromVector(Stream& s, X&&... args)
     127                 :             : {
     128                 :       85267 :     size_t expected_size = ReadCompactSize(s);
     129                 :       85264 :     size_t remaining_before = s.size();
     130         [ +  + ]:       84612 :     UnserializeMany(s, args...);
     131                 :       84612 :     size_t remaining_after = s.size();
     132         [ +  + ]:       84612 :     if (remaining_after + expected_size != remaining_before) {
     133         [ +  - ]:        1210 :         throw std::ios_base::failure("Size of value was not the stated size");
     134                 :             :     }
     135                 :       84007 : }
     136                 :             : 
     137                 :             : // Deserialize bytes of given length from the stream as a KeyOriginInfo
     138                 :             : template<typename Stream>
     139                 :       57737 : KeyOriginInfo DeserializeKeyOrigin(Stream& s, uint64_t length)
     140                 :             : {
     141                 :             :     // Read in key path
     142   [ +  +  +  + ]:       57737 :     if (length % 4 || length == 0) {
     143         [ +  - ]:         196 :         throw std::ios_base::failure("Invalid length for HD key path");
     144                 :             :     }
     145                 :             : 
     146                 :       57639 :     KeyOriginInfo hd_keypath;
     147         [ +  + ]:       57639 :     s >> hd_keypath.fingerprint;
     148         [ +  + ]:     1746357 :     for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
     149                 :             :         uint32_t index;
     150                 :     1688760 :         s >> index;
     151         [ +  - ]:     1688760 :         hd_keypath.path.push_back(index);
     152                 :             :     }
     153                 :       57539 :     return hd_keypath;
     154                 :         100 : }
     155                 :             : 
     156                 :             : // Deserialize a length prefixed KeyOriginInfo from a stream
     157                 :             : template<typename Stream>
     158                 :       42528 : void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
     159                 :             : {
     160                 :       42528 :     hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
     161                 :       42321 : }
     162                 :             : 
     163                 :             : // Deserialize HD keypaths into a map
     164                 :             : template<typename Stream>
     165         [ -  + ]:       32676 : void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
     166                 :             : {
     167                 :             :     // Make sure that the key is the size of pubkey + 1
     168   [ +  +  +  + ]:       32676 :     if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
     169         [ +  - ]:       20790 :         throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
     170                 :             :     }
     171                 :             :     // Read in the pubkey from key
     172                 :       22281 :     CPubKey pubkey(key.begin() + 1, key.end());
     173         [ +  + ]:       22281 :     if (!pubkey.IsFullyValid()) {
     174         [ +  - ]:         320 :        throw std::ios_base::failure("Invalid pubkey");
     175                 :             :     }
     176                 :             : 
     177                 :       22121 :     KeyOriginInfo keypath;
     178         [ +  + ]:       22121 :     DeserializeHDKeypath(s, keypath);
     179                 :             : 
     180                 :             :     // Add to map
     181         [ +  - ]:       21974 :     hd_keypaths.emplace(pubkey, std::move(keypath));
     182                 :       21974 : }
     183                 :             : 
     184                 :             : // Serialize a KeyOriginInfo to a stream
     185                 :             : template<typename Stream>
     186                 :       35706 : void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
     187                 :             : {
     188                 :       35706 :     s << hd_keypath.fingerprint;
     189         [ +  + ]:     1393679 :     for (const auto& path : hd_keypath.path) {
     190                 :     1357973 :         s << path;
     191                 :             :     }
     192                 :       35706 : }
     193                 :             : 
     194                 :             : // Serialize a length prefixed KeyOriginInfo to a stream
     195                 :             : template<typename Stream>
     196                 :       27058 : void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
     197                 :             : {
     198         [ -  + ]:       27058 :     WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
     199         [ +  - ]:       27058 :     SerializeKeyOrigin(s, hd_keypath);
     200                 :       27058 : }
     201                 :             : 
     202                 :             : // Serialize HD keypaths to a stream from a map
     203                 :             : template<typename Stream>
     204                 :      133944 : void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
     205                 :             : {
     206         [ +  + ]:      151422 :     for (const auto& keypath_pair : hd_keypaths) {
     207         [ +  + ]:       17643 :         if (!keypath_pair.first.IsValid()) {
     208         [ +  - ]:         330 :             throw std::ios_base::failure("Invalid CPubKey being serialized");
     209                 :             :         }
     210                 :       17478 :         SerializeToVector(s, type, std::span{keypath_pair.first});
     211         [ +  - ]:       34956 :         SerializeHDKeypath(s, keypath_pair.second);
     212                 :             :     }
     213                 :      133779 : }
     214                 :             : 
     215                 :             : // Deserialize a PSBT_{IN/OUT}_MUSIG2_PARTICIPANT_PUBKEYS field
     216                 :             : template<typename Stream>
     217                 :       10986 : void DeserializeMuSig2ParticipantPubkeys(Stream& s, SpanReader& skey, std::map<CPubKey, std::vector<CPubKey>>& out, std::string context)
     218                 :             : {
     219                 :             :     std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
     220                 :       10986 :     skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
     221                 :       10986 :     CPubKey agg_pubkey(agg_pubkey_bytes);
     222         [ +  + ]:       10986 :     if (!agg_pubkey.IsFullyValid()) {
     223   [ +  -  +  - ]:          72 :         throw std::ios_base::failure(context + " musig2 aggregate pubkey is invalid");
     224                 :             :     }
     225                 :             : 
     226                 :       10950 :     std::vector<CPubKey> participants;
     227         [ +  + ]:       10950 :     std::vector<unsigned char> val;
     228         [ -  + ]:       10907 :     s >> val;
     229                 :       10907 :     SpanReader s_val{val};
     230         [ +  + ]:       13300 :     while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
     231                 :             :         std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
     232         [ +  - ]:        4880 :         s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
     233                 :        2440 :         CPubKey participant(part_pubkey_bytes);
     234   [ +  -  +  + ]:        2440 :         if (!participant.IsFullyValid()) {
     235   [ +  -  +  - ]:          94 :             throw std::ios_base::failure(context + " musig2 participant pubkey is invalid");
     236                 :             :         }
     237         [ +  - ]:        2393 :         participants.push_back(participant);
     238                 :             :     }
     239         [ +  + ]:       10860 :     if (!s_val.empty()) {
     240   [ +  -  +  - ]:          64 :         throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
     241                 :             :     }
     242                 :             : 
     243         [ +  - ]:       10828 :     out.emplace(agg_pubkey, participants);
     244                 :       10950 : }
     245                 :             : 
     246                 :             : // Deserialize the MuSig2 participant identifiers from PSBT_MUSIG2_{PUBNONCE/PARTIAL_SIG} fields
     247                 :             : // Both fields contain the same data after the type byte - aggregate pubkey | participant pubkey | leaf script hash
     248                 :             : template<typename Stream>
     249                 :        6022 : void DeserializeMuSig2ParticipantDataIdentifier(Stream& skey, CPubKey& agg_pub, CPubKey& part_pub, uint256& leaf_hash)
     250                 :             : {
     251                 :        6022 :     leaf_hash.SetNull();
     252                 :             : 
     253                 :             :     std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
     254                 :             :     std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
     255                 :             : 
     256                 :        6022 :     skey >> std::as_writable_bytes(std::span{part_pubkey_bytes}) >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
     257                 :        6022 :     agg_pub.Set(agg_pubkey_bytes.begin(), agg_pubkey_bytes.end());
     258         [ +  + ]:        6022 :     if (!agg_pub.IsFullyValid()) {
     259         [ +  - ]:          80 :         throw std::ios_base::failure("musig2 aggregate pubkey is invalid");
     260                 :             :     }
     261                 :             : 
     262                 :        5982 :     part_pub.Set(part_pubkey_bytes.begin(), part_pubkey_bytes.end());
     263         [ +  + ]:        5982 :     if (!part_pub.IsFullyValid()) {
     264         [ +  - ]:          48 :         throw std::ios_base::failure("musig2 participant pubkey is invalid");
     265                 :             :     }
     266                 :             : 
     267         [ +  + ]:        5958 :     if (!skey.empty()) {
     268                 :         611 :         skey >> leaf_hash;
     269                 :             :     }
     270                 :        5958 : }
     271                 :             : 
     272                 :      195563 : static inline void ExpectedKeySize(const std::string& key_name, const std::vector<unsigned char>& key, uint64_t expected_size) {
     273   [ -  +  +  + ]:      195563 :     if (key.size() != expected_size) {
     274   [ +  -  +  - ]:        7608 :         throw std::ios_base::failure(tfm::format("Size of key was not %d for the type %s", expected_size, key_name));
     275                 :             :     }
     276                 :      191759 : }
     277                 :             : 
     278                 :             : /** A structure for PSBTs which contain per-input information */
     279                 :             : class PSBTInput
     280                 :             : {
     281                 :             : private:
     282                 :        5381 :     uint32_t m_psbt_version;
     283                 :             : 
     284                 :             : public:
     285         [ +  - ]:        5381 :     CTransactionRef non_witness_utxo;
     286                 :        5381 :     CTxOut witness_utxo;
     287                 :             :     CScript redeem_script;
     288                 :             :     CScript witness_script;
     289                 :             :     CScript final_script_sig;
     290                 :             :     CScriptWitness final_script_witness;
     291                 :        5381 :     std::map<CPubKey, KeyOriginInfo> hd_keypaths;
     292                 :        5381 :     std::map<CKeyID, SigPair> partial_sigs;
     293                 :        5381 :     std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
     294                 :        5381 :     std::map<uint256, std::vector<unsigned char>> sha256_preimages;
     295                 :        5381 :     std::map<uint160, std::vector<unsigned char>> hash160_preimages;
     296                 :        5381 :     std::map<uint256, std::vector<unsigned char>> hash256_preimages;
     297                 :             : 
     298                 :        5381 :     Txid prev_txid;
     299                 :        5381 :     uint32_t prev_out;
     300         [ +  - ]:        5381 :     std::optional<uint32_t> sequence;
     301                 :        5381 :     std::optional<uint32_t> time_locktime;
     302                 :        5381 :     std::optional<uint32_t> height_locktime;
     303                 :             : 
     304                 :             :     // Taproot fields
     305                 :        5381 :     std::vector<unsigned char> m_tap_key_sig;
     306                 :        5381 :     std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
     307                 :        5381 :     std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
     308                 :        5381 :     std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
     309                 :        5381 :     XOnlyPubKey m_tap_internal_key;
     310                 :             :     uint256 m_tap_merkle_root;
     311                 :             : 
     312                 :             :     // MuSig2 fields
     313                 :        5381 :     std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
     314                 :             :     // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to pubnonce
     315                 :        5381 :     std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, std::vector<uint8_t>>> m_musig2_pubnonces;
     316                 :             :     // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to partial_sig
     317                 :        5381 :     std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, uint256>> m_musig2_partial_sigs;
     318                 :             : 
     319                 :        5381 :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
     320                 :        5381 :     std::set<PSBTProprietary> m_proprietary;
     321         [ +  - ]:        5381 :     std::optional<int> sighash_type;
     322                 :             : 
     323                 :             :     bool IsNull() const;
     324                 :             :     void FillSignatureData(SignatureData& sigdata) const;
     325                 :             :     void FromSignatureData(const SignatureData& sigdata);
     326                 :             :     [[nodiscard]] bool Merge(const PSBTInput& input);
     327                 :        7995 :     uint32_t GetVersion() const { return m_psbt_version; }
     328                 :             :     COutPoint GetOutPoint() const;
     329                 :             :     /**
     330                 :             :      * Retrieves the UTXO for this input
     331                 :             :      *
     332                 :             :      * @param[out] utxo The UTXO of this input
     333                 :             :      * @return Whether the UTXO could be retrieved
     334                 :             :      */
     335                 :             :     bool GetUTXO(CTxOut& utxo) const;
     336                 :             :     bool HasSignatures() const;
     337                 :             : 
     338                 :       81628 :     explicit PSBTInput(uint32_t psbt_version, const Txid& prev_txid, uint32_t prev_out, std::optional<uint32_t> sequence = std::nullopt)
     339                 :       81628 :         : m_psbt_version(psbt_version),
     340                 :       81628 :         prev_txid(prev_txid),
     341         [ -  + ]:       81628 :         prev_out(prev_out),
     342         [ -  + ]:       81628 :         sequence(sequence)
     343                 :             :     {
     344         [ -  + ]:       81628 :         assert(m_psbt_version == 0 || m_psbt_version == 2);
     345                 :       81628 :     }
     346                 :             : 
     347                 :             :     // Construct a PSBTInput when the previous txid and output index are expected to be serialized
     348                 :             :     template <typename Stream>
     349                 :           0 :     explicit PSBTInput(deserialize_type, Stream& s, uint32_t psbt_version)
     350         [ #  # ]:           0 :         : m_psbt_version(psbt_version)
     351                 :             :     {
     352         [ #  # ]:           0 :         assert(m_psbt_version == 2);
     353         [ #  # ]:           0 :         Unserialize(s);
     354         [ #  # ]:           0 :     }
     355                 :             : 
     356   [ +  -  +  -  :       96858 :     bool operator==(const PSBTInput&) const = default;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  -  +  
                      - ]
     357                 :             : 
     358                 :             :     template <typename Stream>
     359                 :       50508 :     inline void Serialize(Stream& s) const {
     360                 :             :         // Write the utxo
     361         [ +  + ]:       50508 :         if (non_witness_utxo) {
     362                 :         650 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_NON_WITNESS_UTXO));
     363                 :         650 :             SerializeToVector(s, TX_NO_WITNESS(non_witness_utxo));
     364                 :             :         }
     365         [ +  + ]:       50508 :         if (!witness_utxo.IsNull()) {
     366                 :       13384 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESS_UTXO));
     367                 :       13384 :             SerializeToVector(s, witness_utxo);
     368                 :             :         }
     369                 :             : 
     370   [ +  +  +  +  :       54449 :         if (final_script_sig.empty() && final_script_witness.IsNull()) {
                   +  + ]
     371                 :             :             // Write any partial signatures
     372         [ +  + ]:       46386 :             for (const auto& sig_pair : partial_sigs) {
     373                 :        1937 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
     374                 :        1937 :                 s << sig_pair.second.second;
     375                 :             :             }
     376                 :             : 
     377                 :             :             // Write the sighash type
     378         [ +  + ]:       44449 :             if (sighash_type != std::nullopt) {
     379                 :         184 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_SIGHASH));
     380                 :         184 :                 SerializeToVector(s, *sighash_type);
     381                 :             :             }
     382                 :             : 
     383                 :             :             // Write the redeem script
     384   [ +  +  +  + ]:       44877 :             if (!redeem_script.empty()) {
     385                 :        1241 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_REDEEMSCRIPT));
     386                 :        1241 :                 s << redeem_script;
     387                 :             :             }
     388                 :             : 
     389                 :             :             // Write the witness script
     390   [ +  +  +  + ]:       44870 :             if (!witness_script.empty()) {
     391                 :        2062 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESSSCRIPT));
     392                 :        2062 :                 s << witness_script;
     393                 :             :             }
     394                 :             : 
     395                 :             :             // Write any hd keypaths
     396                 :       44449 :             SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_IN_BIP32_DERIVATION));
     397                 :             : 
     398                 :             :             // Write any ripemd160 preimage
     399         [ +  + ]:       48082 :             for (const auto& [hash, preimage] : ripemd160_preimages) {
     400                 :        3633 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_RIPEMD160), std::span{hash});
     401                 :        3633 :                 s << preimage;
     402                 :             :             }
     403                 :             : 
     404                 :             :             // Write any sha256 preimage
     405         [ +  + ]:       48829 :             for (const auto& [hash, preimage] : sha256_preimages) {
     406                 :        4380 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_SHA256), std::span{hash});
     407                 :        4380 :                 s << preimage;
     408                 :             :             }
     409                 :             : 
     410                 :             :             // Write any hash160 preimage
     411         [ +  + ]:       48952 :             for (const auto& [hash, preimage] : hash160_preimages) {
     412                 :        4503 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH160), std::span{hash});
     413                 :        4503 :                 s << preimage;
     414                 :             :             }
     415                 :             : 
     416                 :             :             // Write any hash256 preimage
     417         [ +  + ]:       47193 :             for (const auto& [hash, preimage] : hash256_preimages) {
     418                 :        2744 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH256), std::span{hash});
     419                 :        2744 :                 s << preimage;
     420                 :             :             }
     421                 :             : 
     422                 :             :             // Write taproot key sig
     423         [ +  + ]:       44449 :             if (!m_tap_key_sig.empty()) {
     424                 :         625 :                 SerializeToVector(s, PSBT_IN_TAP_KEY_SIG);
     425                 :         625 :                 s << m_tap_key_sig;
     426                 :             :             }
     427                 :             : 
     428                 :             :             // Write taproot script sigs
     429         [ +  + ]:       50112 :             for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
     430                 :        5663 :                 const auto& [xonly, leaf_hash] = pubkey_leaf;
     431                 :        5663 :                 SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
     432                 :        5663 :                 s << sig;
     433                 :             :             }
     434                 :             : 
     435                 :             :             // Write taproot leaf scripts
     436         [ +  + ]:       53426 :             for (const auto& [leaf, control_blocks] : m_tap_scripts) {
     437                 :        8977 :                 const auto& [script, leaf_ver] = leaf;
     438   [ -  +  +  + ]:       18738 :                 for (const auto& control_block : control_blocks) {
     439                 :        9761 :                     SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, std::span{control_block});
     440                 :        9761 :                     std::vector<unsigned char> value_v(script.begin(), script.end());
     441   [ +  -  +  - ]:        9761 :                     value_v.push_back((uint8_t)leaf_ver);
     442                 :        9761 :                     s << value_v;
     443                 :             :                 }
     444                 :             :             }
     445                 :             : 
     446                 :             :             // Write taproot bip32 keypaths
     447         [ +  + ]:       47737 :             for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
     448                 :        3288 :                 const auto& [leaf_hashes, origin] = leaf_origin;
     449                 :        3288 :                 SerializeToVector(s, PSBT_IN_TAP_BIP32_DERIVATION, xonly);
     450                 :        3288 :                 std::vector<unsigned char> value;
     451         [ +  - ]:        3288 :                 VectorWriter s_value{value, 0};
     452         [ +  - ]:        3288 :                 s_value << leaf_hashes;
     453   [ +  -  +  - ]:        6576 :                 SerializeKeyOrigin(s_value, origin);
     454                 :        3288 :                 s << value;
     455                 :             :             }
     456                 :             : 
     457                 :             :             // Write taproot internal key
     458         [ +  + ]:       88898 :             if (!m_tap_internal_key.IsNull()) {
     459                 :         499 :                 SerializeToVector(s, PSBT_IN_TAP_INTERNAL_KEY);
     460         [ +  - ]:         998 :                 s << ToByteVector(m_tap_internal_key);
     461                 :             :             }
     462                 :             : 
     463                 :             :             // Write taproot merkle root
     464         [ +  + ]:       88898 :             if (!m_tap_merkle_root.IsNull()) {
     465                 :         574 :                 SerializeToVector(s, PSBT_IN_TAP_MERKLE_ROOT);
     466                 :         574 :                 SerializeToVector(s, m_tap_merkle_root);
     467                 :             :             }
     468                 :             : 
     469                 :             :             // Write MuSig2 Participants
     470         [ +  + ]:       46378 :             for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
     471                 :        1929 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
     472                 :        1929 :                 std::vector<unsigned char> value;
     473         [ +  - ]:        1929 :                 VectorWriter s_value{value, 0};
     474   [ +  -  +  + ]:        2460 :                 for (auto& pk : part_pubs) {
     475         [ +  - ]:        1062 :                     s_value << std::span{pk};
     476                 :             :                 }
     477                 :        1929 :                 s << value;
     478                 :             :             }
     479                 :             : 
     480                 :             :             // Write MuSig2 pubnonces
     481         [ +  + ]:       45813 :             for (const auto& [agg_pubkey_leaf_hash, pubnonces] : m_musig2_pubnonces) {
     482                 :        1364 :                 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
     483         [ +  + ]:        3131 :                 for (const auto& [part_pubkey, pubnonce] : pubnonces) {
     484         [ +  + ]:        3534 :                     if (leaf_hash.IsNull()) {
     485                 :        1570 :                         SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey});
     486                 :             :                     } else {
     487                 :         197 :                         SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey}, leaf_hash);
     488                 :             :                     }
     489                 :        1767 :                     s << pubnonce;
     490                 :             :                 }
     491                 :             :             }
     492                 :             : 
     493                 :             :             // Write MuSig2 partial signatures
     494         [ +  + ]:       45496 :             for (const auto& [agg_pubkey_leaf_hash, psigs] : m_musig2_partial_sigs) {
     495                 :        1047 :                 const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
     496         [ +  + ]:        2429 :                 for (const auto& [pubkey, psig] : psigs) {
     497         [ +  + ]:        2764 :                     if (leaf_hash.IsNull()) {
     498                 :        1183 :                         SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey});
     499                 :             :                     } else {
     500                 :         199 :                         SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey}, leaf_hash);
     501                 :             :                     }
     502                 :        1382 :                     SerializeToVector(s, psig);
     503                 :             :                 }
     504                 :             :             }
     505                 :             :         }
     506                 :             : 
     507                 :             :         // Write script sig
     508   [ +  +  +  + ]:       54449 :         if (!final_script_sig.empty()) {
     509                 :        5169 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTSIG));
     510                 :        5169 :             s << final_script_sig;
     511                 :             :         }
     512                 :             :         // write script witness
     513         [ +  + ]:       50508 :         if (!final_script_witness.IsNull()) {
     514                 :         895 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTWITNESS));
     515                 :         895 :             SerializeToVector(s, final_script_witness.stack);
     516                 :             :         }
     517                 :             : 
     518                 :             :         // Write PSBTv2 fields
     519         [ +  + ]:       50508 :         if (m_psbt_version >= 2) {
     520                 :             :             // Write prev txid, vout, sequence, and lock times
     521                 :        3628 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_PREVIOUS_TXID));
     522                 :        3628 :             SerializeToVector(s, prev_txid);
     523                 :             : 
     524                 :        3628 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_OUTPUT_INDEX));
     525                 :        3628 :             SerializeToVector(s, prev_out);
     526                 :             : 
     527         [ +  - ]:        3628 :             if (sequence != std::nullopt) {
     528                 :        3628 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_SEQUENCE));
     529                 :        3628 :                 SerializeToVector(s, *sequence);
     530                 :             :             }
     531         [ -  + ]:        3628 :             if (time_locktime != std::nullopt) {
     532                 :           0 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_REQUIRED_TIME_LOCKTIME));
     533                 :           0 :                 SerializeToVector(s, *time_locktime);
     534                 :             :             }
     535         [ -  + ]:        3628 :             if (height_locktime != std::nullopt) {
     536                 :           0 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_REQUIRED_HEIGHT_LOCKTIME));
     537                 :           0 :                 SerializeToVector(s, *height_locktime);
     538                 :             :             }
     539                 :             :         }
     540                 :             : 
     541                 :             :         // Write proprietary things
     542         [ +  + ]:       53784 :         for (const auto& entry : m_proprietary) {
     543                 :        3276 :             s << entry.key;
     544                 :        3276 :             s << entry.value;
     545                 :             :         }
     546                 :             : 
     547                 :             :         // Write unknown things
     548         [ +  + ]:       83889 :         for (auto& entry : unknown) {
     549                 :       33381 :             s << entry.first;
     550                 :       33381 :             s << entry.second;
     551                 :             :         }
     552                 :             : 
     553                 :       50508 :         s << PSBT_SEPARATOR;
     554                 :       50508 :     }
     555                 :             : 
     556                 :             : 
     557                 :             :     template <typename Stream>
     558                 :       70393 :     inline void Unserialize(Stream& s) {
     559                 :             :         // Used for duplicate key detection
     560                 :       70393 :         std::set<std::vector<unsigned char>> key_lookup;
     561                 :             :         // Cache whether PSBTv2 required fields were seen
     562                 :       70393 :         bool found_prev_txid = false;
     563                 :       70393 :         bool found_prev_out = false;
     564                 :             : 
     565                 :             :         // Read loop
     566                 :       70393 :         bool found_sep = false;
     567         [ +  + ]:      254988 :         while(!s.empty()) {
     568                 :             :             // Read the key of format "<keylen><keytype><keydata>" after which
     569                 :             :             // "key" will contain "<keytype><keydata>"
     570         [ +  + ]:      250117 :             std::vector<unsigned char> key;
     571                 :      249769 :             s >> key;
     572                 :             : 
     573                 :             :             // the key is empty if that was actually a separator byte
     574                 :             :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
     575         [ +  + ]:      249769 :             if (key.empty()) {
     576                 :       65522 :                 found_sep = true;
     577                 :             :                 break;
     578                 :             :             }
     579                 :             : 
     580                 :             :             // Duplicate keys are not permitted
     581   [ +  -  +  + ]:      184247 :             if (!key_lookup.emplace(key).second) {
     582   [ -  +  +  -  :         538 :                 throw std::ios_base::failure(tfm::format("Duplicate Key, input key \"%s\" already provided", HexStr(key)));
             +  -  +  - ]
     583                 :             :             }
     584                 :             : 
     585                 :             :             // "skey" is used so that "key" is unchanged after reading keytype below
     586                 :      183978 :             SpanReader skey{key};
     587                 :             :             // keytype is of the format compact size uint at the beginning of "key"
     588         [ +  + ]:      183978 :             uint64_t type = ReadCompactSize(skey);
     589                 :             : 
     590                 :             :             // Do stuff based on keytype "type", i.e., key checks, reading values of the
     591                 :             :             // format "<valuelen><valuedata>" from the stream "s", and value checks
     592   [ +  +  +  +  :      183974 :             switch(type) {
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
             +  +  +  +  
                      + ]
     593                 :        1472 :                 case PSBT_IN_NON_WITNESS_UTXO:
     594                 :             :                 {
     595   [ +  -  +  + ]:        1497 :                     ExpectedKeySize("Input Non-witness UTXO", key, 1);
     596                 :             :                     // Set the stream to unserialize with witness since this is always a valid network transaction
     597         [ +  + ]:        1447 :                     UnserializeFromVector(s, TX_WITH_WITNESS(non_witness_utxo));
     598                 :             :                     break;
     599                 :             :                 }
     600                 :       16902 :                 case PSBT_IN_WITNESS_UTXO:
     601   [ +  -  +  + ]:       16920 :                     ExpectedKeySize("Input Witness UTXO", key, 1);
     602         [ +  + ]:       16884 :                     UnserializeFromVector(s, witness_utxo);
     603                 :             :                     break;
     604         [ -  + ]:        4711 :                 case PSBT_IN_PARTIAL_SIG:
     605                 :             :                 {
     606                 :             :                     // Make sure that the key is the size of pubkey + 1
     607   [ +  +  +  + ]:        4711 :                     if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
     608         [ +  - ]:          34 :                         throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
     609                 :             :                     }
     610                 :             :                     // Read in the pubkey from key
     611                 :        4694 :                     CPubKey pubkey(key.begin() + 1, key.end());
     612   [ +  -  +  + ]:        4694 :                     if (!pubkey.IsFullyValid()) {
     613         [ +  - ]:         120 :                        throw std::ios_base::failure("Invalid pubkey");
     614                 :             :                     }
     615                 :             : 
     616                 :             :                     // Read in the signature from value
     617         [ +  + ]:        4634 :                     std::vector<unsigned char> sig;
     618                 :        4344 :                     s >> sig;
     619                 :             : 
     620                 :             :                     // Check that the signature is validly encoded
     621   [ +  +  +  -  :        4344 :                     if (sig.empty() || !CheckSignatureEncoding(sig, SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC, nullptr)) {
                   +  + ]
     622         [ +  - ]:         658 :                         throw std::ios_base::failure("Signature is not a valid encoding");
     623                 :             :                     }
     624                 :             : 
     625                 :             :                     // Add to list
     626   [ +  -  +  - ]:        8030 :                     partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
     627                 :             :                     break;
     628                 :        4634 :                 }
     629                 :         470 :                 case PSBT_IN_SIGHASH:
     630   [ +  -  +  + ]:         485 :                     ExpectedKeySize("Input Sighash Type", key, 1);
     631                 :             :                     int sighash;
     632         [ +  + ]:         455 :                     UnserializeFromVector(s, sighash);
     633                 :         442 :                     sighash_type = sighash;
     634                 :         442 :                     break;
     635                 :        2278 :                 case PSBT_IN_REDEEMSCRIPT:
     636                 :             :                 {
     637   [ +  -  +  + ]:        2296 :                     ExpectedKeySize("Input redeemScript", key, 1);
     638         [ +  + ]:        2260 :                     s >> redeem_script;
     639                 :             :                     break;
     640                 :             :                 }
     641                 :        3460 :                 case PSBT_IN_WITNESSSCRIPT:
     642                 :             :                 {
     643   [ +  -  +  + ]:        3472 :                     ExpectedKeySize("Input witnessScript", key, 1);
     644         [ +  + ]:        3448 :                     s >> witness_script;
     645                 :             :                     break;
     646                 :             :                 }
     647                 :        5145 :                 case PSBT_IN_BIP32_DERIVATION:
     648                 :             :                 {
     649         [ +  + ]:        5145 :                     DeserializeHDKeypaths(s, key, hd_keypaths);
     650                 :             :                     break;
     651                 :             :                 }
     652                 :        6767 :                 case PSBT_IN_SCRIPTSIG:
     653                 :             :                 {
     654   [ +  -  +  + ]:        6781 :                     ExpectedKeySize("Input Final scriptSig", key, 1);
     655         [ +  + ]:      186597 :                     s >> final_script_sig;
     656                 :             :                     break;
     657                 :             :                 }
     658                 :        1537 :                 case PSBT_IN_SCRIPTWITNESS:
     659                 :             :                 {
     660   [ +  -  +  + ]:        1554 :                     ExpectedKeySize("Input Final scriptWitness", key, 1);
     661         [ +  + ]:        1520 :                     UnserializeFromVector(s, final_script_witness.stack);
     662                 :             :                     break;
     663                 :             :                 }
     664                 :        6816 :                 case PSBT_IN_RIPEMD160:
     665                 :             :                 {
     666   [ +  -  +  +  :       13632 :                     ExpectedKeySize("Input RIPEMD160 Preimage", key, CRIPEMD160::OUTPUT_SIZE + 1);
                   +  - ]
     667                 :             :                     // Read in the hash from key
     668         [ +  - ]:        6800 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     669                 :        6800 :                     uint160 hash(hash_vec);
     670                 :             : 
     671                 :             :                     // Read in the preimage from value
     672         [ +  + ]:        6800 :                     std::vector<unsigned char> preimage;
     673                 :        6758 :                     s >> preimage;
     674                 :             : 
     675                 :             :                     // Add to preimages list
     676         [ +  - ]:        6758 :                     ripemd160_preimages.emplace(hash, std::move(preimage));
     677                 :             :                     break;
     678                 :        6842 :                 }
     679                 :        7972 :                 case PSBT_IN_SHA256:
     680                 :             :                 {
     681   [ +  -  +  +  :       15944 :                     ExpectedKeySize("Input SHA256 Preimage", key, CSHA256::OUTPUT_SIZE + 1);
                   +  - ]
     682                 :             :                     // Read in the hash from key
     683         [ +  - ]:        7955 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     684                 :        7955 :                     uint256 hash(hash_vec);
     685                 :             : 
     686                 :             :                     // Read in the preimage from value
     687         [ +  + ]:        7955 :                     std::vector<unsigned char> preimage;
     688                 :        7914 :                     s >> preimage;
     689                 :             : 
     690                 :             :                     // Add to preimages list
     691         [ +  - ]:        7914 :                     sha256_preimages.emplace(hash, std::move(preimage));
     692                 :             :                     break;
     693                 :        7996 :                 }
     694                 :        7411 :                 case PSBT_IN_HASH160:
     695                 :             :                 {
     696   [ +  -  +  +  :       14822 :                     ExpectedKeySize("Input Hash160 Preimage", key, CHash160::OUTPUT_SIZE + 1);
                   +  - ]
     697                 :             :                     // Read in the hash from key
     698         [ +  - ]:        7396 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     699                 :        7396 :                     uint160 hash(hash_vec);
     700                 :             : 
     701                 :             :                     // Read in the preimage from value
     702         [ +  + ]:        7396 :                     std::vector<unsigned char> preimage;
     703                 :        7356 :                     s >> preimage;
     704                 :             : 
     705                 :             :                     // Add to preimages list
     706         [ +  - ]:        7356 :                     hash160_preimages.emplace(hash, std::move(preimage));
     707                 :             :                     break;
     708                 :        7436 :                 }
     709                 :        6538 :                 case PSBT_IN_HASH256:
     710                 :             :                 {
     711   [ +  -  +  +  :       13076 :                     ExpectedKeySize("Input Hash256 Preimage", key, CHash256::OUTPUT_SIZE + 1);
                   +  - ]
     712                 :             :                     // Read in the hash from key
     713         [ +  - ]:        6524 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     714                 :        6524 :                     uint256 hash(hash_vec);
     715                 :             : 
     716                 :             :                     // Read in the preimage from value
     717         [ +  + ]:        6524 :                     std::vector<unsigned char> preimage;
     718                 :        6480 :                     s >> preimage;
     719                 :             : 
     720                 :             :                     // Add to preimages list
     721         [ +  - ]:        6480 :                     hash256_preimages.emplace(hash, std::move(preimage));
     722                 :             :                     break;
     723                 :        6568 :                 }
     724                 :         789 :                 case PSBT_IN_PREVIOUS_TXID:
     725                 :             :                 {
     726   [ +  -  +  + ]:        1543 :                     ExpectedKeySize("Input Previous TXID", key, 1);
     727         [ +  - ]:          35 :                     if (m_psbt_version < 2) {
     728         [ +  - ]:          70 :                         throw std::ios_base::failure("Previous txid is not allowed in PSBTv0");
     729                 :             :                     }
     730         [ #  # ]:           0 :                     UnserializeFromVector(s, prev_txid);
     731                 :             :                     found_prev_txid = true;
     732                 :             :                     break;
     733                 :             :                 }
     734                 :          44 :                 case PSBT_IN_OUTPUT_INDEX:
     735                 :             :                 {
     736   [ +  -  +  + ]:          83 :                     ExpectedKeySize("Input Previous Output's Index", key, 1);
     737         [ +  - ]:           5 :                     if (m_psbt_version < 2) {
     738         [ +  - ]:          10 :                         throw std::ios_base::failure("Previous output's index is not allowed in PSBTv0");
     739                 :             :                     }
     740         [ #  # ]:           0 :                     UnserializeFromVector(s, prev_out);
     741                 :             :                     found_prev_out = true;
     742                 :             :                     break;
     743                 :             :                 }
     744                 :         236 :                 case PSBT_IN_SEQUENCE:
     745                 :             :                 {
     746   [ +  -  +  + ]:         461 :                     ExpectedKeySize("Input Sequence", key, 1);
     747         [ +  - ]:          11 :                     if (m_psbt_version < 2) {
     748         [ +  - ]:          22 :                         throw std::ios_base::failure("Sequence is not allowed in PSBTv0");
     749                 :             :                     }
     750         [ #  # ]:           0 :                     sequence.emplace();
     751         [ #  # ]:           0 :                     UnserializeFromVector(s, *sequence);
     752                 :             :                     break;
     753                 :             :                 }
     754                 :         424 :                 case PSBT_IN_REQUIRED_TIME_LOCKTIME:
     755                 :             :                 {
     756   [ +  -  +  + ]:         836 :                     ExpectedKeySize("Input Required Time Based Locktime", key, 1);
     757         [ +  - ]:          12 :                     if (m_psbt_version < 2) {
     758         [ +  - ]:          24 :                         throw std::ios_base::failure("Required time based locktime is not allowed in PSBTv0");
     759                 :             :                     }
     760         [ #  # ]:           0 :                     time_locktime.emplace();
     761         [ #  # ]:           0 :                     UnserializeFromVector(s, *time_locktime);
     762         [ #  # ]:           0 :                     if (*time_locktime < LOCKTIME_THRESHOLD) {
     763         [ #  # ]:           0 :                         throw std::ios_base::failure("Required time based locktime is invalid (less than 500000000)");
     764                 :             :                     }
     765                 :             :                     break;
     766                 :             :                 }
     767                 :          45 :                 case PSBT_IN_REQUIRED_HEIGHT_LOCKTIME:
     768                 :             :                 {
     769   [ +  -  +  + ]:          81 :                     ExpectedKeySize("Input Required Height Based Locktime", key, 1);
     770         [ +  - ]:           9 :                     if (m_psbt_version < 2) {
     771         [ +  - ]:          18 :                         throw std::ios_base::failure("Required height based locktime is not allowed in PSBTv0");
     772                 :             :                     }
     773         [ #  # ]:           0 :                     height_locktime.emplace();
     774         [ #  # ]:           0 :                     UnserializeFromVector(s, *height_locktime);
     775         [ #  # ]:           0 :                     if (*height_locktime >= LOCKTIME_THRESHOLD) {
     776         [ #  # ]:           0 :                         throw std::ios_base::failure("Required height based locktime is invalid (greater than or equal to 500000000)");
     777         [ #  # ]:           0 :                     } else if (*height_locktime == 0) {
     778         [ #  # ]:           0 :                         throw std::ios_base::failure("Required height based locktime is invalid (0)");
     779                 :             :                     }
     780                 :             :                     break;
     781                 :             :                 }
     782                 :        1055 :                 case PSBT_IN_TAP_KEY_SIG:
     783                 :             :                 {
     784   [ +  -  +  + ]:        1065 :                     ExpectedKeySize("Input Taproot Key Path Signature", key, 1);
     785         [ +  + ]:        1045 :                     s >> m_tap_key_sig;
     786   [ -  +  +  + ]:        1021 :                     if (m_tap_key_sig.size() < 64) {
     787         [ +  - ]:          28 :                         throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
     788         [ +  + ]:        1007 :                     } else if (m_tap_key_sig.size() > 65) {
     789         [ +  - ]:          26 :                         throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
     790                 :             :                     }
     791                 :             :                     break;
     792                 :             :                 }
     793                 :        8978 :                 case PSBT_IN_TAP_SCRIPT_SIG:
     794                 :             :                 {
     795   [ +  -  +  +  :       17956 :                     ExpectedKeySize("Input Taproot Script Path Signature", key, 65);
                   -  + ]
     796                 :        8965 :                     SpanReader s_key{std::span{key}.subspan(1)};
     797                 :        8965 :                     XOnlyPubKey xonly;
     798         [ +  - ]:        8965 :                     uint256 hash;
     799         [ +  - ]:        8965 :                     s_key >> xonly;
     800                 :        8965 :                     s_key >> hash;
     801         [ +  + ]:        8965 :                     std::vector<unsigned char> sig;
     802         [ -  + ]:        8936 :                     s >> sig;
     803         [ +  + ]:        8936 :                     if (sig.size() < 64) {
     804         [ +  - ]:          50 :                         throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
     805         [ +  + ]:        8911 :                     } else if (sig.size() > 65) {
     806         [ +  - ]:          28 :                         throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
     807                 :             :                     }
     808         [ +  - ]:        8897 :                     m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
     809                 :             :                     break;
     810                 :        8965 :                 }
     811         [ -  + ]:       21085 :                 case PSBT_IN_TAP_LEAF_SCRIPT:
     812                 :             :                 {
     813         [ +  + ]:       21085 :                     if (key.size() < 34) {
     814         [ +  - ]:          58 :                         throw std::ios_base::failure("Input Taproot leaf script key is not at least 34 bytes");
     815         [ +  + ]:       21056 :                     } else if ((key.size() - 2) % 32 != 0) {
     816         [ +  - ]:          22 :                         throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
     817                 :             :                     }
     818         [ +  + ]:       21045 :                     std::vector<unsigned char> script_v;
     819                 :       20997 :                     s >> script_v;
     820         [ +  + ]:       20997 :                     if (script_v.empty()) {
     821         [ +  - ]:          32 :                         throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
     822                 :             :                     }
     823         [ +  - ]:       20981 :                     uint8_t leaf_ver = script_v.back();
     824                 :       20981 :                     script_v.pop_back();
     825         [ +  - ]:       20981 :                     const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
     826   [ +  -  +  -  :       41962 :                     m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
                   +  - ]
     827                 :             :                     break;
     828                 :       21045 :                 }
     829                 :        6245 :                 case PSBT_IN_TAP_BIP32_DERIVATION:
     830                 :             :                 {
     831   [ +  -  +  +  :       12490 :                     ExpectedKeySize("Input Taproot BIP32 Keypath", key, 33);
                   -  + ]
     832                 :        6232 :                     SpanReader s_key{std::span{key}.subspan(1)};
     833         [ +  - ]:        6232 :                     XOnlyPubKey xonly;
     834         [ +  + ]:        6232 :                     s_key >> xonly;
     835                 :        6232 :                     std::set<uint256> leaf_hashes;
     836   [ +  +  +  + ]:        6232 :                     uint64_t value_len = ReadCompactSize(s);
     837         [ +  + ]:        6220 :                     size_t before_hashes = s.size();
     838         [ +  + ]:        6134 :                     s >> leaf_hashes;
     839                 :        6134 :                     size_t after_hashes = s.size();
     840                 :        6134 :                     size_t hashes_len = before_hashes - after_hashes;
     841         [ +  + ]:        6134 :                     if (hashes_len > value_len) {
     842         [ +  - ]:          40 :                         throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
     843                 :             :                     }
     844                 :        6114 :                     size_t origin_len = value_len - hashes_len;
     845   [ +  +  +  - ]:       12210 :                     m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
     846                 :             :                     break;
     847                 :        6232 :                 }
     848                 :         600 :                 case PSBT_IN_TAP_INTERNAL_KEY:
     849                 :             :                 {
     850   [ +  -  +  + ]:         613 :                     ExpectedKeySize("Input Taproot Internal Key", key, 1);
     851         [ +  + ]:         587 :                     UnserializeFromVector(s, m_tap_internal_key);
     852                 :             :                     break;
     853                 :             :                 }
     854                 :         752 :                 case PSBT_IN_TAP_MERKLE_ROOT:
     855                 :             :                 {
     856   [ +  -  +  + ]:         771 :                     ExpectedKeySize("Input Taproot Merkle Root", key, 1);
     857         [ +  + ]:         733 :                     UnserializeFromVector(s, m_tap_merkle_root);
     858                 :             :                     break;
     859                 :             :                 }
     860                 :        2964 :                 case PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS:
     861                 :             :                 {
     862   [ +  -  +  + ]:        2979 :                     ExpectedKeySize("Input MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
     863   [ +  -  +  + ]:        5898 :                     DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
     864                 :             :                     break;
     865                 :             :                 }
     866         [ -  + ]:        3572 :                 case PSBT_IN_MUSIG2_PUB_NONCE:
     867                 :             :                 {
     868   [ +  +  +  + ]:        3572 :                     if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
     869         [ +  - ]:          28 :                         throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
     870                 :             :                     }
     871                 :        3558 :                     CPubKey agg_pub, part_pub;
     872                 :        3558 :                     uint256 leaf_hash;
     873         [ +  + ]:        3558 :                     DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
     874                 :             : 
     875         [ +  + ]:        3522 :                     std::vector<uint8_t> pubnonce;
     876         [ -  + ]:        3504 :                     s >> pubnonce;
     877         [ +  + ]:        3504 :                     if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) {
     878         [ +  - ]:          20 :                         throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
     879                 :             :                     }
     880                 :             : 
     881   [ +  -  +  - ]:        3494 :                     m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
     882                 :             :                     break;
     883                 :        3522 :                 }
     884         [ -  + ]:        2479 :                 case PSBT_IN_MUSIG2_PARTIAL_SIG:
     885                 :             :                 {
     886   [ +  +  +  + ]:        2479 :                     if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
     887         [ +  - ]:          30 :                         throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
     888                 :             :                     }
     889                 :        2464 :                     CPubKey agg_pub, part_pub;
     890                 :        2464 :                     uint256 leaf_hash;
     891         [ +  + ]:        2464 :                     DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
     892                 :             : 
     893                 :        2436 :                     uint256 partial_sig;
     894         [ +  + ]:        2436 :                     UnserializeFromVector(s, partial_sig);
     895                 :             : 
     896   [ +  -  +  - ]:        2426 :                     m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
     897                 :             :                     break;
     898                 :             :                 }
     899         [ +  + ]:        7927 :                 case PSBT_IN_PROPRIETARY:
     900                 :             :                 {
     901         [ +  + ]:        7927 :                     PSBTProprietary this_prop;
     902                 :        7907 :                     skey >> this_prop.identifier;
     903         [ +  + ]:        7907 :                     this_prop.subtype = ReadCompactSize(skey);
     904         [ +  - ]:        7905 :                     this_prop.key = key;
     905                 :             : 
     906                 :        7855 :                     s >> this_prop.value;
     907         [ +  - ]:        7855 :                     m_proprietary.insert(this_prop);
     908                 :             :                     break;
     909                 :        7927 :                 }
     910                 :             :                 // Unknown stuff
     911                 :       55300 :                 default:
     912                 :             :                     // Read in the value
     913         [ +  + ]:       55300 :                     std::vector<unsigned char> val_bytes;
     914                 :       55234 :                     s >> val_bytes;
     915         [ +  - ]:       55234 :                     unknown.emplace(std::move(key), std::move(val_bytes));
     916                 :             :                     break;
     917                 :       55300 :             }
     918                 :             :         }
     919                 :             : 
     920                 :             :         if (!found_sep) {
     921         [ +  - ]:         240 :             throw std::ios_base::failure("Separator is missing at the end of an input map");
     922                 :             :         }
     923                 :             : 
     924                 :             :         // Make sure required PSBTv2 fields are present
     925         [ -  + ]:       65522 :         if (m_psbt_version >= 2) {
     926         [ #  # ]:           0 :             if (!found_prev_txid) {
     927         [ #  # ]:           0 :                 throw std::ios_base::failure("Previous TXID is required in PSBTv2");
     928                 :             :             }
     929         [ #  # ]:           0 :             if (!found_prev_out) {
     930         [ #  # ]:           0 :                 throw std::ios_base::failure("Previous output's index is required in PSBTv2");
     931                 :             :             }
     932                 :             :         }
     933                 :       65522 :     }
     934                 :             : };
     935                 :             : 
     936                 :             : /** A structure for PSBTs which contains per output information */
     937                 :             : class PSBTOutput
     938                 :             : {
     939                 :             : private:
     940                 :        6096 :     uint32_t m_psbt_version;
     941                 :             : 
     942                 :             : public:
     943                 :             :     CScript redeem_script;
     944                 :             :     CScript witness_script;
     945                 :        6096 :     std::map<CPubKey, KeyOriginInfo> hd_keypaths;
     946                 :             : 
     947                 :        6096 :     XOnlyPubKey m_tap_internal_key;
     948                 :        6096 :     std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
     949                 :        6096 :     std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
     950                 :        6096 :     std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
     951                 :             : 
     952                 :        6096 :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
     953                 :        6096 :     std::set<PSBTProprietary> m_proprietary;
     954                 :             : 
     955                 :        6096 :     CAmount amount;
     956                 :             :     CScript script;
     957                 :             : 
     958                 :             :     bool IsNull() const;
     959                 :             :     void FillSignatureData(SignatureData& sigdata) const;
     960                 :             :     void FromSignatureData(const SignatureData& sigdata);
     961                 :             :     [[nodiscard]] bool Merge(const PSBTOutput& output);
     962                 :       30331 :     uint32_t GetVersion() const { return m_psbt_version; }
     963                 :             : 
     964                 :      110285 :     explicit PSBTOutput(uint32_t psbt_version, CAmount amount, const CScript& script)
     965                 :      110285 :         : m_psbt_version(psbt_version),
     966                 :      110285 :         amount(amount),
     967                 :      110285 :         script(script)
     968                 :             :     {
     969         [ -  + ]:      110285 :         assert(m_psbt_version == 0 || m_psbt_version == 2);
     970                 :      110285 :     }
     971                 :             : 
     972                 :             :     // Construct a PSBTOutput when the amount and script are expected to be serialized
     973                 :             :     template <typename Stream>
     974                 :           0 :     explicit PSBTOutput(deserialize_type, Stream& s, uint32_t psbt_version)
     975         [ #  # ]:           0 :         : m_psbt_version(psbt_version)
     976                 :             :     {
     977         [ #  # ]:           0 :         assert(m_psbt_version == 2);
     978         [ #  # ]:           0 :         Unserialize(s);
     979                 :           0 :     }
     980                 :             : 
     981   [ +  -  +  -  :       36576 :     bool operator==(const PSBTOutput&) const = default;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
             -  +  -  -  
                      + ]
     982                 :             : 
     983                 :             :     template <typename Stream>
     984                 :       78875 :     inline void Serialize(Stream& s) const {
     985                 :             :         // Write the redeem script
     986   [ +  +  +  + ]:       80389 :         if (!redeem_script.empty()) {
     987                 :        2506 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_REDEEMSCRIPT));
     988                 :        2506 :             s << redeem_script;
     989                 :             :         }
     990                 :             : 
     991                 :             :         // Write the witness script
     992   [ +  +  +  + ]:       79656 :         if (!witness_script.empty()) {
     993                 :        1687 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_WITNESSSCRIPT));
     994                 :        1687 :             s << witness_script;
     995                 :             :         }
     996                 :             : 
     997                 :             :         // Write any hd keypaths
     998                 :       78875 :         SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_OUT_BIP32_DERIVATION));
     999                 :             : 
    1000         [ +  + ]:       78875 :         if (m_psbt_version >= 2) {
    1001                 :             :             // Write amount and spk
    1002                 :        3688 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_AMOUNT));
    1003                 :        3688 :             SerializeToVector(s, amount);
    1004                 :             : 
    1005                 :        3688 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_SCRIPT));
    1006                 :        3688 :             s << script;
    1007                 :             :         }
    1008                 :             : 
    1009                 :             :         // Write proprietary things
    1010         [ +  + ]:       86665 :         for (const auto& entry : m_proprietary) {
    1011                 :        7790 :             s << entry.key;
    1012                 :        7790 :             s << entry.value;
    1013                 :             :         }
    1014                 :             : 
    1015                 :             :         // Write taproot internal key
    1016         [ +  + ]:      157750 :         if (!m_tap_internal_key.IsNull()) {
    1017                 :        1883 :             SerializeToVector(s, PSBT_OUT_TAP_INTERNAL_KEY);
    1018         [ +  - ]:        3766 :             s << ToByteVector(m_tap_internal_key);
    1019                 :             :         }
    1020                 :             : 
    1021                 :             :         // Write taproot tree
    1022         [ +  + ]:       78875 :         if (!m_tap_tree.empty()) {
    1023                 :        1144 :             SerializeToVector(s, PSBT_OUT_TAP_TREE);
    1024                 :        1144 :             std::vector<unsigned char> value;
    1025         [ +  - ]:        1144 :             VectorWriter s_value{value, 0};
    1026   [ +  -  +  + ]:        5514 :             for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
    1027         [ +  - ]:        4370 :                 s_value << depth;
    1028         [ +  - ]:        4370 :                 s_value << leaf_ver;
    1029                 :        4370 :                 s_value << script;
    1030                 :             :             }
    1031                 :        1144 :             s << value;
    1032                 :        1144 :         }
    1033                 :             : 
    1034                 :             :         // Write taproot bip32 keypaths
    1035         [ +  + ]:       84235 :         for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
    1036                 :        5360 :             const auto& [leaf_hashes, origin] = leaf;
    1037                 :        5360 :             SerializeToVector(s, PSBT_OUT_TAP_BIP32_DERIVATION, xonly);
    1038                 :        5360 :             std::vector<unsigned char> value;
    1039         [ +  - ]:        5360 :             VectorWriter s_value{value, 0};
    1040         [ +  - ]:        5360 :             s_value << leaf_hashes;
    1041   [ +  -  +  - ]:       10720 :             SerializeKeyOrigin(s_value, origin);
    1042                 :        5360 :             s << value;
    1043                 :             :         }
    1044                 :             : 
    1045                 :             :         // Write MuSig2 Participants
    1046         [ +  + ]:       84173 :         for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
    1047                 :        5298 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
    1048                 :        5298 :             std::vector<unsigned char> value;
    1049         [ +  - ]:        5298 :             VectorWriter s_value{value, 0};
    1050   [ +  -  +  + ]:        6498 :             for (auto& pk : part_pubs) {
    1051         [ +  - ]:        2400 :                 s_value << std::span{pk};
    1052                 :             :             }
    1053                 :        5298 :             s << value;
    1054                 :             :         }
    1055                 :             : 
    1056                 :             :         // Write unknown things
    1057         [ +  + ]:      111716 :         for (auto& entry : unknown) {
    1058                 :       32841 :             s << entry.first;
    1059                 :       32841 :             s << entry.second;
    1060                 :             :         }
    1061                 :             : 
    1062                 :       78875 :         s << PSBT_SEPARATOR;
    1063                 :       78875 :     }
    1064                 :             : 
    1065                 :             : 
    1066                 :             :     template <typename Stream>
    1067                 :       98585 :     inline void Unserialize(Stream& s) {
    1068                 :             :         // Used for duplicate key detection
    1069                 :       98585 :         std::set<std::vector<unsigned char>> key_lookup;
    1070                 :             :         // Cache whether PSBTv2 required fields are found
    1071                 :       98585 :         bool found_amount = false;
    1072                 :       98585 :         bool found_script = false;
    1073                 :             : 
    1074                 :             :         // Read loop
    1075                 :       98585 :         bool found_sep = false;
    1076         [ +  + ]:      214214 :         while(!s.empty()) {
    1077                 :             :             // Read the key of format "<keylen><keytype><keydata>" after which
    1078                 :             :             // "key" will contain "<keytype><keydata>"
    1079         [ +  + ]:      211756 :             std::vector<unsigned char> key;
    1080                 :      211431 :             s >> key;
    1081                 :             : 
    1082                 :             :             // the key is empty if that was actually a separator byte
    1083                 :             :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
    1084         [ +  + ]:      211431 :             if (key.empty()) {
    1085                 :       96127 :                 found_sep = true;
    1086                 :             :                 break;
    1087                 :             :             }
    1088                 :             : 
    1089                 :             :             // Duplicate keys are not permitted
    1090   [ +  -  +  + ]:      115304 :             if (!key_lookup.emplace(key).second) {
    1091   [ -  +  +  -  :         224 :                 throw std::ios_base::failure(tfm::format("Duplicate Key, output key \"%s\" already provided", HexStr(key)));
             +  -  +  - ]
    1092                 :             :             }
    1093                 :             : 
    1094                 :             :             // "skey" is used so that "key" is unchanged after reading keytype below
    1095                 :      115192 :             SpanReader skey{key};
    1096                 :             :             // keytype is of the format compact size uint at the beginning of "key"
    1097         [ +  + ]:      115192 :             uint64_t type = ReadCompactSize(skey);
    1098                 :             : 
    1099                 :             :             // Do stuff based on keytype "type", i.e., key checks, reading values of the
    1100                 :             :             // format "<valuelen><valuedata>" from the stream "s", and value checks
    1101   [ +  +  +  +  :      115187 :             switch(type) {
          +  +  +  +  +  
                   +  + ]
    1102                 :        4427 :                 case PSBT_OUT_REDEEMSCRIPT:
    1103                 :             :                 {
    1104   [ +  -  +  + ]:        4464 :                     ExpectedKeySize("Output redeemScript", key, 1);
    1105         [ +  + ]:        4390 :                     s >> redeem_script;
    1106                 :             :                     break;
    1107                 :             :                 }
    1108                 :        3290 :                 case PSBT_OUT_WITNESSSCRIPT:
    1109                 :             :                 {
    1110   [ +  -  +  + ]:        3303 :                     ExpectedKeySize("Output witnessScript", key, 1);
    1111         [ +  + ]:        3277 :                     s >> witness_script;
    1112                 :             :                     break;
    1113                 :             :                 }
    1114                 :       16911 :                 case PSBT_OUT_BIP32_DERIVATION:
    1115                 :             :                 {
    1116         [ +  + ]:       16911 :                     DeserializeHDKeypaths(s, key, hd_keypaths);
    1117                 :             :                     break;
    1118                 :             :                 }
    1119                 :         397 :                 case PSBT_OUT_AMOUNT:
    1120                 :             :                 {
    1121   [ +  -  +  + ]:         737 :                     ExpectedKeySize("Output Amount", key, 1);
    1122         [ +  - ]:          57 :                     if (m_psbt_version < 2) {
    1123         [ +  - ]:         114 :                         throw std::ios_base::failure("Output amount is not allowed in PSBTv0");
    1124                 :             :                     }
    1125         [ #  # ]:           0 :                     UnserializeFromVector(s, amount);
    1126                 :             :                     found_amount = true;
    1127                 :             :                     break;
    1128                 :             :                 }
    1129                 :         229 :                 case PSBT_OUT_SCRIPT:
    1130                 :             :                 {
    1131   [ +  -  +  + ]:         423 :                     ExpectedKeySize("Output Script", key, 1);
    1132         [ +  - ]:          35 :                     if (m_psbt_version < 2) {
    1133         [ +  - ]:          70 :                         throw std::ios_base::failure("Output script is not allowed in PSBTv0");
    1134                 :             :                     }
    1135         [ -  - ]:      113241 :                     s >> script;
    1136                 :             :                     found_script = true;
    1137                 :             :                     break;
    1138                 :             :                 }
    1139                 :        2244 :                 case PSBT_OUT_TAP_INTERNAL_KEY:
    1140                 :             :                 {
    1141   [ +  -  +  + ]:        2262 :                     ExpectedKeySize("Output Taproot Internal Key", key, 1);
    1142         [ +  + ]:        2226 :                     UnserializeFromVector(s, m_tap_internal_key);
    1143                 :             :                     break;
    1144                 :             :                 }
    1145                 :        2947 :                 case PSBT_OUT_TAP_TREE:
    1146                 :             :                 {
    1147   [ +  -  +  + ]:        2963 :                     ExpectedKeySize("Output Taproot Tree Key", key, 1);
    1148         [ +  + ]:        2931 :                     std::vector<unsigned char> tree_v;
    1149         [ -  + ]:        2896 :                     s >> tree_v;
    1150         [ +  + ]:        2896 :                     SpanReader s_tree{tree_v};
    1151         [ +  + ]:        2896 :                     if (s_tree.empty()) {
    1152         [ +  - ]:          34 :                         throw std::ios_base::failure("Output Taproot tree must not be empty");
    1153                 :             :                     }
    1154                 :        2879 :                     TaprootBuilder builder;
    1155         [ +  + ]:      137342 :                     while (!s_tree.empty()) {
    1156                 :             :                         uint8_t depth;
    1157                 :             :                         uint8_t leaf_ver;
    1158         [ +  - ]:      134463 :                         std::vector<unsigned char> script;
    1159         [ +  + ]:      134463 :                         s_tree >> depth;
    1160         [ +  + ]:      134404 :                         s_tree >> leaf_ver;
    1161                 :      134162 :                         s_tree >> script;
    1162         [ +  + ]:      134162 :                         if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
    1163         [ +  - ]:          86 :                             throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
    1164                 :             :                         }
    1165         [ +  + ]:      134119 :                         if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
    1166         [ +  - ]:         112 :                             throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
    1167                 :             :                         }
    1168         [ +  - ]:      134063 :                         m_tap_tree.emplace_back(depth, leaf_ver, script);
    1169   [ -  +  +  - ]:      134063 :                         builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
    1170                 :             :                     }
    1171         [ +  + ]:        2479 :                     if (!builder.IsComplete()) {
    1172         [ +  - ]:         206 :                         throw std::ios_base::failure("Output Taproot tree is malformed");
    1173                 :             :                     }
    1174                 :             :                     break;
    1175                 :        3434 :                 }
    1176                 :        9356 :                 case PSBT_OUT_TAP_BIP32_DERIVATION:
    1177                 :             :                 {
    1178   [ +  -  +  +  :       18712 :                     ExpectedKeySize("Output Taproot BIP32 Keypath", key, 33);
                   -  + ]
    1179         [ +  + ]:        9331 :                     XOnlyPubKey xonly(uint256(std::span<uint8_t>(key).last(32)));
    1180                 :        9331 :                     std::set<uint256> leaf_hashes;
    1181   [ +  +  +  + ]:        9331 :                     uint64_t value_len = ReadCompactSize(s);
    1182         [ +  + ]:        9315 :                     size_t before_hashes = s.size();
    1183         [ +  + ]:        9164 :                     s >> leaf_hashes;
    1184                 :        9164 :                     size_t after_hashes = s.size();
    1185                 :        9164 :                     size_t hashes_len = before_hashes - after_hashes;
    1186         [ +  + ]:        9164 :                     if (hashes_len > value_len) {
    1187         [ +  - ]:          32 :                         throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
    1188                 :             :                     }
    1189                 :        9148 :                     size_t origin_len = value_len - hashes_len;
    1190   [ +  +  +  - ]:       18270 :                     m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
    1191                 :             :                     break;
    1192                 :        9331 :                 }
    1193                 :        8061 :                 case PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS:
    1194                 :             :                 {
    1195   [ +  -  +  + ]:        8085 :                     ExpectedKeySize("Output MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
    1196   [ +  -  +  + ]:       16074 :                     DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Output"});
    1197                 :             :                     break;
    1198                 :             :                 }
    1199         [ +  + ]:       12635 :                 case PSBT_OUT_PROPRIETARY:
    1200                 :             :                 {
    1201         [ +  + ]:       12635 :                     PSBTProprietary this_prop;
    1202                 :       12609 :                     skey >> this_prop.identifier;
    1203         [ +  + ]:       12609 :                     this_prop.subtype = ReadCompactSize(skey);
    1204         [ +  - ]:       12608 :                     this_prop.key = key;
    1205                 :             : 
    1206                 :       12573 :                     s >> this_prop.value;
    1207         [ +  - ]:       12573 :                     m_proprietary.insert(this_prop);
    1208                 :             :                     break;
    1209                 :       12635 :                 }
    1210                 :             :                 // Unknown stuff
    1211                 :       54690 :                 default: {
    1212                 :             :                     // Read in the value
    1213         [ +  + ]:       54690 :                     std::vector<unsigned char> val_bytes;
    1214                 :       54610 :                     s >> val_bytes;
    1215         [ +  - ]:       54610 :                     unknown.emplace(std::move(key), std::move(val_bytes));
    1216                 :             :                     break;
    1217                 :       54690 :                 }
    1218                 :             :             }
    1219                 :             :         }
    1220                 :             : 
    1221                 :             :         if (!found_sep) {
    1222         [ +  - ]:         140 :             throw std::ios_base::failure("Separator is missing at the end of an output map");
    1223                 :             :         }
    1224                 :             : 
    1225                 :             :         // Make sure required PSBTv2 fields are present
    1226         [ -  + ]:       96127 :         if (m_psbt_version >= 2) {
    1227         [ #  # ]:           0 :             if (!found_amount) {
    1228         [ #  # ]:           0 :                 throw std::ios_base::failure("Output amount is required in PSBTv2");
    1229                 :             :             }
    1230         [ #  # ]:           0 :             if (!found_script) {
    1231         [ #  # ]:           0 :                 throw std::ios_base::failure("Output script is required in PSBTv2");
    1232                 :             :             }
    1233                 :             :         }
    1234                 :       96127 :     }
    1235                 :             : };
    1236                 :             : 
    1237                 :             : /** A version of CTransaction with the PSBT format*/
    1238                 :             : class PartiallySignedTransaction
    1239                 :             : {
    1240                 :             : private:
    1241                 :             :     std::optional<uint32_t> m_version;
    1242                 :             : 
    1243                 :             : public:
    1244                 :             :     // We use a vector of CExtPubKey in the event that there happens to be the same KeyOriginInfos for different CExtPubKeys
    1245                 :             :     // Note that this map swaps the key and values from the serialization
    1246                 :             :     std::map<KeyOriginInfo, std::set<CExtPubKey>> m_xpubs;
    1247                 :             :     std::optional<std::bitset<8>> m_tx_modifiable;
    1248                 :             :     std::vector<PSBTInput> inputs;
    1249                 :             :     std::vector<PSBTOutput> outputs;
    1250                 :             :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
    1251                 :             :     std::set<PSBTProprietary> m_proprietary;
    1252                 :             : 
    1253                 :             :     uint32_t tx_version;
    1254                 :             :     std::optional<uint32_t> fallback_locktime;
    1255                 :             : 
    1256                 :             :     bool IsNull() const;
    1257                 :             :     uint32_t GetVersion() const;
    1258                 :             : 
    1259                 :             :     /** Merge psbt into this. The two psbts must have the same underlying CTransaction (i.e. the
    1260                 :             :       * same actual Bitcoin transaction.) Returns true if the merge succeeded, false otherwise. */
    1261                 :             :     [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
    1262                 :             :     bool AddInput(const PSBTInput& psbtin);
    1263                 :             :     bool AddOutput(const PSBTOutput& psbtout);
    1264                 :             :     std::optional<uint32_t> ComputeTimeLock() const;
    1265                 :             :     std::optional<CMutableTransaction> GetUnsignedTx() const;
    1266                 :             :     std::optional<Txid> GetUniqueID() const;
    1267                 :             :     explicit PartiallySignedTransaction(const CMutableTransaction& tx, uint32_t version = 2);
    1268                 :             : 
    1269                 :             :     template <typename Stream>
    1270                 :       33929 :     inline void Serialize(Stream& s) const {
    1271                 :             : 
    1272                 :             :         // magic bytes
    1273                 :       33929 :         s << PSBT_MAGIC_BYTES;
    1274                 :             : 
    1275         [ +  + ]:       33929 :         if (GetVersion() < 2) {
    1276                 :             :             // unsigned tx flag
    1277                 :       33854 :             SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_UNSIGNED_TX));
    1278                 :             : 
    1279                 :             :             // Write serialized tx to a stream
    1280         [ +  - ]:       67708 :             SerializeToVector(s, TX_NO_WITNESS(*GetUnsignedTx()));
    1281                 :             :         }
    1282                 :             : 
    1283                 :             :         // Write xpubs
    1284         [ +  + ]:       41475 :         for (const auto& xpub_pair : m_xpubs) {
    1285         [ +  + ]:       17126 :             for (const auto& xpub : xpub_pair.second) {
    1286                 :             :                 unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
    1287                 :        9580 :                 xpub.EncodeWithVersion(ser_xpub);
    1288                 :             :                 // Note that the serialization swaps the key and value
    1289                 :             :                 // The xpub is the key (for uniqueness) while the path is the value
    1290                 :        9580 :                 SerializeToVector(s, PSBT_GLOBAL_XPUB, ser_xpub);
    1291         [ +  - ]:       19160 :                 SerializeHDKeypath(s, xpub_pair.first);
    1292                 :             :             }
    1293                 :             :         }
    1294                 :             : 
    1295         [ +  + ]:       33929 :         if (GetVersion() >= 2) {
    1296                 :             :             // Write PSBTv2 tx version, locktime, counts, etc.
    1297                 :          75 :             SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_TX_VERSION));
    1298                 :          75 :             SerializeToVector(s, tx_version);
    1299         [ +  - ]:          75 :             if (fallback_locktime != std::nullopt) {
    1300                 :          75 :                 SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_FALLBACK_LOCKTIME));
    1301                 :          75 :                 SerializeToVector(s, *fallback_locktime);
    1302                 :             :             }
    1303                 :             : 
    1304                 :          75 :             SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_INPUT_COUNT));
    1305         [ -  + ]:          75 :             SerializeToVector(s, CompactSizeWriter(inputs.size()));
    1306                 :          75 :             SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_OUTPUT_COUNT));
    1307         [ -  + ]:          75 :             SerializeToVector(s, CompactSizeWriter(outputs.size()));
    1308                 :             : 
    1309         [ -  + ]:          75 :             if (m_tx_modifiable != std::nullopt) {
    1310                 :           0 :                 SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_TX_MODIFIABLE));
    1311                 :           0 :                 SerializeToVector(s, static_cast<uint8_t>(m_tx_modifiable->to_ulong()));
    1312                 :             :             }
    1313                 :             :         }
    1314                 :             : 
    1315                 :             :         // PSBT version
    1316         [ +  + ]:       33929 :         if (GetVersion() > 0) {
    1317                 :          75 :             SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_VERSION));
    1318                 :          75 :             SerializeToVector(s, *m_version);
    1319                 :             :         }
    1320                 :             : 
    1321                 :             :         // Write proprietary things
    1322         [ +  + ]:       36321 :         for (const auto& entry : m_proprietary) {
    1323                 :        2392 :             s << entry.key;
    1324                 :        2392 :             s << entry.value;
    1325                 :             :         }
    1326                 :             : 
    1327                 :             :         // Write the unknown things
    1328         [ +  + ]:       61043 :         for (auto& entry : unknown) {
    1329                 :       27114 :             s << entry.first;
    1330                 :       27114 :             s << entry.second;
    1331                 :             :         }
    1332                 :             : 
    1333                 :             :         // Separator
    1334                 :       33929 :         s << PSBT_SEPARATOR;
    1335                 :             : 
    1336                 :             :         // Write inputs
    1337         [ +  + ]:       84042 :         for (const PSBTInput& input : inputs) {
    1338                 :       50113 :             s << input;
    1339                 :             :         }
    1340                 :             :         // Write outputs
    1341         [ +  + ]:      112623 :         for (const PSBTOutput& output : outputs) {
    1342                 :       78694 :             s << output;
    1343                 :             :         }
    1344                 :       33929 :     }
    1345                 :             : 
    1346                 :             : 
    1347                 :             :     template <typename Stream>
    1348                 :       64723 :     inline void Unserialize(Stream& s) {
    1349                 :             :         // Read the magic bytes
    1350                 :             :         uint8_t magic[5];
    1351                 :       60328 :         s >> magic;
    1352         [ +  + ]:       60328 :         if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
    1353         [ +  - ]:        1194 :             throw std::ios_base::failure("Invalid PSBT magic bytes");
    1354                 :             :         }
    1355                 :             : 
    1356                 :             :         // Used for duplicate key detection
    1357                 :       59731 :         std::set<std::vector<unsigned char>> key_lookup;
    1358                 :             : 
    1359                 :             :         // Track the global xpubs we have already seen. Just for sanity checking
    1360                 :       59731 :         std::set<CExtPubKey> global_xpubs;
    1361                 :             : 
    1362                 :             :         // Read global data
    1363                 :       59731 :         bool found_sep = false;
    1364                 :       59731 :         std::optional<CMutableTransaction> tx;
    1365                 :       59731 :         uint64_t input_count = 0;
    1366                 :       59731 :         uint64_t output_count = 0;
    1367                 :       59731 :         bool found_input_count = false;
    1368                 :       59731 :         bool found_output_count = false;
    1369                 :       59731 :         bool found_tx_version = false;
    1370                 :       59731 :         bool found_fallback_locktime = false;
    1371         [ +  + ]:      190320 :         while(!s.empty()) {
    1372                 :             :             // Read the key of format "<keylen><keytype><keydata>" after which
    1373                 :             :             // "key" will contain "<keytype><keydata>"
    1374         [ +  + ]:      187764 :             std::vector<unsigned char> key;
    1375                 :      187602 :             s >> key;
    1376                 :             : 
    1377                 :             :             // the key is empty if that was actually a separator byte
    1378                 :             :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
    1379         [ +  + ]:      187602 :             if (key.empty()) {
    1380                 :       57175 :                 found_sep = true;
    1381                 :             :                 break;
    1382                 :             :             }
    1383                 :             : 
    1384                 :             :             // Duplicate keys are not permitted
    1385   [ +  -  +  + ]:      130427 :             if (!key_lookup.emplace(key).second) {
    1386   [ -  +  +  -  :         126 :                 throw std::ios_base::failure(tfm::format("Duplicate Key, global key \"%s\" already provided", HexStr(key)));
             +  -  +  - ]
    1387                 :             :             }
    1388                 :             : 
    1389                 :             :             // "skey" is used so that "key" is unchanged after reading keytype below
    1390                 :      130364 :             SpanReader skey{key};
    1391                 :             :             // keytype is of the format compact size uint at the beginning of "key"
    1392         [ +  + ]:      130364 :             uint64_t type = ReadCompactSize(skey);
    1393                 :             : 
    1394                 :             :             // Do stuff based on keytype "type", i.e., key checks, reading values of the
    1395                 :             :             // format "<valuelen><valuedata>" from the stream "s", and value checks
    1396   [ +  +  +  +  :      130342 :             switch(type) {
          +  +  +  +  +  
                      + ]
    1397                 :       58695 :                 case PSBT_GLOBAL_UNSIGNED_TX:
    1398                 :             :                 {
    1399   [ +  -  +  + ]:       58712 :                     ExpectedKeySize("Global Unsigned TX", key, 1);
    1400                 :             :                     // Set the stream to serialize with non-witness since this should always be non-witness
    1401         [ +  - ]:       58678 :                     tx.emplace();
    1402         [ +  + ]:       58678 :                     UnserializeFromVector(s, TX_NO_WITNESS(*tx));
    1403                 :             :                     // Make sure that all scriptSigs and scriptWitnesses are empty
    1404         [ +  + ]:      130993 :                     for (const CTxIn& txin : tx->vin) {
    1405   [ +  +  +  +  :       72737 :                         if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
                   -  + ]
    1406         [ +  - ]:          40 :                             throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
    1407                 :             :                         }
    1408                 :             :                     }
    1409                 :       58268 :                     tx_version = tx->version;
    1410         [ -  + ]:       58268 :                     fallback_locktime = tx->nLockTime;
    1411                 :             :                     // Set the input and output counts
    1412   [ -  +  -  + ]:       58268 :                     input_count = tx->vin.size();
    1413         [ -  + ]:       58268 :                     output_count = tx->vout.size();
    1414                 :       58268 :                     break;
    1415                 :             :                 }
    1416                 :         469 :                 case PSBT_GLOBAL_TX_VERSION:
    1417                 :             :                 {
    1418   [ +  -  +  + ]:         917 :                     ExpectedKeySize("Global Transaction Version", key, 1);
    1419         [ -  + ]:          21 :                     UnserializeFromVector(s, tx_version);
    1420                 :             :                     found_tx_version = true;
    1421                 :             :                     break;
    1422                 :             :                 }
    1423                 :         664 :                 case PSBT_GLOBAL_FALLBACK_LOCKTIME:
    1424                 :             :                 {
    1425   [ +  -  +  + ]:        1277 :                     ExpectedKeySize("Global Fallback Locktime", key, 1);
    1426         [ +  + ]:          51 :                     fallback_locktime.emplace();
    1427         [ -  + ]:          51 :                     UnserializeFromVector(s, *fallback_locktime);
    1428                 :             :                     found_fallback_locktime = true;
    1429                 :             :                     break;
    1430                 :             :                 }
    1431                 :         138 :                 case PSBT_GLOBAL_INPUT_COUNT:
    1432                 :             :                 {
    1433   [ +  -  +  +  :         276 :                     ExpectedKeySize("Global Input Count", key, 1);
                   +  + ]
    1434                 :          30 :                     CompactSizeReader reader(input_count);
    1435         [ +  + ]:          30 :                     UnserializeFromVector(s, reader);
    1436                 :             :                     found_input_count = true;
    1437                 :             :                     break;
    1438                 :             :                 }
    1439                 :         111 :                 case PSBT_GLOBAL_OUTPUT_COUNT:
    1440                 :             :                 {
    1441   [ +  -  +  +  :         222 :                     ExpectedKeySize("Global Output Count", key, 1);
                   +  + ]
    1442                 :          12 :                     CompactSizeReader reader(output_count);
    1443         [ +  + ]:          12 :                     UnserializeFromVector(s, reader);
    1444                 :             :                     found_output_count = true;
    1445                 :             :                     break;
    1446                 :             :                 }
    1447                 :         100 :                 case PSBT_GLOBAL_TX_MODIFIABLE:
    1448                 :             :                 {
    1449   [ +  -  +  + ]:         179 :                     ExpectedKeySize("Global TX Modifiable Flags", key, 1);
    1450                 :             :                     uint8_t tx_mod;
    1451         [ +  + ]:          21 :                     UnserializeFromVector(s, tx_mod);
    1452         [ -  + ]:           2 :                     m_tx_modifiable.emplace(tx_mod);
    1453                 :             :                     break;
    1454                 :             :                 }
    1455                 :       20501 :                 case PSBT_GLOBAL_XPUB:
    1456                 :             :                 {
    1457   [ +  -  +  +  :       41002 :                     ExpectedKeySize("Global XPUB", key, BIP32_EXTKEY_WITH_VERSION_SIZE + 1);
                   +  - ]
    1458                 :             :                     // Read in the xpub from key
    1459         [ +  - ]:       20471 :                     CExtPubKey xpub;
    1460         [ +  - ]:       20471 :                     xpub.DecodeWithVersion(&key.data()[1]);
    1461   [ +  -  +  + ]:       20471 :                     if (!xpub.pubkey.IsFullyValid()) {
    1462         [ +  - ]:         128 :                        throw std::ios_base::failure("Invalid pubkey");
    1463                 :             :                     }
    1464         [ +  - ]:       20407 :                     global_xpubs.insert(xpub);
    1465                 :             :                     // Read in the keypath from stream
    1466                 :       20407 :                     KeyOriginInfo keypath;
    1467         [ +  + ]:       20407 :                     DeserializeHDKeypath(s, keypath);
    1468                 :             : 
    1469                 :             :                     // Note that we store these swapped to make searches faster.
    1470                 :             :                     // Serialization uses xpub -> keypath to enqure key uniqueness
    1471         [ +  + ]:       20347 :                     if (!m_xpubs.contains(keypath)) {
    1472                 :             :                         // Make a new set to put the xpub in
    1473   [ +  -  +  - ]:       36116 :                         m_xpubs[keypath] = {xpub};
    1474                 :             :                     } else {
    1475                 :             :                         // Insert xpub into existing set
    1476   [ +  -  +  - ]:        4578 :                         m_xpubs[keypath].insert(xpub);
    1477                 :             :                     }
    1478                 :             :                     break;
    1479                 :       20407 :                 }
    1480                 :         179 :                 case PSBT_GLOBAL_VERSION:
    1481                 :             :                 {
    1482   [ +  -  +  + ]:         192 :                     ExpectedKeySize("Global PSBT Version", key, 1);
    1483                 :             :                     uint32_t v;
    1484         [ +  + ]:         166 :                     UnserializeFromVector(s, v);
    1485                 :         154 :                     m_version = v;
    1486         [ +  + ]:         154 :                     if (*m_version > PSBT_HIGHEST_VERSION) {
    1487         [ +  - ]:          28 :                         throw std::ios_base::failure("Unsupported version number");
    1488                 :             :                     }
    1489                 :             :                     break;
    1490                 :             :                 }
    1491         [ +  + ]:        5746 :                 case PSBT_GLOBAL_PROPRIETARY:
    1492                 :             :                 {
    1493         [ +  + ]:        5746 :                     PSBTProprietary this_prop;
    1494                 :        5719 :                     skey >> this_prop.identifier;
    1495         [ +  + ]:        5719 :                     this_prop.subtype = ReadCompactSize(skey);
    1496         [ +  - ]:        5718 :                     this_prop.key = key;
    1497                 :             : 
    1498                 :        5672 :                     s >> this_prop.value;
    1499         [ +  - ]:        5672 :                     m_proprietary.insert(this_prop);
    1500                 :             :                     break;
    1501                 :        5746 :                 }
    1502                 :             :                 // Unknown stuff
    1503                 :       43739 :                 default: {
    1504                 :             :                     // Read in the value
    1505         [ +  + ]:       43739 :                     std::vector<unsigned char> val_bytes;
    1506                 :       43679 :                     s >> val_bytes;
    1507         [ +  - ]:       43679 :                     unknown.emplace(std::move(key), std::move(val_bytes));
    1508                 :       43739 :                 }
    1509                 :             :             }
    1510                 :             :         }
    1511                 :             : 
    1512                 :             :         if (!found_sep) {
    1513         [ +  - ]:         158 :             throw std::ios_base::failure("Separator is missing at the end of the global map");
    1514                 :             :         }
    1515                 :             : 
    1516         [ +  - ]:       57175 :         const uint32_t psbt_ver = GetVersion();
    1517                 :             : 
    1518                 :             :         // Check PSBT version constraints
    1519         [ +  - ]:       57175 :         if (psbt_ver == 0) {
    1520                 :             :             // Make sure that we got an unsigned tx for PSBTv0
    1521         [ +  + ]:       57175 :             if (!tx) {
    1522         [ +  - ]:         112 :                 throw std::ios_base::failure("No unsigned transaction was provided");
    1523                 :             :             }
    1524                 :             :             // Make sure no PSBTv2 fields are present
    1525         [ -  + ]:       57119 :             if (found_tx_version) {
    1526         [ #  # ]:           0 :                 throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is not allowed in PSBTv0");
    1527                 :             :             }
    1528         [ -  + ]:       57119 :             if (found_fallback_locktime) {
    1529         [ #  # ]:           0 :                 throw std::ios_base::failure("PSBT_GLOBAL_FALLBACK_LOCKTIME is not allowed in PSBTv0");
    1530                 :             :             }
    1531         [ +  + ]:       57119 :             if (found_input_count) {
    1532         [ +  - ]:           8 :                 throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is not allowed in PSBTv0");
    1533                 :             :             }
    1534         [ +  + ]:       57115 :             if (found_output_count) {
    1535         [ +  - ]:           2 :                 throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is not allowed in PSBTv0");
    1536                 :             :             }
    1537         [ -  + ]:       57114 :             if (m_tx_modifiable != std::nullopt) {
    1538         [ #  # ]:           0 :                 throw std::ios_base::failure("PSBT_GLOBAL_TX_MODIFIABLE is not allowed in PSBTv0");
    1539                 :             :             }
    1540                 :             :         }
    1541                 :             :         // Disallow v1
    1542         [ -  + ]:       57114 :         if (psbt_ver == 1) {
    1543         [ #  # ]:           0 :             throw std::ios_base::failure("There is no PSBT version 1");
    1544                 :             :         }
    1545         [ -  + ]:       57114 :         if (psbt_ver == 2) {
    1546                 :             :             // Tx version, input, and output counts are required
    1547         [ #  # ]:           0 :             if (!found_tx_version) {
    1548         [ #  # ]:           0 :                 throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is required in PSBTv2");
    1549                 :             :             }
    1550         [ #  # ]:           0 :             if (!found_input_count) {
    1551         [ #  # ]:           0 :                 throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is required in PSBTv2");
    1552                 :             :             }
    1553         [ #  # ]:           0 :             if (!found_output_count) {
    1554         [ #  # ]:           0 :                 throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is required in PSBTv2");
    1555                 :             :             }
    1556                 :             :             // Unsigned tx is disallowed
    1557         [ #  # ]:           0 :             if (tx) {
    1558         [ #  # ]:           0 :                 throw std::ios_base::failure("PSBT_GLOBAL_UNSIGNED_TX is not allowed in PSBTv2");
    1559                 :             :             }
    1560                 :             :         }
    1561         [ -  + ]:       57114 :         if (psbt_ver > 2) {
    1562         [ #  # ]:           0 :             throw std::ios_base::failure("Unknown PSBT version");
    1563                 :             :         }
    1564                 :             : 
    1565                 :             :         // Read input data
    1566                 :             :         unsigned int i = 0;
    1567   [ +  +  +  + ]:      122096 :         while (!s.empty() && i < input_count) {
    1568         [ +  - ]:       69205 :             if (psbt_ver < 2) {
    1569         [ +  - ]:       69205 :                 inputs.emplace_back(psbt_ver, tx->vin[i].prevout.hash, tx->vin[i].prevout.n, tx->vin[i].nSequence);
    1570         [ +  + ]:       69205 :                 s >> inputs.back();
    1571                 :             :             } else {
    1572         [ #  # ]:           0 :                 inputs.emplace_back(deserialize, s, psbt_ver);
    1573                 :             :             }
    1574                 :             : 
    1575                 :             :             // Make sure the non-witness utxo matches the outpoint
    1576                 :       65127 :             const PSBTInput& input = inputs.back();
    1577         [ +  + ]:       65127 :             if (input.non_witness_utxo) {
    1578         [ +  - ]:         835 :                 if (psbt_ver < 2) {
    1579         [ +  + ]:         835 :                     if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
    1580         [ +  - ]:         264 :                         throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
    1581                 :             :                     }
    1582   [ -  +  +  + ]:         703 :                     if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
    1583         [ +  - ]:          26 :                         throw std::ios_base::failure("Input specifies output index that does not exist");
    1584                 :             :                     }
    1585                 :             :                 } else {
    1586         [ #  # ]:           0 :                     if (input.non_witness_utxo->GetHash() != input.prev_txid) {
    1587         [ #  # ]:           0 :                         throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
    1588                 :             :                     }
    1589   [ #  #  #  # ]:           0 :                     if (input.prev_out >= input.non_witness_utxo->vout.size()) {
    1590         [ #  # ]:           0 :                         throw std::ios_base::failure("Input specifies output index that does not exist");
    1591                 :             :                     }
    1592                 :             :                 }
    1593                 :             :             }
    1594                 :       64982 :             ++i;
    1595                 :             :         }
    1596                 :             :         // Make sure that the number of inputs matches the number of inputs in the transaction
    1597   [ -  +  +  + ]:       52891 :         if (inputs.size() != input_count) {
    1598         [ +  - ]:         126 :             throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
    1599                 :             :         }
    1600                 :             : 
    1601                 :             :         // Read output data
    1602                 :             :         i = 0;
    1603   [ +  +  +  + ]:      148774 :         while (!s.empty() && i < output_count) {
    1604         [ +  - ]:       98004 :             if (psbt_ver < 2) {
    1605         [ +  - ]:       98004 :                 outputs.emplace_back(psbt_ver, tx->vout[i].nValue, tx->vout[i].scriptPubKey);
    1606         [ +  + ]:       98004 :                 s >> outputs.back();
    1607                 :             :             } else {
    1608         [ #  # ]:           0 :                 outputs.emplace_back(deserialize, s, psbt_ver);
    1609                 :             :             }
    1610                 :       95946 :             ++i;
    1611                 :             :         }
    1612                 :             :         // Make sure that the number of outputs matches the number of outputs in the transaction
    1613   [ -  +  +  + ]:       50770 :         if (outputs.size() != output_count) {
    1614         [ +  - ]:         178 :             throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
    1615                 :             :         }
    1616                 :       68781 :     }
    1617                 :             : 
    1618                 :             :     template <typename Stream>
    1619         [ +  + ]:       64723 :     PartiallySignedTransaction(deserialize_type, Stream& s) {
    1620         [ +  + ]:       64723 :         Unserialize(s);
    1621                 :       92807 :     }
    1622                 :             : };
    1623                 :             : 
    1624                 :             : enum class PSBTRole {
    1625                 :             :     CREATOR,
    1626                 :             :     UPDATER,
    1627                 :             :     SIGNER,
    1628                 :             :     FINALIZER,
    1629                 :             :     EXTRACTOR
    1630                 :             : };
    1631                 :             : 
    1632                 :             : std::string PSBTRoleName(PSBTRole role);
    1633                 :             : 
    1634                 :             : /** Compute a PrecomputedTransactionData object from a psbt. */
    1635                 :             : std::optional<PrecomputedTransactionData> PrecomputePSBTData(const PartiallySignedTransaction& psbt);
    1636                 :             : 
    1637                 :             : /** Checks whether a PSBTInput is already signed by checking for non-null finalized fields. */
    1638                 :             : bool PSBTInputSigned(const PSBTInput& input);
    1639                 :             : 
    1640                 :             : /** Checks whether a PSBTInput is already signed by doing script verification using final fields. */
    1641                 :             : bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
    1642                 :             : 
    1643                 :             : /** Signs a PSBTInput, verifying that all provided data matches what is being signed.
    1644                 :             :  *
    1645                 :             :  * txdata should be the output of PrecomputePSBTData (which can be shared across
    1646                 :             :  * multiple SignPSBTInput calls). If it is nullptr, a dummy signature will be created.
    1647                 :             :  **/
    1648                 :             : [[nodiscard]] PSBTError SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options, SignatureData* out_sigdata = nullptr);
    1649                 :             : 
    1650                 :             : /**  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. */
    1651                 :             : void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx);
    1652                 :             : 
    1653                 :             : /** Counts the unsigned inputs of a PSBT. */
    1654                 :             : size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt);
    1655                 :             : 
    1656                 :             : /** Updates a PSBTOutput with information from provider.
    1657                 :             :  *
    1658                 :             :  * This fills in the redeem_script, witness_script, and hd_keypaths where possible.
    1659                 :             :  */
    1660                 :             : void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index);
    1661                 :             : 
    1662                 :             : /**
    1663                 :             :  * Finalizes a PSBT if possible, combining partial signatures.
    1664                 :             :  *
    1665                 :             :  * @param[in,out] psbtx PartiallySignedTransaction to finalize
    1666                 :             :  * return True if the PSBT is now complete, false otherwise
    1667                 :             :  */
    1668                 :             : bool FinalizePSBT(PartiallySignedTransaction& psbtx);
    1669                 :             : 
    1670                 :             : /**
    1671                 :             :  * Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
    1672                 :             :  *
    1673                 :             :  * @param[in]  psbtx PartiallySignedTransaction
    1674                 :             :  * @param[out] result CMutableTransaction representing the complete transaction, if successful
    1675                 :             :  * @return True if we successfully extracted the transaction, false otherwise
    1676                 :             :  */
    1677                 :             : bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result);
    1678                 :             : 
    1679                 :             : /**
    1680                 :             :  * Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial signatures from each input.
    1681                 :             :  *
    1682                 :             :  * @param[in]  psbtxs the PSBTs to combine
    1683                 :             :  * @return     The combined PSBT or std::nullopt if the PSBTs cannot be combined
    1684                 :             :  */
    1685                 :             : [[nodiscard]] std::optional<PartiallySignedTransaction> CombinePSBTs(const std::vector<PartiallySignedTransaction>& psbtxs);
    1686                 :             : 
    1687                 :             : //! Decode a base64ed PSBT into a PartiallySignedTransaction
    1688                 :             : [[nodiscard]] util::Result<PartiallySignedTransaction> DecodeBase64PSBT(const std::string& base64_tx);
    1689                 :             : //! Decode a raw (binary blob) PSBT into a PartiallySignedTransaction
    1690                 :             : [[nodiscard]] util::Result<PartiallySignedTransaction> DecodeRawPSBT(std::span<const std::byte> tx_data);
    1691                 :             : 
    1692                 :             : #endif // BITCOIN_PSBT_H
        

Generated by: LCOV version 2.0-1