LCOV - code coverage report
Current view: top level - src - psbt.h (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 604 607 99.5 %
Date: 2023-10-05 15:40:34 Functions: 53 54 98.1 %
Branches: 749 1058 70.8 %

           Branch data     Line data    Source code
       1                 :            : // Copyright (c) 2009-2022 The Bitcoin Core developers
       2                 :            : // Distributed under the MIT software license, see the accompanying
       3                 :            : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :            : 
       5                 :            : #ifndef BITCOIN_PSBT_H
       6                 :            : #define BITCOIN_PSBT_H
       7                 :            : 
       8                 :            : #include <node/transaction.h>
       9                 :            : #include <policy/feerate.h>
      10                 :            : #include <primitives/transaction.h>
      11                 :            : #include <pubkey.h>
      12                 :            : #include <script/keyorigin.h>
      13                 :            : #include <script/sign.h>
      14                 :            : #include <script/signingprovider.h>
      15                 :            : #include <span.h>
      16                 :            : #include <streams.h>
      17                 :            : 
      18                 :            : #include <optional>
      19                 :            : 
      20                 :            : // Magic bytes
      21                 :            : static constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff};
      22                 :            : 
      23                 :            : // Global types
      24                 :            : static constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00;
      25                 :            : static constexpr uint8_t PSBT_GLOBAL_XPUB = 0x01;
      26                 :            : static constexpr uint8_t PSBT_GLOBAL_VERSION = 0xFB;
      27                 :            : static constexpr uint8_t PSBT_GLOBAL_PROPRIETARY = 0xFC;
      28                 :            : 
      29                 :            : // Input types
      30                 :            : static constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00;
      31                 :            : static constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01;
      32                 :            : static constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02;
      33                 :            : static constexpr uint8_t PSBT_IN_SIGHASH = 0x03;
      34                 :            : static constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04;
      35                 :            : static constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05;
      36                 :            : static constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06;
      37                 :            : static constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07;
      38                 :            : static constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08;
      39                 :            : static constexpr uint8_t PSBT_IN_RIPEMD160 = 0x0A;
      40                 :            : static constexpr uint8_t PSBT_IN_SHA256 = 0x0B;
      41                 :            : static constexpr uint8_t PSBT_IN_HASH160 = 0x0C;
      42                 :            : static constexpr uint8_t PSBT_IN_HASH256 = 0x0D;
      43                 :            : static constexpr uint8_t PSBT_IN_TAP_KEY_SIG = 0x13;
      44                 :            : static constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG = 0x14;
      45                 :            : static constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT = 0x15;
      46                 :            : static constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
      47                 :            : static constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY = 0x17;
      48                 :            : static constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT = 0x18;
      49                 :            : static constexpr uint8_t PSBT_IN_PROPRIETARY = 0xFC;
      50                 :            : 
      51                 :            : // Output types
      52                 :            : static constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00;
      53                 :            : static constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01;
      54                 :            : static constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02;
      55                 :            : static constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
      56                 :            : static constexpr uint8_t PSBT_OUT_TAP_TREE = 0x06;
      57                 :            : static constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
      58                 :            : static constexpr uint8_t PSBT_OUT_PROPRIETARY = 0xFC;
      59                 :            : 
      60                 :            : // The separator is 0x00. Reading this in means that the unserializer can interpret it
      61                 :            : // as a 0 length key which indicates that this is the separator. The separator has no value.
      62                 :            : static constexpr uint8_t PSBT_SEPARATOR = 0x00;
      63                 :            : 
      64                 :            : // BIP 174 does not specify a maximum file size, but we set a limit anyway
      65                 :            : // to prevent reading a stream indefinitely and running out of memory.
      66                 :            : const std::streamsize MAX_FILE_SIZE_PSBT = 100000000; // 100 MB
      67                 :            : 
      68                 :            : // PSBT version number
      69                 :            : static constexpr uint32_t PSBT_HIGHEST_VERSION = 0;
      70                 :            : 
      71                 :            : /** A structure for PSBT proprietary types */
      72         [ -  + ]:      99075 : struct PSBTProprietary
      73                 :            : {
      74                 :            :     uint64_t subtype;
      75                 :            :     std::vector<unsigned char> identifier;
      76                 :            :     std::vector<unsigned char> key;
      77                 :            :     std::vector<unsigned char> value;
      78                 :            : 
      79                 :     163429 :     bool operator<(const PSBTProprietary &b) const {
      80                 :     163429 :         return key < b.key;
      81                 :            :     }
      82                 :            :     bool operator==(const PSBTProprietary &b) const {
      83                 :            :         return key == b.key;
      84                 :            :     }
      85                 :            : };
      86                 :            : 
      87                 :            : // Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
      88                 :            : // The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
      89                 :            : template<typename Stream, typename... X>
      90                 :     141799 : void SerializeToVector(Stream& s, const X&... args)
      91                 :            : {
      92                 :     141799 :     WriteCompactSize(s, GetSerializeSizeMany(s.GetVersion(), args...));
      93                 :     141799 :     SerializeMany(s, args...);
      94                 :     141799 : }
      95                 :            : 
      96                 :            : // Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
      97                 :            : template<typename Stream, typename... X>
      98                 :     106108 : void UnserializeFromVector(Stream& s, X&... args)
      99                 :            : {
     100                 :     106108 :     size_t expected_size = ReadCompactSize(s);
     101                 :     106108 :     size_t remaining_before = s.size();
     102                 :     106108 :     UnserializeMany(s, args...);
     103                 :     106108 :     size_t remaining_after = s.size();
     104   [ +  +  +  +  :     106108 :     if (remaining_after + expected_size != remaining_before) {
          +  +  +  +  +  
          +  +  +  +  +  
                   +  + ]
     105   [ +  -  +  -  :       7140 :         throw std::ios_base::failure("Size of value was not the stated size");
          +  -  +  -  +  
          -  +  -  +  -  
                   +  - ]
     106                 :            :     }
     107                 :      98968 : }
     108                 :            : 
     109                 :            : // Deserialize bytes of given length from the stream as a KeyOriginInfo
     110                 :            : template<typename Stream>
     111                 :      46236 : KeyOriginInfo DeserializeKeyOrigin(Stream& s, uint64_t length)
     112                 :            : {
     113                 :            :     // Read in key path
     114         [ +  + ]:      46236 :     if (length % 4 || length == 0) {
     115         [ +  - ]:       1379 :         throw std::ios_base::failure("Invalid length for HD key path");
     116                 :            :     }
     117                 :            : 
     118                 :      45060 :     KeyOriginInfo hd_keypath;
     119         [ +  + ]:      45060 :     s >> hd_keypath.fingerprint;
     120         [ +  + ]:    1733004 :     for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
     121                 :            :         uint32_t index;
     122         [ +  + ]:    1688147 :         s >> index;
     123         [ +  - ]:    1687985 :         hd_keypath.path.push_back(index);
     124                 :    1687985 :     }
     125                 :      44857 :     return hd_keypath;
     126         [ +  - ]:      45060 : }
     127                 :            : 
     128                 :            : // Deserialize a length prefixed KeyOriginInfo from a stream
     129                 :            : template<typename Stream>
     130                 :      29486 : void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
     131                 :            : {
     132                 :      29486 :     hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
     133                 :      29486 : }
     134                 :            : 
     135                 :            : // Deserialize HD keypaths into a map
     136                 :            : template<typename Stream>
     137                 :      21086 : void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
     138                 :            : {
     139                 :            :     // Make sure that the key is the size of pubkey + 1
     140   [ +  +  +  + ]:      21086 :     if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
     141         [ +  - ]:       1845 :         throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
     142                 :            :     }
     143                 :            :     // Read in the pubkey from key
     144                 :      19949 :     CPubKey pubkey(key.begin() + 1, key.end());
     145         [ +  + ]:      19949 :     if (!pubkey.IsFullyValid()) {
     146         [ +  - ]:        841 :        throw std::ios_base::failure("Invalid pubkey");
     147                 :            :     }
     148         [ +  + ]:      19108 :     if (hd_keypaths.count(pubkey) > 0) {
     149         [ +  - ]:         25 :         throw std::ios_base::failure("Duplicate Key, pubkey derivation path already provided");
     150                 :            :     }
     151                 :            : 
     152                 :      19083 :     KeyOriginInfo keypath;
     153         [ +  + ]:      19083 :     DeserializeHDKeypath(s, keypath);
     154                 :            : 
     155                 :            :     // Add to map
     156         [ +  - ]:      18375 :     hd_keypaths.emplace(pubkey, std::move(keypath));
     157                 :      19083 : }
     158                 :            : 
     159                 :            : // Serialize a KeyOriginInfo to a stream
     160                 :            : template<typename Stream>
     161                 :      24685 : void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
     162                 :            : {
     163                 :      24685 :     s << hd_keypath.fingerprint;
     164   [ +  +  +  + ]:    1386221 :     for (const auto& path : hd_keypath.path) {
     165                 :    1361536 :         s << path;
     166                 :            :     }
     167                 :      24685 : }
     168                 :            : 
     169                 :            : // Serialize a length prefixed KeyOriginInfo to a stream
     170                 :            : template<typename Stream>
     171                 :      15786 : void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
     172                 :            : {
     173                 :      15786 :     WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
     174         [ +  - ]:      15786 :     SerializeKeyOrigin(s, hd_keypath);
     175                 :      15786 : }
     176                 :            : 
     177                 :            : // Serialize HD keypaths to a stream from a map
     178                 :            : template<typename Stream>
     179                 :     126616 : void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
     180                 :            : {
     181         [ +  + ]:     138366 :     for (const auto& keypath_pair : hd_keypaths) {
     182         [ +  + ]:      11853 :         if (!keypath_pair.first.IsValid()) {
     183         [ +  - ]:        103 :             throw std::ios_base::failure("Invalid CPubKey being serialized");
     184                 :            :         }
     185                 :      11750 :         SerializeToVector(s, type, Span{keypath_pair.first});
     186         [ +  - ]:      11750 :         SerializeHDKeypath(s, keypath_pair.second);
     187                 :            :     }
     188                 :     126513 : }
     189                 :            : 
     190                 :            : /** A structure for PSBTs which contain per-input information */
     191   [ +  -  +  -  :     187485 : struct PSBTInput
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
                -  -  + ]
     192                 :            : {
     193                 :            :     CTransactionRef non_witness_utxo;
     194                 :            :     CTxOut witness_utxo;
     195                 :            :     CScript redeem_script;
     196                 :            :     CScript witness_script;
     197                 :            :     CScript final_script_sig;
     198                 :            :     CScriptWitness final_script_witness;
     199                 :            :     std::map<CPubKey, KeyOriginInfo> hd_keypaths;
     200                 :            :     std::map<CKeyID, SigPair> partial_sigs;
     201                 :            :     std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
     202                 :            :     std::map<uint256, std::vector<unsigned char>> sha256_preimages;
     203                 :            :     std::map<uint160, std::vector<unsigned char>> hash160_preimages;
     204                 :            :     std::map<uint256, std::vector<unsigned char>> hash256_preimages;
     205                 :            : 
     206                 :            :     // Taproot fields
     207                 :            :     std::vector<unsigned char> m_tap_key_sig;
     208                 :            :     std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
     209                 :            :     std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
     210                 :            :     std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
     211                 :            :     XOnlyPubKey m_tap_internal_key;
     212                 :            :     uint256 m_tap_merkle_root;
     213                 :            : 
     214                 :            :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
     215                 :            :     std::set<PSBTProprietary> m_proprietary;
     216                 :            :     std::optional<int> sighash_type;
     217                 :            : 
     218                 :            :     bool IsNull() const;
     219                 :            :     void FillSignatureData(SignatureData& sigdata) const;
     220                 :            :     void FromSignatureData(const SignatureData& sigdata);
     221                 :            :     void Merge(const PSBTInput& input);
     222   [ +  -  +  -  :     121329 :     PSBTInput() {}
          +  -  +  -  -  
             +  +  -  +  
                      - ]
     223                 :            : 
     224                 :            :     template <typename Stream>
     225                 :      57549 :     inline void Serialize(Stream& s) const {
     226                 :            :         // Write the utxo
     227         [ +  + ]:      57549 :         if (non_witness_utxo) {
     228                 :        557 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_NON_WITNESS_UTXO));
     229                 :        557 :             OverrideStream<Stream> os{&s, s.GetVersion() | SERIALIZE_TRANSACTION_NO_WITNESS};
     230                 :        557 :             SerializeToVector(os, non_witness_utxo);
     231                 :        557 :         }
     232         [ +  + ]:      57549 :         if (!witness_utxo.IsNull()) {
     233                 :       1492 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESS_UTXO));
     234                 :       1492 :             SerializeToVector(s, witness_utxo);
     235                 :       1492 :         }
     236                 :            : 
     237   [ +  +  +  + ]:      57549 :         if (final_script_sig.empty() && final_script_witness.IsNull()) {
     238                 :            :             // Write any partial signatures
     239         [ +  + ]:      62731 :             for (auto sig_pair : partial_sigs) {
     240   [ +  -  +  -  :       6216 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), Span{sig_pair.second.first});
                   +  - ]
     241         [ +  - ]:       6216 :                 s << sig_pair.second.second;
     242                 :       6216 :             }
     243                 :            : 
     244                 :            :             // Write the sighash type
     245         [ +  + ]:      56515 :             if (sighash_type != std::nullopt) {
     246                 :         81 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_SIGHASH));
     247                 :         81 :                 SerializeToVector(s, *sighash_type);
     248                 :         81 :             }
     249                 :            : 
     250                 :            :             // Write the redeem script
     251         [ +  + ]:      56515 :             if (!redeem_script.empty()) {
     252                 :       1195 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_REDEEMSCRIPT));
     253                 :       1195 :                 s << redeem_script;
     254                 :       1195 :             }
     255                 :            : 
     256                 :            :             // Write the witness script
     257         [ +  + ]:      56515 :             if (!witness_script.empty()) {
     258                 :        634 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESSSCRIPT));
     259                 :        634 :                 s << witness_script;
     260                 :        634 :             }
     261                 :            : 
     262                 :            :             // Write any hd keypaths
     263                 :      56515 :             SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_IN_BIP32_DERIVATION));
     264                 :            : 
     265                 :            :             // Write any ripemd160 preimage
     266         [ +  + ]:      60736 :             for (const auto& [hash, preimage] : ripemd160_preimages) {
     267                 :       8442 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_RIPEMD160), Span{hash});
     268                 :       8442 :                 s << preimage;
     269                 :            :             }
     270                 :            : 
     271                 :            :             // Write any sha256 preimage
     272         [ +  + ]:      63382 :             for (const auto& [hash, preimage] : sha256_preimages) {
     273                 :      13734 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_SHA256), Span{hash});
     274                 :      13734 :                 s << preimage;
     275                 :            :             }
     276                 :            : 
     277                 :            :             // Write any hash160 preimage
     278         [ +  + ]:      58856 :             for (const auto& [hash, preimage] : hash160_preimages) {
     279                 :       4682 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH160), Span{hash});
     280                 :       4682 :                 s << preimage;
     281                 :            :             }
     282                 :            : 
     283                 :            :             // Write any hash256 preimage
     284         [ +  + ]:      58555 :             for (const auto& [hash, preimage] : hash256_preimages) {
     285                 :       4080 :                 SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH256), Span{hash});
     286                 :       4080 :                 s << preimage;
     287                 :            :             }
     288                 :            : 
     289                 :            :             // Write taproot key sig
     290         [ +  + ]:      56515 :             if (!m_tap_key_sig.empty()) {
     291                 :         76 :                 SerializeToVector(s, PSBT_IN_TAP_KEY_SIG);
     292                 :         76 :                 s << m_tap_key_sig;
     293                 :         76 :             }
     294                 :            : 
     295                 :            :             // Write taproot script sigs
     296         [ +  + ]:      62902 :             for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
     297                 :      12774 :                 const auto& [xonly, leaf_hash] = pubkey_leaf;
     298                 :      12774 :                 SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
     299                 :      12774 :                 s << sig;
     300                 :            :             }
     301                 :            : 
     302                 :            :             // Write taproot leaf scripts
     303         [ +  + ]:      67414 :             for (const auto& [leaf, control_blocks] : m_tap_scripts) {
     304                 :      38111 :                 const auto& [script, leaf_ver] = leaf;
     305         [ +  + ]:      24505 :                 for (const auto& control_block : control_blocks) {
     306                 :      13606 :                     SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, Span{control_block});
     307   [ +  -  +  - ]:      27212 :                     std::vector<unsigned char> value_v(script.begin(), script.end());
     308         [ +  - ]:      13606 :                     value_v.push_back((uint8_t)leaf_ver);
     309         [ +  - ]:      13606 :                     s << value_v;
     310                 :      13606 :                 }
     311                 :            :             }
     312                 :            : 
     313                 :            :             // Write taproot bip32 keypaths
     314         [ +  + ]:      58416 :             for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
     315                 :       1901 :                 const auto& [leaf_hashes, origin] = leaf_origin;
     316                 :       3802 :                 SerializeToVector(s, PSBT_IN_TAP_BIP32_DERIVATION, xonly);
     317                 :       1901 :                 std::vector<unsigned char> value;
     318         [ +  - ]:       1901 :                 CVectorWriter s_value{s.GetVersion(), value, 0};
     319         [ +  - ]:       1901 :                 s_value << leaf_hashes;
     320   [ +  -  +  - ]:       1901 :                 SerializeKeyOrigin(s_value, origin);
     321         [ +  - ]:       1901 :                 s << value;
     322                 :       1901 :             }
     323                 :            : 
     324                 :            :             // Write taproot internal key
     325         [ +  + ]:      56515 :             if (!m_tap_internal_key.IsNull()) {
     326                 :         73 :                 SerializeToVector(s, PSBT_IN_TAP_INTERNAL_KEY);
     327         [ +  - ]:         73 :                 s << ToByteVector(m_tap_internal_key);
     328                 :         73 :             }
     329                 :            : 
     330                 :            :             // Write taproot merkle root
     331         [ +  + ]:      56515 :             if (!m_tap_merkle_root.IsNull()) {
     332                 :        208 :                 SerializeToVector(s, PSBT_IN_TAP_MERKLE_ROOT);
     333                 :        208 :                 SerializeToVector(s, m_tap_merkle_root);
     334                 :        208 :             }
     335                 :      56515 :         }
     336                 :            : 
     337                 :            :         // Write script sig
     338         [ +  + ]:      57549 :         if (!final_script_sig.empty()) {
     339                 :        563 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTSIG));
     340                 :        563 :             s << final_script_sig;
     341                 :        563 :         }
     342                 :            :         // write script witness
     343         [ +  + ]:      57549 :         if (!final_script_witness.IsNull()) {
     344                 :        471 :             SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTWITNESS));
     345                 :        471 :             SerializeToVector(s, final_script_witness.stack);
     346                 :        471 :         }
     347                 :            : 
     348                 :            :         // Write proprietary things
     349         [ +  + ]:      62741 :         for (const auto& entry : m_proprietary) {
     350                 :       5192 :             s << entry.key;
     351                 :       5192 :             s << entry.value;
     352                 :            :         }
     353                 :            : 
     354                 :            :         // Write unknown things
     355         [ +  + ]:     105904 :         for (auto& entry : unknown) {
     356                 :      48355 :             s << entry.first;
     357                 :      48355 :             s << entry.second;
     358                 :            :         }
     359                 :            : 
     360                 :      57549 :         s << PSBT_SEPARATOR;
     361                 :      57549 :     }
     362                 :            : 
     363                 :            : 
     364                 :            :     template <typename Stream>
     365                 :     117234 :     inline void Unserialize(Stream& s) {
     366                 :            :         // Used for duplicate key detection
     367                 :     117234 :         std::set<std::vector<unsigned char>> key_lookup;
     368                 :            : 
     369                 :            :         // Read loop
     370                 :     117234 :         bool found_sep = false;
     371         [ +  + ]:     326291 :         while(!s.empty()) {
     372                 :            :             // Read
     373                 :     326112 :             std::vector<unsigned char> key;
     374         [ +  + ]:     326112 :             s >> key;
     375                 :            : 
     376                 :            :             // the key is empty if that was actually a separator byte
     377                 :            :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
     378         [ +  + ]:     322010 :             if (key.empty()) {
     379                 :      95061 :                 found_sep = true;
     380                 :      95061 :                 break;
     381                 :            :             }
     382                 :            : 
     383                 :            :             // Type is compact size uint at beginning of key
     384   [ +  -  +  - ]:     226949 :             SpanReader skey{s.GetVersion(), key};
     385         [ +  + ]:     226949 :             uint64_t type = ReadCompactSize(skey);
     386                 :            : 
     387                 :            :             // Do stuff based on type
     388   [ +  +  +  +  :     226807 :             switch(type) {
          +  +  +  +  +  
          +  +  +  +  +  
          +  +  +  +  +  
                   +  + ]
     389                 :            :                 case PSBT_IN_NON_WITNESS_UTXO:
     390                 :            :                 {
     391   [ +  -  +  + ]:       4230 :                     if (!key_lookup.emplace(key).second) {
     392         [ +  - ]:        472 :                         throw std::ios_base::failure("Duplicate Key, input non-witness utxo already provided");
     393         [ +  + ]:       3758 :                     } else if (key.size() != 1) {
     394         [ +  - ]:        947 :                         throw std::ios_base::failure("Non-witness utxo key is more than one byte type");
     395                 :            :                     }
     396                 :            :                     // Set the stream to unserialize with witness since this is always a valid network transaction
     397         [ +  - ]:       2811 :                     OverrideStream<Stream> os{&s, s.GetVersion() & ~SERIALIZE_TRANSACTION_NO_WITNESS};
     398         [ +  + ]:       2811 :                     UnserializeFromVector(os, non_witness_utxo);
     399                 :       1400 :                     break;
     400                 :            :                 }
     401                 :            :                 case PSBT_IN_WITNESS_UTXO:
     402   [ +  -  +  + ]:       4574 :                     if (!key_lookup.emplace(key).second) {
     403         [ +  - ]:        185 :                         throw std::ios_base::failure("Duplicate Key, input witness utxo already provided");
     404         [ +  + ]:       4389 :                     } else if (key.size() != 1) {
     405         [ +  - ]:        147 :                         throw std::ios_base::failure("Witness utxo key is more than one byte type");
     406                 :            :                     }
     407         [ +  + ]:       4242 :                     UnserializeFromVector(s, witness_utxo);
     408                 :       3959 :                     break;
     409                 :            :                 case PSBT_IN_PARTIAL_SIG:
     410                 :            :                 {
     411                 :            :                     // Make sure that the key is the size of pubkey + 1
     412   [ +  +  +  + ]:      15219 :                     if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
     413         [ +  - ]:        611 :                         throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
     414                 :            :                     }
     415                 :            :                     // Read in the pubkey from key
     416         [ +  - ]:      14608 :                     CPubKey pubkey(key.begin() + 1, key.end());
     417   [ +  -  +  + ]:      14608 :                     if (!pubkey.IsFullyValid()) {
     418         [ +  - ]:        437 :                        throw std::ios_base::failure("Invalid pubkey");
     419                 :            :                     }
     420   [ +  -  +  -  :      14171 :                     if (partial_sigs.count(pubkey.GetID()) > 0) {
                   +  + ]
     421         [ +  - ]:         74 :                         throw std::ios_base::failure("Duplicate Key, input partial signature for pubkey already provided");
     422                 :            :                     }
     423                 :            : 
     424                 :            :                     // Read in the signature from value
     425                 :      14097 :                     std::vector<unsigned char> sig;
     426         [ +  + ]:      14097 :                     s >> sig;
     427                 :            : 
     428                 :            :                     // Add to list
     429   [ +  -  +  -  :      13920 :                     partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
                   +  - ]
     430                 :            :                     break;
     431                 :      14097 :                 }
     432                 :            :                 case PSBT_IN_SIGHASH:
     433   [ +  -  +  + ]:       1095 :                     if (!key_lookup.emplace(key).second) {
     434         [ +  - ]:        187 :                         throw std::ios_base::failure("Duplicate Key, input sighash type already provided");
     435         [ +  + ]:        908 :                     } else if (key.size() != 1) {
     436         [ +  - ]:        431 :                         throw std::ios_base::failure("Sighash type key is more than one byte type");
     437                 :            :                     }
     438                 :            :                     int sighash;
     439         [ +  + ]:        477 :                     UnserializeFromVector(s, sighash);
     440         [ +  - ]:        278 :                     sighash_type = sighash;
     441                 :        278 :                     break;
     442                 :            :                 case PSBT_IN_REDEEMSCRIPT:
     443                 :            :                 {
     444   [ +  -  +  + ]:       3936 :                     if (!key_lookup.emplace(key).second) {
     445         [ +  - ]:        197 :                         throw std::ios_base::failure("Duplicate Key, input redeemScript already provided");
     446         [ +  + ]:       3739 :                     } else if (key.size() != 1) {
     447         [ +  - ]:        183 :                         throw std::ios_base::failure("Input redeemScript key is more than one byte type");
     448                 :            :                     }
     449         [ +  + ]:       3556 :                     s >> redeem_script;
     450                 :       3284 :                     break;
     451                 :            :                 }
     452                 :            :                 case PSBT_IN_WITNESSSCRIPT:
     453                 :            :                 {
     454   [ +  -  +  + ]:       1985 :                     if (!key_lookup.emplace(key).second) {
     455         [ +  - ]:         73 :                         throw std::ios_base::failure("Duplicate Key, input witnessScript already provided");
     456         [ +  + ]:       1912 :                     } else if (key.size() != 1) {
     457         [ +  - ]:        423 :                         throw std::ios_base::failure("Input witnessScript key is more than one byte type");
     458                 :            :                     }
     459         [ +  + ]:       1489 :                     s >> witness_script;
     460                 :       1453 :                     break;
     461                 :            :                 }
     462                 :            :                 case PSBT_IN_BIP32_DERIVATION:
     463                 :            :                 {
     464         [ +  + ]:       3484 :                     DeserializeHDKeypaths(s, key, hd_keypaths);
     465                 :       3401 :                     break;
     466                 :            :                 }
     467                 :            :                 case PSBT_IN_SCRIPTSIG:
     468                 :            :                 {
     469   [ +  -  +  + ]:       1643 :                     if (!key_lookup.emplace(key).second) {
     470         [ +  - ]:         70 :                         throw std::ios_base::failure("Duplicate Key, input final scriptSig already provided");
     471         [ +  + ]:       1573 :                     } else if (key.size() != 1) {
     472         [ +  - ]:         40 :                         throw std::ios_base::failure("Final scriptSig key is more than one byte type");
     473                 :            :                     }
     474         [ +  + ]:       1533 :                     s >> final_script_sig;
     475                 :       1525 :                     break;
     476                 :            :                 }
     477                 :            :                 case PSBT_IN_SCRIPTWITNESS:
     478                 :            :                 {
     479   [ +  -  +  + ]:       1252 :                     if (!key_lookup.emplace(key).second) {
     480         [ +  - ]:         50 :                         throw std::ios_base::failure("Duplicate Key, input final scriptWitness already provided");
     481         [ +  + ]:       1202 :                     } else if (key.size() != 1) {
     482         [ +  - ]:        236 :                         throw std::ios_base::failure("Final scriptWitness key is more than one byte type");
     483                 :            :                     }
     484         [ +  + ]:        966 :                     UnserializeFromVector(s, final_script_witness.stack);
     485                 :        805 :                     break;
     486                 :            :                 }
     487                 :            :                 case PSBT_IN_RIPEMD160:
     488                 :            :                 {
     489                 :            :                     // Make sure that the key is the size of a ripemd160 hash + 1
     490         [ +  + ]:       7158 :                     if (key.size() != CRIPEMD160::OUTPUT_SIZE + 1) {
     491         [ +  - ]:        159 :                         throw std::ios_base::failure("Size of key was not the expected size for the type ripemd160 preimage");
     492                 :            :                     }
     493                 :            :                     // Read in the hash from key
     494         [ +  - ]:       6999 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     495   [ +  -  +  - ]:       6999 :                     uint160 hash(hash_vec);
     496   [ +  -  +  + ]:       6999 :                     if (ripemd160_preimages.count(hash) > 0) {
     497         [ +  - ]:         91 :                         throw std::ios_base::failure("Duplicate Key, input ripemd160 preimage already provided");
     498                 :            :                     }
     499                 :            : 
     500                 :            :                     // Read in the preimage from value
     501                 :       6908 :                     std::vector<unsigned char> preimage;
     502         [ +  + ]:       6908 :                     s >> preimage;
     503                 :            : 
     504                 :            :                     // Add to preimages list
     505         [ +  - ]:       6757 :                     ripemd160_preimages.emplace(hash, std::move(preimage));
     506                 :            :                     break;
     507                 :       6999 :                 }
     508                 :            :                 case PSBT_IN_SHA256:
     509                 :            :                 {
     510                 :            :                     // Make sure that the key is the size of a sha256 hash + 1
     511         [ +  + ]:      10806 :                     if (key.size() != CSHA256::OUTPUT_SIZE + 1) {
     512         [ +  - ]:         72 :                         throw std::ios_base::failure("Size of key was not the expected size for the type sha256 preimage");
     513                 :            :                     }
     514                 :            :                     // Read in the hash from key
     515         [ +  - ]:      10734 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     516   [ +  -  +  - ]:      10734 :                     uint256 hash(hash_vec);
     517   [ +  -  +  + ]:      10734 :                     if (sha256_preimages.count(hash) > 0) {
     518         [ +  - ]:         56 :                         throw std::ios_base::failure("Duplicate Key, input sha256 preimage already provided");
     519                 :            :                     }
     520                 :            : 
     521                 :            :                     // Read in the preimage from value
     522                 :      10678 :                     std::vector<unsigned char> preimage;
     523         [ +  + ]:      10678 :                     s >> preimage;
     524                 :            : 
     525                 :            :                     // Add to preimages list
     526         [ +  - ]:      10526 :                     sha256_preimages.emplace(hash, std::move(preimage));
     527                 :            :                     break;
     528                 :      10734 :                 }
     529                 :            :                 case PSBT_IN_HASH160:
     530                 :            :                 {
     531                 :            :                     // Make sure that the key is the size of a hash160 hash + 1
     532         [ +  + ]:       5909 :                     if (key.size() != CHash160::OUTPUT_SIZE + 1) {
     533         [ +  - ]:         71 :                         throw std::ios_base::failure("Size of key was not the expected size for the type hash160 preimage");
     534                 :            :                     }
     535                 :            :                     // Read in the hash from key
     536         [ +  - ]:       5838 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     537   [ +  -  +  - ]:       5838 :                     uint160 hash(hash_vec);
     538   [ +  -  +  + ]:       5838 :                     if (hash160_preimages.count(hash) > 0) {
     539         [ +  - ]:         82 :                         throw std::ios_base::failure("Duplicate Key, input hash160 preimage already provided");
     540                 :            :                     }
     541                 :            : 
     542                 :            :                     // Read in the preimage from value
     543                 :       5756 :                     std::vector<unsigned char> preimage;
     544         [ +  + ]:       5756 :                     s >> preimage;
     545                 :            : 
     546                 :            :                     // Add to preimages list
     547         [ +  - ]:       5612 :                     hash160_preimages.emplace(hash, std::move(preimage));
     548                 :            :                     break;
     549                 :       5838 :                 }
     550                 :            :                 case PSBT_IN_HASH256:
     551                 :            :                 {
     552                 :            :                     // Make sure that the key is the size of a hash256 hash + 1
     553         [ +  + ]:       4701 :                     if (key.size() != CHash256::OUTPUT_SIZE + 1) {
     554         [ +  - ]:        113 :                         throw std::ios_base::failure("Size of key was not the expected size for the type hash256 preimage");
     555                 :            :                     }
     556                 :            :                     // Read in the hash from key
     557         [ +  - ]:       4588 :                     std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
     558   [ +  -  +  - ]:       4588 :                     uint256 hash(hash_vec);
     559   [ +  -  +  + ]:       4588 :                     if (hash256_preimages.count(hash) > 0) {
     560         [ +  - ]:         30 :                         throw std::ios_base::failure("Duplicate Key, input hash256 preimage already provided");
     561                 :            :                     }
     562                 :            : 
     563                 :            :                     // Read in the preimage from value
     564                 :       4558 :                     std::vector<unsigned char> preimage;
     565         [ +  + ]:       4558 :                     s >> preimage;
     566                 :            : 
     567                 :            :                     // Add to preimages list
     568         [ +  - ]:       4300 :                     hash256_preimages.emplace(hash, std::move(preimage));
     569                 :            :                     break;
     570                 :       4588 :                 }
     571                 :            :                 case PSBT_IN_TAP_KEY_SIG:
     572                 :            :                 {
     573   [ +  -  +  + ]:       1452 :                     if (!key_lookup.emplace(key).second) {
     574         [ +  - ]:        150 :                         throw std::ios_base::failure("Duplicate Key, input Taproot key signature already provided");
     575         [ +  + ]:       1302 :                     } else if (key.size() != 1) {
     576         [ +  - ]:        179 :                         throw std::ios_base::failure("Input Taproot key signature key is more than one byte type");
     577                 :            :                     }
     578         [ +  + ]:       1123 :                     s >> m_tap_key_sig;
     579         [ +  + ]:       1078 :                     if (m_tap_key_sig.size() < 64) {
     580         [ +  - ]:        313 :                         throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
     581         [ +  + ]:        765 :                     } else if (m_tap_key_sig.size() > 65) {
     582         [ +  - ]:        275 :                         throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
     583                 :            :                     }
     584                 :        490 :                     break;
     585                 :            :                 }
     586                 :            :                 case PSBT_IN_TAP_SCRIPT_SIG:
     587                 :            :                 {
     588   [ +  -  +  + ]:      12464 :                     if (!key_lookup.emplace(key).second) {
     589         [ +  - ]:        196 :                         throw std::ios_base::failure("Duplicate Key, input Taproot script signature already provided");
     590         [ +  + ]:      12268 :                     } else if (key.size() != 65) {
     591         [ +  - ]:        266 :                         throw std::ios_base::failure("Input Taproot script signature key is not 65 bytes");
     592                 :            :                     }
     593   [ +  -  +  - ]:      12002 :                     SpanReader s_key{s.GetVersion(), Span{key}.subspan(1)};
     594         [ +  - ]:      12002 :                     XOnlyPubKey xonly;
     595         [ +  - ]:      12002 :                     uint256 hash;
     596         [ +  - ]:      12002 :                     s_key >> xonly;
     597         [ +  - ]:      12002 :                     s_key >> hash;
     598                 :      12002 :                     std::vector<unsigned char> sig;
     599         [ +  + ]:      12002 :                     s >> sig;
     600         [ +  + ]:      11785 :                     if (sig.size() < 64) {
     601         [ +  - ]:        585 :                         throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
     602         [ +  + ]:      11200 :                     } else if (sig.size() > 65) {
     603         [ +  - ]:        299 :                         throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
     604                 :            :                     }
     605   [ +  -  +  - ]:      10901 :                     m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
     606                 :            :                     break;
     607                 :      12002 :                 }
     608                 :            :                 case PSBT_IN_TAP_LEAF_SCRIPT:
     609                 :            :                 {
     610   [ +  -  +  + ]:      33630 :                     if (!key_lookup.emplace(key).second) {
     611         [ +  - ]:        124 :                         throw std::ios_base::failure("Duplicate Key, input Taproot leaf script already provided");
     612         [ +  + ]:      33506 :                     } else if (key.size() < 34) {
     613         [ +  - ]:        515 :                         throw std::ios_base::failure("Taproot leaf script key is not at least 34 bytes");
     614         [ +  + ]:      32991 :                     } else if ((key.size() - 2) % 32 != 0) {
     615         [ +  - ]:        848 :                         throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
     616                 :            :                     }
     617                 :      32143 :                     std::vector<unsigned char> script_v;
     618         [ +  + ]:      32143 :                     s >> script_v;
     619         [ +  + ]:      31936 :                     if (script_v.empty()) {
     620         [ +  - ]:        251 :                         throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
     621                 :            :                     }
     622                 :      31685 :                     uint8_t leaf_ver = script_v.back();
     623                 :      31685 :                     script_v.pop_back();
     624         [ +  - ]:      31685 :                     const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
     625   [ +  -  +  -  :      31685 :                     m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
                   +  - ]
     626                 :            :                     break;
     627                 :      32143 :                 }
     628                 :            :                 case PSBT_IN_TAP_BIP32_DERIVATION:
     629                 :            :                 {
     630   [ +  -  +  + ]:       4407 :                     if (!key_lookup.emplace(key).second) {
     631         [ +  - ]:         70 :                         throw std::ios_base::failure("Duplicate Key, input Taproot BIP32 keypath already provided");
     632         [ +  + ]:       4337 :                     } else if (key.size() != 33) {
     633         [ +  - ]:        502 :                         throw std::ios_base::failure("Input Taproot BIP32 keypath key is not at 33 bytes");
     634                 :            :                     }
     635   [ +  -  +  - ]:       3835 :                     SpanReader s_key{s.GetVersion(), Span{key}.subspan(1)};
     636         [ +  - ]:       3835 :                     XOnlyPubKey xonly;
     637         [ +  - ]:       3835 :                     s_key >> xonly;
     638                 :       3835 :                     std::set<uint256> leaf_hashes;
     639         [ +  + ]:       3835 :                     uint64_t value_len = ReadCompactSize(s);
     640                 :       3773 :                     size_t before_hashes = s.size();
     641         [ +  + ]:       3773 :                     s >> leaf_hashes;
     642                 :       3253 :                     size_t after_hashes = s.size();
     643                 :       3253 :                     size_t hashes_len = before_hashes - after_hashes;
     644         [ +  + ]:       3253 :                     if (hashes_len > value_len) {
     645         [ +  - ]:        122 :                         throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
     646                 :            :                     }
     647                 :       3131 :                     size_t origin_len = value_len - hashes_len;
     648   [ +  +  +  -  :       3131 :                     m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
                   +  - ]
     649                 :            :                     break;
     650                 :       3835 :                 }
     651                 :            :                 case PSBT_IN_TAP_INTERNAL_KEY:
     652                 :            :                 {
     653   [ +  -  +  + ]:        311 :                     if (!key_lookup.emplace(key).second) {
     654         [ +  - ]:         53 :                         throw std::ios_base::failure("Duplicate Key, input Taproot internal key already provided");
     655         [ +  + ]:        258 :                     } else if (key.size() != 1) {
     656         [ +  - ]:         90 :                         throw std::ios_base::failure("Input Taproot internal key key is more than one byte type");
     657                 :            :                     }
     658         [ +  + ]:        168 :                     UnserializeFromVector(s, m_tap_internal_key);
     659                 :        148 :                     break;
     660                 :            :                 }
     661                 :            :                 case PSBT_IN_TAP_MERKLE_ROOT:
     662                 :            :                 {
     663   [ +  -  +  + ]:        572 :                     if (!key_lookup.emplace(key).second) {
     664         [ +  - ]:         70 :                         throw std::ios_base::failure("Duplicate Key, input Taproot merkle root already provided");
     665         [ +  + ]:        502 :                     } else if (key.size() != 1) {
     666         [ +  - ]:         83 :                         throw std::ios_base::failure("Input Taproot merkle root key is more than one byte type");
     667                 :            :                     }
     668         [ +  + ]:        419 :                     UnserializeFromVector(s, m_tap_merkle_root);
     669                 :        340 :                     break;
     670                 :            :                 }
     671                 :            :                 case PSBT_IN_PROPRIETARY:
     672                 :            :                 {
     673                 :       8921 :                     PSBTProprietary this_prop;
     674         [ +  + ]:       8921 :                     skey >> this_prop.identifier;
     675         [ +  - ]:       8518 :                     this_prop.subtype = ReadCompactSize(skey);
     676         [ +  - ]:       8518 :                     this_prop.key = key;
     677                 :            : 
     678   [ +  -  +  + ]:       8518 :                     if (m_proprietary.count(this_prop) > 0) {
     679         [ +  - ]:        129 :                         throw std::ios_base::failure("Duplicate Key, proprietary key already found");
     680                 :            :                     }
     681         [ +  + ]:       8389 :                     s >> this_prop.value;
     682         [ +  - ]:       8282 :                     m_proprietary.insert(this_prop);
     683                 :            :                     break;
     684                 :       8921 :                 }
     685                 :            :                 // Unknown stuff
     686                 :            :                 default:
     687   [ +  -  +  + ]:      99058 :                     if (unknown.count(key) > 0) {
     688         [ +  - ]:        223 :                         throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
     689                 :            :                     }
     690                 :            :                     // Read in the value
     691                 :      98835 :                     std::vector<unsigned char> val_bytes;
     692         [ +  + ]:      98835 :                     s >> val_bytes;
     693         [ +  - ]:      97074 :                     unknown.emplace(std::move(key), std::move(val_bytes));
     694                 :            :                     break;
     695                 :      98835 :             }
     696         [ +  + ]:     326112 :         }
     697                 :            : 
     698         [ +  + ]:      95240 :         if (!found_sep) {
     699         [ +  - ]:        179 :             throw std::ios_base::failure("Separator is missing at the end of an input map");
     700                 :            :         }
     701                 :     139228 :     }
     702                 :            : 
     703                 :            :     template <typename Stream>
     704                 :            :     PSBTInput(deserialize_type, Stream& s) {
     705                 :            :         Unserialize(s);
     706                 :            :     }
     707                 :            : };
     708                 :            : 
     709                 :            : /** A structure for PSBTs which contains per output information */
     710   [ +  -  +  -  :     159159 : struct PSBTOutput
          +  -  +  -  -  
                      + ]
     711                 :            : {
     712                 :            :     CScript redeem_script;
     713                 :            :     CScript witness_script;
     714                 :            :     std::map<CPubKey, KeyOriginInfo> hd_keypaths;
     715                 :            :     XOnlyPubKey m_tap_internal_key;
     716                 :            :     std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
     717                 :            :     std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
     718                 :            :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
     719                 :            :     std::set<PSBTProprietary> m_proprietary;
     720                 :            : 
     721                 :            :     bool IsNull() const;
     722                 :            :     void FillSignatureData(SignatureData& sigdata) const;
     723                 :            :     void FromSignatureData(const SignatureData& sigdata);
     724                 :            :     void Merge(const PSBTOutput& output);
     725   [ +  -  -  + ]:     110502 :     PSBTOutput() {}
     726                 :            : 
     727                 :            :     template <typename Stream>
     728                 :      69071 :     inline void Serialize(Stream& s) const {
     729                 :            :         // Write the redeem script
     730         [ +  + ]:      69071 :         if (!redeem_script.empty()) {
     731                 :       1223 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_REDEEMSCRIPT));
     732                 :       1223 :             s << redeem_script;
     733                 :       1223 :         }
     734                 :            : 
     735                 :            :         // Write the witness script
     736         [ +  + ]:      69071 :         if (!witness_script.empty()) {
     737                 :        567 :             SerializeToVector(s, CompactSizeWriter(PSBT_OUT_WITNESSSCRIPT));
     738                 :        567 :             s << witness_script;
     739                 :        567 :         }
     740                 :            : 
     741                 :            :         // Write any hd keypaths
     742                 :      69071 :         SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_OUT_BIP32_DERIVATION));
     743                 :            : 
     744                 :            :         // Write proprietary things
     745         [ +  + ]:      73071 :         for (const auto& entry : m_proprietary) {
     746                 :       4000 :             s << entry.key;
     747                 :       4000 :             s << entry.value;
     748                 :            :         }
     749                 :            : 
     750                 :            :         // Write taproot internal key
     751         [ +  + ]:      69071 :         if (!m_tap_internal_key.IsNull()) {
     752                 :        686 :             SerializeToVector(s, PSBT_OUT_TAP_INTERNAL_KEY);
     753         [ +  - ]:        686 :             s << ToByteVector(m_tap_internal_key);
     754                 :        686 :         }
     755                 :            : 
     756                 :            :         // Write taproot tree
     757         [ +  + ]:      69071 :         if (!m_tap_tree.empty()) {
     758                 :        969 :             SerializeToVector(s, PSBT_OUT_TAP_TREE);
     759                 :        969 :             std::vector<unsigned char> value;
     760         [ +  - ]:        969 :             CVectorWriter s_value{s.GetVersion(), value, 0};
     761         [ +  + ]:       3621 :             for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
     762         [ +  - ]:       2652 :                 s_value << depth;
     763         [ +  - ]:       2652 :                 s_value << leaf_ver;
     764         [ +  - ]:       2652 :                 s_value << script;
     765                 :            :             }
     766         [ +  - ]:        969 :             s << value;
     767                 :        969 :         }
     768                 :            : 
     769                 :            :         // Write taproot bip32 keypaths
     770         [ +  + ]:      76069 :         for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
     771                 :       6998 :             const auto& [leaf_hashes, origin] = leaf;
     772                 :      13996 :             SerializeToVector(s, PSBT_OUT_TAP_BIP32_DERIVATION, xonly);
     773                 :       6998 :             std::vector<unsigned char> value;
     774         [ +  - ]:       6998 :             CVectorWriter s_value{s.GetVersion(), value, 0};
     775         [ +  - ]:       6998 :             s_value << leaf_hashes;
     776   [ +  -  +  - ]:       6998 :             SerializeKeyOrigin(s_value, origin);
     777         [ +  - ]:       6998 :             s << value;
     778                 :       6998 :         }
     779                 :            : 
     780                 :            :         // Write unknown things
     781         [ +  + ]:      96590 :         for (auto& entry : unknown) {
     782                 :      27519 :             s << entry.first;
     783                 :      27519 :             s << entry.second;
     784                 :            :         }
     785                 :            : 
     786                 :      69071 :         s << PSBT_SEPARATOR;
     787                 :      69071 :     }
     788                 :            : 
     789                 :            : 
     790                 :            :     template <typename Stream>
     791                 :      99627 :     inline void Unserialize(Stream& s) {
     792                 :            :         // Used for duplicate key detection
     793                 :      99627 :         std::set<std::vector<unsigned char>> key_lookup;
     794                 :            : 
     795                 :            :         // Read loop
     796                 :      99627 :         bool found_sep = false;
     797         [ +  + ]:     217734 :         while(!s.empty()) {
     798                 :            :             // Read
     799                 :     217552 :             std::vector<unsigned char> key;
     800         [ +  + ]:     217552 :             s >> key;
     801                 :            : 
     802                 :            :             // the key is empty if that was actually a separator byte
     803                 :            :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
     804         [ +  + ]:     215729 :             if (key.empty()) {
     805                 :      86667 :                 found_sep = true;
     806                 :      86667 :                 break;
     807                 :            :             }
     808                 :            : 
     809                 :            :             // Type is compact size uint at beginning of key
     810   [ +  -  +  - ]:     129062 :             SpanReader skey{s.GetVersion(), key};
     811         [ +  + ]:     129062 :             uint64_t type = ReadCompactSize(skey);
     812                 :            : 
     813                 :            :             // Do stuff based on type
     814   [ +  +  +  +  :     128976 :             switch(type) {
             +  +  +  + ]
     815                 :            :                 case PSBT_OUT_REDEEMSCRIPT:
     816                 :            :                 {
     817   [ +  -  +  + ]:       6372 :                     if (!key_lookup.emplace(key).second) {
     818         [ +  - ]:         49 :                         throw std::ios_base::failure("Duplicate Key, output redeemScript already provided");
     819         [ +  + ]:       6323 :                     } else if (key.size() != 1) {
     820         [ +  - ]:       1223 :                         throw std::ios_base::failure("Output redeemScript key is more than one byte type");
     821                 :            :                     }
     822         [ +  + ]:       5100 :                     s >> redeem_script;
     823                 :       4987 :                     break;
     824                 :            :                 }
     825                 :            :                 case PSBT_OUT_WITNESSSCRIPT:
     826                 :            :                 {
     827   [ +  -  +  + ]:       2160 :                     if (!key_lookup.emplace(key).second) {
     828         [ +  - ]:         72 :                         throw std::ios_base::failure("Duplicate Key, output witnessScript already provided");
     829         [ +  + ]:       2088 :                     } else if (key.size() != 1) {
     830         [ +  - ]:         77 :                         throw std::ios_base::failure("Output witnessScript key is more than one byte type");
     831                 :            :                     }
     832         [ +  + ]:       2011 :                     s >> witness_script;
     833                 :       1996 :                     break;
     834                 :            :                 }
     835                 :            :                 case PSBT_OUT_BIP32_DERIVATION:
     836                 :            :                 {
     837         [ +  + ]:      16572 :                     DeserializeHDKeypaths(s, key, hd_keypaths);
     838                 :      14938 :                     break;
     839                 :            :                 }
     840                 :            :                 case PSBT_OUT_TAP_INTERNAL_KEY:
     841                 :            :                 {
     842   [ +  -  +  + ]:       1491 :                     if (!key_lookup.emplace(key).second) {
     843         [ +  - ]:         22 :                         throw std::ios_base::failure("Duplicate Key, output Taproot internal key already provided");
     844         [ +  + ]:       1469 :                     } else if (key.size() != 1) {
     845         [ +  - ]:        453 :                         throw std::ios_base::failure("Output Taproot internal key key is more than one byte type");
     846                 :            :                     }
     847         [ +  + ]:       1016 :                     UnserializeFromVector(s, m_tap_internal_key);
     848                 :        894 :                     break;
     849                 :            :                 }
     850                 :            :                 case PSBT_OUT_TAP_TREE:
     851                 :            :                 {
     852   [ +  -  +  + ]:       5695 :                     if (!key_lookup.emplace(key).second) {
     853         [ +  - ]:         70 :                         throw std::ios_base::failure("Duplicate Key, output Taproot tree already provided");
     854         [ +  + ]:       5625 :                     } else if (key.size() != 1) {
     855         [ +  - ]:         95 :                         throw std::ios_base::failure("Output Taproot tree key is more than one byte type");
     856                 :            :                     }
     857                 :       5530 :                     std::vector<unsigned char> tree_v;
     858         [ +  + ]:       5530 :                     s >> tree_v;
     859   [ +  -  +  - ]:       4921 :                     SpanReader s_tree{s.GetVersion(), tree_v};
     860   [ +  -  +  + ]:       4921 :                     if (s_tree.empty()) {
     861         [ +  - ]:        252 :                         throw std::ios_base::failure("Output Taproot tree must not be empty");
     862                 :            :                     }
     863         [ +  - ]:       4669 :                     TaprootBuilder builder;
     864   [ +  -  +  + ]:      81903 :                     while (!s_tree.empty()) {
     865                 :            :                         uint8_t depth;
     866                 :            :                         uint8_t leaf_ver;
     867                 :      80167 :                         std::vector<unsigned char> script;
     868         [ +  - ]:      80167 :                         s_tree >> depth;
     869         [ +  + ]:      80167 :                         s_tree >> leaf_ver;
     870         [ +  + ]:      80134 :                         s_tree >> script;
     871         [ +  + ]:      78002 :                         if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
     872         [ +  - ]:        181 :                             throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
     873                 :            :                         }
     874         [ +  + ]:      77821 :                         if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
     875         [ +  - ]:        587 :                             throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
     876                 :            :                         }
     877   [ +  -  +  - ]:      77234 :                         m_tap_tree.push_back(std::make_tuple(depth, leaf_ver, script));
     878   [ +  -  +  - ]:      77234 :                         builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
     879                 :      80167 :                     }
     880   [ +  -  +  + ]:       1736 :                     if (!builder.IsComplete()) {
     881         [ +  - ]:        263 :                         throw std::ios_base::failure("Output Taproot tree is malformed");
     882                 :            :                     }
     883                 :            :                     break;
     884                 :       5530 :                 }
     885                 :            :                 case PSBT_OUT_TAP_BIP32_DERIVATION:
     886                 :            :                 {
     887   [ +  -  +  + ]:      14950 :                     if (!key_lookup.emplace(key).second) {
     888         [ +  - ]:        208 :                         throw std::ios_base::failure("Duplicate Key, output Taproot BIP32 keypath already provided");
     889         [ +  + ]:      14742 :                     } else if (key.size() != 33) {
     890         [ +  - ]:         90 :                         throw std::ios_base::failure("Output Taproot BIP32 keypath key is not at 33 bytes");
     891                 :            :                     }
     892   [ +  -  +  -  :      14652 :                     XOnlyPubKey xonly(uint256(Span<uint8_t>(key).last(32)));
             +  -  +  - ]
     893                 :      14652 :                     std::set<uint256> leaf_hashes;
     894         [ +  + ]:      14652 :                     uint64_t value_len = ReadCompactSize(s);
     895                 :      14464 :                     size_t before_hashes = s.size();
     896         [ +  + ]:      14464 :                     s >> leaf_hashes;
     897                 :      13863 :                     size_t after_hashes = s.size();
     898                 :      13863 :                     size_t hashes_len = before_hashes - after_hashes;
     899         [ +  + ]:      13863 :                     if (hashes_len > value_len) {
     900         [ +  - ]:         70 :                         throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
     901                 :            :                     }
     902                 :      13793 :                     size_t origin_len = value_len - hashes_len;
     903   [ +  +  -  +  :      13793 :                     m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
                   -  + ]
     904                 :            :                     break;
     905                 :      14652 :                 }
     906                 :            :                 case PSBT_OUT_PROPRIETARY:
     907                 :            :                 {
     908                 :      13659 :                     PSBTProprietary this_prop;
     909         [ +  + ]:      13659 :                     skey >> this_prop.identifier;
     910         [ +  - ]:      13523 :                     this_prop.subtype = ReadCompactSize(skey);
     911         [ +  - ]:      13523 :                     this_prop.key = key;
     912                 :            : 
     913   [ +  -  +  + ]:      13523 :                     if (m_proprietary.count(this_prop) > 0) {
     914         [ +  - ]:        130 :                         throw std::ios_base::failure("Duplicate Key, proprietary key already found");
     915                 :            :                     }
     916         [ +  + ]:      13393 :                     s >> this_prop.value;
     917         [ +  - ]:      13243 :                     m_proprietary.insert(this_prop);
     918                 :            :                     break;
     919                 :      13659 :                 }
     920                 :            :                 // Unknown stuff
     921                 :            :                 default: {
     922   [ +  -  +  + ]:      68077 :                     if (unknown.count(key) > 0) {
     923         [ +  - ]:        459 :                         throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
     924                 :            :                     }
     925                 :            :                     // Read in the value
     926                 :      67618 :                     std::vector<unsigned char> val_bytes;
     927         [ +  + ]:      67618 :                     s >> val_bytes;
     928         [ +  - ]:      66830 :                     unknown.emplace(std::move(key), std::move(val_bytes));
     929                 :            :                     break;
     930                 :      67618 :                 }
     931                 :            :             }
     932         [ +  + ]:     217552 :         }
     933                 :            : 
     934         [ +  + ]:      86849 :         if (!found_sep) {
     935         [ +  - ]:        182 :             throw std::ios_base::failure("Separator is missing at the end of an output map");
     936                 :            :         }
     937                 :     112405 :     }
     938                 :            : 
     939                 :            :     template <typename Stream>
     940                 :            :     PSBTOutput(deserialize_type, Stream& s) {
     941                 :            :         Unserialize(s);
     942                 :            :     }
     943                 :            : };
     944                 :            : 
     945                 :            : /** A version of CTransaction with the PSBT format*/
     946   [ +  -  +  -  :      29185 : struct PartiallySignedTransaction
             +  -  -  + ]
     947                 :            : {
     948                 :            :     std::optional<CMutableTransaction> tx;
     949                 :            :     // We use a vector of CExtPubKey in the event that there happens to be the same KeyOriginInfos for different CExtPubKeys
     950                 :            :     // Note that this map swaps the key and values from the serialization
     951                 :            :     std::map<KeyOriginInfo, std::set<CExtPubKey>> m_xpubs;
     952                 :            :     std::vector<PSBTInput> inputs;
     953                 :            :     std::vector<PSBTOutput> outputs;
     954                 :            :     std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
     955                 :            :     std::optional<uint32_t> m_version;
     956                 :            :     std::set<PSBTProprietary> m_proprietary;
     957                 :            : 
     958                 :            :     bool IsNull() const;
     959                 :            :     uint32_t GetVersion() const;
     960                 :            : 
     961                 :            :     /** Merge psbt into this. The two psbts must have the same underlying CTransaction (i.e. the
     962                 :            :       * same actual Bitcoin transaction.) Returns true if the merge succeeded, false otherwise. */
     963                 :            :     [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
     964                 :            :     bool AddInput(const CTxIn& txin, PSBTInput& psbtin);
     965                 :            :     bool AddOutput(const CTxOut& txout, const PSBTOutput& psbtout);
     966                 :     154284 :     PartiallySignedTransaction() {}
     967                 :            :     explicit PartiallySignedTransaction(const CMutableTransaction& tx);
     968                 :            :     /**
     969                 :            :      * Finds the UTXO for a given input index
     970                 :            :      *
     971                 :            :      * @param[out] utxo The UTXO of the input if found
     972                 :            :      * @param[in] input_index Index of the input to retrieve the UTXO of
     973                 :            :      * @return Whether the UTXO for the specified input was found
     974                 :            :      */
     975                 :            :     bool GetInputUTXO(CTxOut& utxo, int input_index) const;
     976                 :            : 
     977                 :            :     template <typename Stream>
     978                 :      31916 :     inline void Serialize(Stream& s) const {
     979                 :            : 
     980                 :            :         // magic bytes
     981                 :      31916 :         s << PSBT_MAGIC_BYTES;
     982                 :            : 
     983                 :            :         // unsigned tx flag
     984                 :      31916 :         SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_UNSIGNED_TX));
     985                 :            : 
     986                 :            :         // Write serialized tx to a stream
     987                 :      31916 :         OverrideStream<Stream> os{&s, s.GetVersion() | SERIALIZE_TRANSACTION_NO_WITNESS};
     988                 :      31916 :         SerializeToVector(os, *tx);
     989                 :            : 
     990                 :            :         // Write xpubs
     991         [ +  + ]:      35639 :         for (const auto& xpub_pair : m_xpubs) {
     992         [ +  + ]:       7759 :             for (const auto& xpub : xpub_pair.second) {
     993                 :            :                 unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
     994                 :       4036 :                 xpub.EncodeWithVersion(ser_xpub);
     995                 :            :                 // Note that the serialization swaps the key and value
     996                 :            :                 // The xpub is the key (for uniqueness) while the path is the value
     997                 :       4036 :                 SerializeToVector(s, PSBT_GLOBAL_XPUB, ser_xpub);
     998         [ +  - ]:       4036 :                 SerializeHDKeypath(s, xpub_pair.first);
     999                 :            :             }
    1000                 :            :         }
    1001                 :            : 
    1002                 :            :         // PSBT version
    1003         [ +  - ]:      31916 :         if (GetVersion() > 0) {
    1004                 :          0 :             SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_VERSION));
    1005                 :          0 :             SerializeToVector(s, *m_version);
    1006                 :          0 :         }
    1007                 :            : 
    1008                 :            :         // Write proprietary things
    1009         [ +  + ]:      36162 :         for (const auto& entry : m_proprietary) {
    1010                 :       4246 :             s << entry.key;
    1011                 :       4246 :             s << entry.value;
    1012                 :            :         }
    1013                 :            : 
    1014                 :            :         // Write the unknown things
    1015         [ +  + ]:      65855 :         for (auto& entry : unknown) {
    1016                 :      33939 :             s << entry.first;
    1017                 :      33939 :             s << entry.second;
    1018                 :            :         }
    1019                 :            : 
    1020                 :            :         // Separator
    1021                 :      31916 :         s << PSBT_SEPARATOR;
    1022                 :            : 
    1023                 :            :         // Write inputs
    1024         [ +  + ]:      89161 :         for (const PSBTInput& input : inputs) {
    1025                 :      57245 :             s << input;
    1026                 :            :         }
    1027                 :            :         // Write outputs
    1028         [ +  + ]:     100844 :         for (const PSBTOutput& output : outputs) {
    1029                 :      68928 :             s << output;
    1030                 :            :         }
    1031                 :      31916 :     }
    1032                 :            : 
    1033                 :            : 
    1034                 :            :     template <typename Stream>
    1035                 :     144728 :     inline void Unserialize(Stream& s) {
    1036                 :            :         // Read the magic bytes
    1037                 :            :         uint8_t magic[5];
    1038                 :     144728 :         s >> magic;
    1039         [ +  + ]:     144728 :         if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
    1040         [ +  - ]:     106581 :             throw std::ios_base::failure("Invalid PSBT magic bytes");
    1041                 :            :         }
    1042                 :            : 
    1043                 :            :         // Used for duplicate key detection
    1044                 :     105452 :         std::set<std::vector<unsigned char>> key_lookup;
    1045                 :            : 
    1046                 :            :         // Track the global xpubs we have already seen. Just for sanity checking
    1047                 :     105452 :         std::set<CExtPubKey> global_xpubs;
    1048                 :            : 
    1049                 :            :         // Read global data
    1050                 :     105452 :         bool found_sep = false;
    1051   [ +  +  #  # ]:     279253 :         while(!s.empty()) {
    1052                 :            :             // Read
    1053                 :     279157 :             std::vector<unsigned char> key;
    1054         [ +  + ]:     279157 :             s >> key;
    1055                 :            : 
    1056                 :            :             // the key is empty if that was actually a separator byte
    1057                 :            :             // This is a special case for key lengths 0 as those are not allowed (except for separator)
    1058         [ +  + ]:     274197 :             if (key.empty()) {
    1059                 :      75038 :                 found_sep = true;
    1060                 :      75038 :                 break;
    1061                 :            :             }
    1062                 :            : 
    1063                 :            :             // Type is compact size uint at beginning of key
    1064   [ +  -  +  -  :     199159 :             SpanReader skey{s.GetVersion(), key};
                   #  # ]
    1065         [ +  + ]:     199159 :             uint64_t type = ReadCompactSize(skey);
    1066                 :            : 
    1067                 :            :             // Do stuff based on type
    1068   [ +  +  +  +  :     198690 :             switch(type) {
                      + ]
    1069                 :            :                 case PSBT_GLOBAL_UNSIGNED_TX:
    1070                 :            :                 {
    1071   [ +  -  +  + ]:      95392 :                     if (!key_lookup.emplace(key).second) {
    1072         [ +  - ]:        140 :                         throw std::ios_base::failure("Duplicate Key, unsigned tx already provided");
    1073         [ +  + ]:      95252 :                     } else if (key.size() != 1) {
    1074         [ +  - ]:        486 :                         throw std::ios_base::failure("Global unsigned tx key is more than one byte type");
    1075                 :            :                     }
    1076         [ +  - ]:      94766 :                     CMutableTransaction mtx;
    1077                 :            :                     // Set the stream to serialize with non-witness since this should always be non-witness
    1078   [ +  -  #  # ]:      94766 :                     OverrideStream<Stream> os{&s, s.GetVersion() | SERIALIZE_TRANSACTION_NO_WITNESS};
    1079         [ +  + ]:      94766 :                     UnserializeFromVector(os, mtx);
    1080         [ +  - ]:      77904 :                     tx = std::move(mtx);
    1081                 :            :                     // Make sure that all scriptSigs and scriptWitnesses are empty
    1082   [ +  -  +  + ]:     219644 :                     for (const CTxIn& txin : tx->vin) {
    1083   [ +  +  #  # ]:     141822 :                         if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
    1084         [ +  - ]:         82 :                             throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
    1085                 :            :                         }
    1086                 :            :                     }
    1087                 :            :                     break;
    1088                 :      94766 :                 }
    1089                 :            :                 case PSBT_GLOBAL_XPUB:
    1090                 :            :                 {
    1091         [ +  + ]:      11892 :                     if (key.size() != BIP32_EXTKEY_WITH_VERSION_SIZE + 1) {
    1092         [ +  - ]:        239 :                         throw std::ios_base::failure("Size of key was not the expected size for the type global xpub");
    1093                 :            :                     }
    1094                 :            :                     // Read in the xpub from key
    1095         [ +  - ]:      11653 :                     CExtPubKey xpub;
    1096         [ +  - ]:      11653 :                     xpub.DecodeWithVersion(&key.data()[1]);
    1097   [ +  -  +  + ]:      11653 :                     if (!xpub.pubkey.IsFullyValid()) {
    1098         [ +  - ]:       1088 :                        throw std::ios_base::failure("Invalid pubkey");
    1099                 :            :                     }
    1100   [ +  -  +  + ]:      10565 :                     if (global_xpubs.count(xpub) > 0) {
    1101         [ +  - ]:        162 :                        throw std::ios_base::failure("Duplicate key, global xpub already provided");
    1102                 :            :                     }
    1103         [ +  - ]:      10403 :                     global_xpubs.insert(xpub);
    1104                 :            :                     // Read in the keypath from stream
    1105                 :      10403 :                     KeyOriginInfo keypath;
    1106         [ +  + ]:      10403 :                     DeserializeHDKeypath(s, keypath);
    1107                 :            : 
    1108                 :            :                     // Note that we store these swapped to make searches faster.
    1109                 :            :                     // Serialization uses xpub -> keypath to enqure key uniqueness
    1110   [ +  -  +  + ]:       9819 :                     if (m_xpubs.count(keypath) == 0) {
    1111                 :            :                         // Make a new set to put the xpub in
    1112   [ +  -  +  - ]:       9032 :                         m_xpubs[keypath] = {xpub};
    1113                 :       9032 :                     } else {
    1114                 :            :                         // Insert xpub into existing set
    1115   [ +  -  +  - ]:        787 :                         m_xpubs[keypath].insert(xpub);
    1116                 :            :                     }
    1117                 :            :                     break;
    1118                 :      10403 :                 }
    1119                 :            :                 case PSBT_GLOBAL_VERSION:
    1120                 :            :                 {
    1121         [ +  + ]:       1335 :                     if (m_version) {
    1122         [ +  - ]:         33 :                         throw std::ios_base::failure("Duplicate Key, version already provided");
    1123         [ +  + ]:       1302 :                     } else if (key.size() != 1) {
    1124         [ +  - ]:         59 :                         throw std::ios_base::failure("Global version key is more than one byte type");
    1125                 :            :                     }
    1126                 :            :                     uint32_t v;
    1127         [ +  + ]:       1243 :                     UnserializeFromVector(s, v);
    1128         [ +  - ]:       1037 :                     m_version = v;
    1129   [ +  -  +  + ]:       1037 :                     if (*m_version > PSBT_HIGHEST_VERSION) {
    1130         [ +  - ]:        642 :                         throw std::ios_base::failure("Unsupported version number");
    1131                 :            :                     }
    1132                 :        395 :                     break;
    1133                 :            :                 }
    1134                 :            :                 case PSBT_GLOBAL_PROPRIETARY:
    1135                 :            :                 {
    1136                 :       9981 :                     PSBTProprietary this_prop;
    1137         [ +  + ]:       9981 :                     skey >> this_prop.identifier;
    1138         [ +  - ]:       9327 :                     this_prop.subtype = ReadCompactSize(skey);
    1139         [ +  - ]:       9327 :                     this_prop.key = key;
    1140                 :            : 
    1141   [ +  -  +  + ]:       9327 :                     if (m_proprietary.count(this_prop) > 0) {
    1142         [ +  - ]:        585 :                         throw std::ios_base::failure("Duplicate Key, proprietary key already found");
    1143                 :            :                     }
    1144         [ +  + ]:       8742 :                     s >> this_prop.value;
    1145         [ +  - ]:       8274 :                     m_proprietary.insert(this_prop);
    1146                 :            :                     break;
    1147                 :       9981 :                 }
    1148                 :            :                 // Unknown stuff
    1149                 :            :                 default: {
    1150   [ +  -  +  + ]:      80090 :                     if (unknown.count(key) > 0) {
    1151         [ +  - ]:        546 :                         throw std::ios_base::failure("Duplicate Key, key for unknown value already provided");
    1152                 :            :                     }
    1153                 :            :                     // Read in the value
    1154                 :      79544 :                     std::vector<unsigned char> val_bytes;
    1155         [ +  + ]:      79544 :                     s >> val_bytes;
    1156         [ +  - ]:      77491 :                     unknown.emplace(std::move(key), std::move(val_bytes));
    1157                 :      79544 :                 }
    1158                 :      77491 :             }
    1159         [ +  + ]:     279157 :         }
    1160                 :            : 
    1161         [ +  + ]:      75134 :         if (!found_sep) {
    1162         [ +  - ]:         96 :             throw std::ios_base::failure("Separator is missing at the end of the global map");
    1163                 :            :         }
    1164                 :            : 
    1165                 :            :         // Make sure that we got an unsigned tx
    1166         [ +  + ]:      75038 :         if (!tx) {
    1167         [ +  - ]:       2006 :             throw std::ios_base::failure("No unsigned transaction was provided");
    1168                 :            :         }
    1169                 :            : 
    1170                 :            :         // Read input data
    1171                 :      73032 :         unsigned int i = 0;
    1172   [ +  +  +  -  :     167685 :         while (!s.empty() && i < tx->vin.size()) {
             +  +  #  # ]
    1173         [ +  - ]:     116512 :             PSBTInput input;
    1174         [ +  + ]:     116512 :             s >> input;
    1175         [ +  - ]:      94757 :             inputs.push_back(input);
    1176                 :            : 
    1177                 :            :             // Make sure the non-witness utxo matches the outpoint
    1178   [ +  -  +  +  :      94757 :             if (input.non_witness_utxo && input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
          +  -  +  -  +  
                -  +  + ]
    1179         [ +  - ]:        104 :                 throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
    1180                 :            :             }
    1181                 :      94653 :             ++i;
    1182                 :     116512 :         }
    1183                 :            :         // Make sure that the number of inputs matches the number of inputs in the transaction
    1184   [ +  -  +  + ]:      51173 :         if (inputs.size() != tx->vin.size()) {
    1185         [ +  - ]:        101 :             throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
    1186                 :            :         }
    1187                 :            : 
    1188                 :            :         // Read output data
    1189                 :      51072 :         i = 0;
    1190   [ +  +  +  -  :     137596 :         while (!s.empty() && i < tx->vout.size()) {
             +  +  #  # ]
    1191         [ +  - ]:      99234 :             PSBTOutput output;
    1192         [ +  + ]:      99234 :             s >> output;
    1193         [ +  - ]:      86524 :             outputs.push_back(output);
    1194                 :      86524 :             ++i;
    1195                 :      99234 :         }
    1196                 :            :         // Make sure that the number of outputs matches the number of outputs in the transaction
    1197   [ +  -  +  + ]:      38362 :         if (outputs.size() != tx->vout.size()) {
    1198         [ +  - ]:        215 :             throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
    1199                 :            :         }
    1200                 :     157629 :     }
    1201                 :            : 
    1202                 :            :     template <typename Stream>
    1203                 :            :     PartiallySignedTransaction(deserialize_type, Stream& s) {
    1204                 :            :         Unserialize(s);
    1205                 :            :     }
    1206                 :            : };
    1207                 :            : 
    1208                 :            : enum class PSBTRole {
    1209                 :            :     CREATOR,
    1210                 :            :     UPDATER,
    1211                 :            :     SIGNER,
    1212                 :            :     FINALIZER,
    1213                 :            :     EXTRACTOR
    1214                 :            : };
    1215                 :            : 
    1216                 :            : std::string PSBTRoleName(PSBTRole role);
    1217                 :            : 
    1218                 :            : /** Compute a PrecomputedTransactionData object from a psbt. */
    1219                 :            : PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt);
    1220                 :            : 
    1221                 :            : /** Checks whether a PSBTInput is already signed by checking for non-null finalized fields. */
    1222                 :            : bool PSBTInputSigned(const PSBTInput& input);
    1223                 :            : 
    1224                 :            : /** Checks whether a PSBTInput is already signed by doing script verification using final fields. */
    1225                 :            : bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
    1226                 :            : 
    1227                 :            : /** Signs a PSBTInput, verifying that all provided data matches what is being signed.
    1228                 :            :  *
    1229                 :            :  * txdata should be the output of PrecomputePSBTData (which can be shared across
    1230                 :            :  * multiple SignPSBTInput calls). If it is nullptr, a dummy signature will be created.
    1231                 :            :  **/
    1232                 :            : bool SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, int sighash = SIGHASH_ALL, SignatureData* out_sigdata = nullptr, bool finalize = true);
    1233                 :            : 
    1234                 :            : /**  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. */
    1235                 :            : void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx, const int& sighash_type);
    1236                 :            : 
    1237                 :            : /** Counts the unsigned inputs of a PSBT. */
    1238                 :            : size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt);
    1239                 :            : 
    1240                 :            : /** Updates a PSBTOutput with information from provider.
    1241                 :            :  *
    1242                 :            :  * This fills in the redeem_script, witness_script, and hd_keypaths where possible.
    1243                 :            :  */
    1244                 :            : void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index);
    1245                 :            : 
    1246                 :            : /**
    1247                 :            :  * Finalizes a PSBT if possible, combining partial signatures.
    1248                 :            :  *
    1249                 :            :  * @param[in,out] psbtx PartiallySignedTransaction to finalize
    1250                 :            :  * return True if the PSBT is now complete, false otherwise
    1251                 :            :  */
    1252                 :            : bool FinalizePSBT(PartiallySignedTransaction& psbtx);
    1253                 :            : 
    1254                 :            : /**
    1255                 :            :  * Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
    1256                 :            :  *
    1257                 :            :  * @param[in]  psbtx PartiallySignedTransaction
    1258                 :            :  * @param[out] result CMutableTransaction representing the complete transaction, if successful
    1259                 :            :  * @return True if we successfully extracted the transaction, false otherwise
    1260                 :            :  */
    1261                 :            : bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result);
    1262                 :            : 
    1263                 :            : /**
    1264                 :            :  * Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial signatures from each input.
    1265                 :            :  *
    1266                 :            :  * @param[out] out   the combined PSBT, if successful
    1267                 :            :  * @param[in]  psbtxs the PSBTs to combine
    1268                 :            :  * @return error (OK if we successfully combined the transactions, other error if they were not compatible)
    1269                 :            :  */
    1270                 :            : [[nodiscard]] TransactionError CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs);
    1271                 :            : 
    1272                 :            : //! Decode a base64ed PSBT into a PartiallySignedTransaction
    1273                 :            : [[nodiscard]] bool DecodeBase64PSBT(PartiallySignedTransaction& decoded_psbt, const std::string& base64_psbt, std::string& error);
    1274                 :            : //! Decode a raw (binary blob) PSBT into a PartiallySignedTransaction
    1275                 :            : [[nodiscard]] bool DecodeRawPSBT(PartiallySignedTransaction& decoded_psbt, Span<const std::byte> raw_psbt, std::string& error);
    1276                 :            : 
    1277                 :            : #endif // BITCOIN_PSBT_H

Generated by: LCOV version 1.14