LCOV - code coverage report
Current view: top level - src - psbt.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 93.3 % 509 475
Test Date: 2026-08-25 06:30:02 Functions: 96.9 % 32 31
Branches: 70.9 % 802 569

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-present The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <psbt.h>
       6                 :             : 
       7                 :             : #include <common/types.h>
       8                 :             : #include <node/types.h>
       9                 :             : #include <policy/policy.h>
      10                 :             : #include <primitives/transaction.h>
      11                 :             : #include <script/signingprovider.h>
      12                 :             : #include <util/check.h>
      13                 :             : #include <util/result.h>
      14                 :             : #include <util/strencodings.h>
      15                 :             : 
      16                 :             : #include <algorithm>
      17                 :             : #include <set>
      18                 :             : 
      19                 :             : using common::PSBTError;
      20                 :             : 
      21         [ +  + ]:         545 : PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx, uint32_t version) : m_version(version)
      22                 :             : {
      23   [ +  +  -  + ]:         545 :     assert(m_version == 0 || m_version == 2);
      24                 :             : 
      25                 :         545 :     tx_version = tx.version;
      26         [ -  + ]:         545 :     fallback_locktime = tx.nLockTime;
      27   [ -  +  +  - ]:         545 :     inputs.reserve(tx.vin.size());
      28         [ +  + ]:        2326 :     for (const CTxIn& input : tx.vin) {
      29   [ +  -  +  - ]:        1781 :         inputs.emplace_back(GetVersion(), input.prevout.hash, input.prevout.n, input.nSequence);
      30                 :             :     }
      31   [ -  +  +  - ]:         545 :     outputs.reserve(tx.vout.size());
      32         [ +  + ]:        4770 :     for (const CTxOut& output : tx.vout) {
      33   [ +  -  +  - ]:        4225 :         outputs.emplace_back(GetVersion(), output.nValue, output.scriptPubKey);
      34                 :             :     }
      35                 :         545 : }
      36                 :             : 
      37                 :         203 : bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt)
      38                 :             : {
      39                 :             :     // Prohibited to merge two PSBTs over different transactions
      40                 :         203 :     std::optional<Txid> this_id = GetUniqueID();
      41                 :         203 :     std::optional<Txid> psbt_id = psbt.GetUniqueID();
      42   [ +  -  +  -  :         203 :     if (!this_id || !psbt_id || this_id != psbt_id) {
                   +  + ]
      43                 :             :         return false;
      44                 :             :     }
      45         [ +  - ]:         202 :     if (GetVersion() != psbt.GetVersion()) {
      46                 :             :         return false;
      47                 :             :     }
      48                 :             : 
      49   [ -  +  +  + ]:         406 :     for (unsigned int i = 0; i < inputs.size(); ++i) {
      50         [ +  - ]:         204 :         if (!inputs[i].Merge(psbt.inputs[i])) {
      51                 :             :             return false;
      52                 :             :         }
      53                 :             :     }
      54   [ -  +  +  + ]:         590 :     for (unsigned int i = 0; i < outputs.size(); ++i) {
      55         [ +  - ]:         388 :         if (!outputs[i].Merge(psbt.outputs[i])) {
      56                 :             :             return false;
      57                 :             :         }
      58                 :             :     }
      59                 :         202 :     MergeGlobalXPubs(psbt);
      60   [ -  +  -  - ]:         202 :     if (fallback_locktime == std::nullopt && psbt.fallback_locktime != std::nullopt) fallback_locktime = psbt.fallback_locktime;
      61                 :             : 
      62                 :             :     // Set m_tx_modifiable only if either PSBT had it set
      63   [ +  -  -  + ]:         202 :     if (m_tx_modifiable.has_value() || psbt.m_tx_modifiable.has_value()) {
      64                 :             :         // In general, we AND the modifiable flags
      65         [ #  # ]:           0 :         std::bitset<8> this_modifiable = m_tx_modifiable.value_or(0);
      66         [ #  # ]:           0 :         std::bitset<8> psbt_modifiable = psbt.m_tx_modifiable.value_or(0);
      67         [ #  # ]:           0 :         std::bitset<8> final_modifiable = this_modifiable & psbt_modifiable;
      68                 :             :         // SIGHASH_SINGLE Modifiable (bit 2) needs to be bitwise OR'd
      69   [ #  #  #  #  :           0 :         final_modifiable.set(2, this_modifiable[2] || psbt_modifiable[2]);
                   #  # ]
      70                 :             : 
      71         [ #  # ]:           0 :         m_tx_modifiable = final_modifiable;
      72                 :             :     }
      73                 :             : 
      74                 :         202 :     m_proprietary.insert(psbt.m_proprietary.begin(), psbt.m_proprietary.end());
      75                 :         202 :     unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
      76                 :             : 
      77                 :         202 :     return true;
      78                 :             : }
      79                 :             : 
      80                 :         213 : void PartiallySignedTransaction::MergeGlobalXPubs(const PartiallySignedTransaction& psbt)
      81                 :             : {
      82         [ +  + ]:         218 :     for (const auto& [origin, xpubs] : psbt.m_xpubs) {
      83         [ +  + ]:          10 :         for (const CExtPubKey& xpub : xpubs) {
      84                 :           8 :             const bool known{std::ranges::any_of(m_xpubs, [&](const auto& entry) { return entry.second.contains(xpub); })};
      85         [ +  + ]:           5 :             if (!known) m_xpubs[origin].insert(xpub);
      86                 :             :         }
      87                 :             :     }
      88                 :         213 : }
      89                 :             : 
      90                 :       60094 : std::optional<uint32_t> PartiallySignedTransaction::ComputeTimeLock() const
      91                 :             : {
      92         [ +  + ]:       60094 :     if (GetVersion() >= 2) {
      93                 :       59370 :         std::optional<uint32_t> time_lock{0};
      94                 :       59370 :         std::optional<uint32_t> height_lock{0};
      95         [ +  + ]:     7605914 :         for (const PSBTInput& input : inputs) {
      96   [ +  +  +  + ]:     7546546 :             if (input.time_locktime.has_value() && !input.height_locktime.has_value()) {
      97         [ +  - ]:          10 :                 height_lock.reset(); // Transaction can no longer have a height locktime
      98         [ +  + ]:          10 :                 if (!time_lock.has_value()) {
      99                 :           2 :                     return std::nullopt;
     100                 :             :                 }
     101   [ +  +  +  + ]:     7546536 :             } else if (!input.time_locktime.has_value() && input.height_locktime.has_value()) {
     102         [ +  + ]:          10 :                 time_lock.reset(); // Transaction can no longer have a time locktime
     103         [ -  + ]:          10 :                 if (!height_lock.has_value()) {
     104                 :           0 :                     return std::nullopt;
     105                 :             :                 }
     106                 :             :             }
     107   [ +  +  +  + ]:     7546544 :             if (input.time_locktime && time_lock.has_value()) {
     108                 :          19 :                 time_lock = std::max(time_lock, input.time_locktime);
     109                 :             :             }
     110   [ +  +  +  + ]:     7546544 :             if (input.height_locktime && height_lock.has_value()) {
     111                 :          21 :                 height_lock = std::max(height_lock, input.height_locktime);
     112                 :             :             }
     113                 :             :         }
     114   [ +  +  +  + ]:       59368 :         if (height_lock.has_value() && *height_lock > 0) {
     115                 :           9 :             return *height_lock;
     116                 :             :         }
     117   [ +  -  +  + ]:       59359 :         if (time_lock.has_value() && *time_lock > 0) {
     118                 :           8 :             return *time_lock;
     119                 :             :         }
     120                 :             :     }
     121         [ +  + ]:      120148 :     return fallback_locktime.value_or(0);
     122                 :             : }
     123                 :             : 
     124                 :       60080 : std::optional<CMutableTransaction> PartiallySignedTransaction::GetUnsignedTx() const
     125                 :             : {
     126                 :       60080 :     CMutableTransaction mtx;
     127                 :       60080 :     mtx.version = tx_version;
     128         [ +  - ]:       60080 :     std::optional<uint32_t> locktime = ComputeTimeLock();
     129         [ +  + ]:       60080 :     if (!locktime) {
     130                 :           1 :         return std::nullopt;
     131                 :             :     }
     132                 :       60079 :     mtx.nLockTime = *locktime;
     133                 :       60079 :     uint32_t max_sequence = CTxIn::SEQUENCE_FINAL;
     134         [ +  + ]:     7607658 :     for (const PSBTInput& input : inputs) {
     135                 :     7547579 :         CTxIn txin;
     136                 :     7547579 :         txin.prevout.hash = input.prev_txid;
     137                 :     7547579 :         txin.prevout.n = input.prev_out;
     138         [ +  + ]:     7547579 :         txin.nSequence = input.sequence.value_or(max_sequence);
     139         [ +  - ]:     7547579 :         mtx.vin.push_back(txin);
     140                 :     7547579 :     }
     141         [ +  + ]:      874363 :     for (const PSBTOutput& output : outputs) {
     142                 :      814284 :         CTxOut txout;
     143                 :      814284 :         txout.nValue = output.amount;
     144                 :      814284 :         txout.scriptPubKey = output.script;
     145         [ +  - ]:      814284 :         mtx.vout.push_back(txout);
     146                 :      814284 :     }
     147                 :       60079 :     return mtx;
     148                 :       60080 : }
     149                 :             : 
     150                 :         406 : std::optional<Txid> PartiallySignedTransaction::GetUniqueID() const
     151                 :             : {
     152                 :             :     // Get the unsigned transaction
     153                 :         406 :     std::optional<CMutableTransaction> mtx = GetUnsignedTx();
     154         [ -  + ]:         406 :     if (!mtx) {
     155                 :           0 :         return std::nullopt;
     156                 :             :     }
     157   [ +  -  +  + ]:         406 :     if (GetVersion() >= 2) {
     158         [ +  + ]:         750 :         for (CTxIn& txin : mtx->vin) {
     159                 :         376 :             txin.nSequence = 0;
     160                 :             :         }
     161                 :             :     }
     162         [ +  - ]:         406 :     return mtx->GetHash();
     163                 :         406 : }
     164                 :             : 
     165                 :          37 : bool PartiallySignedTransaction::AddInput(const PSBTInput& psbtin)
     166                 :             : {
     167                 :             :     // The input being added must be for this PSBT's version
     168         [ +  + ]:          37 :     if (psbtin.GetVersion() != GetVersion()) {
     169                 :             :         return false;
     170                 :             :     }
     171                 :             : 
     172                 :             :     // Prevent duplicate inputs
     173         [ +  - ]:          36 :     if (std::find_if(inputs.begin(), inputs.end(),
     174   [ +  -  +  + ]:         216 :         [psbtin](const PSBTInput& psbt) {
     175   [ +  +  +  + ]:          78 :             return psbt.prev_txid == psbtin.prev_txid && psbt.prev_out == psbtin.prev_out;
     176                 :             :         }
     177                 :          72 :     ) != inputs.end()) {
     178                 :             :         return false;
     179                 :             :     }
     180                 :             : 
     181         [ +  + ]:          29 :     if (GetVersion() < 2) {
     182                 :             :         // This is a v0 psbt, so do the v0 AddInput
     183                 :          21 :         inputs.push_back(psbtin);
     184                 :          21 :         inputs.back().partial_sigs.clear();
     185                 :          21 :         inputs.back().final_script_sig.clear();
     186                 :          21 :         inputs.back().final_script_witness.SetNull();
     187                 :          21 :         return true;
     188                 :             :     }
     189                 :             : 
     190                 :             :     // Check inputs modifiable flag
     191   [ +  -  +  + ]:           8 :     if (!m_tx_modifiable.has_value() || !m_tx_modifiable->test(0)) {
     192                 :             :         return false;
     193                 :             :     }
     194                 :             : 
     195                 :             :     // Determine if we need to iterate the inputs.
     196                 :             :     // For now, we only do this if the new input has a required time lock.
     197                 :             :     // BIP 370 states that we should also do this if m_tx_modifiable's bit 2 is set
     198                 :             :     // (Has SIGHASH_SINGLE flag) but since we are only adding inputs at the end of the vector,
     199                 :             :     // we don't care about that.
     200   [ +  +  +  + ]:           7 :     bool iterate_inputs = psbtin.time_locktime != std::nullopt || psbtin.height_locktime != std::nullopt;
     201                 :           4 :     if (iterate_inputs) {
     202                 :           4 :         std::optional<uint32_t> old_timelock = ComputeTimeLock();
     203         [ +  - ]:           4 :         if (!old_timelock) {
     204                 :             :             return false;
     205                 :             :         }
     206                 :             : 
     207                 :           4 :         std::optional<uint32_t> time_lock = psbtin.time_locktime;
     208                 :           4 :         std::optional<uint32_t> height_lock = psbtin.height_locktime;
     209                 :           4 :         bool has_sigs = false;
     210         [ +  + ]:          17 :         for (const PSBTInput& input : inputs) {
     211   [ +  +  +  + ]:          14 :             if (input.time_locktime.has_value() && !input.height_locktime.has_value()) {
     212         [ +  + ]:           2 :                 height_lock.reset(); // Transaction can no longer have a height locktime
     213         [ +  + ]:           2 :                 if (time_lock == std::nullopt) {
     214                 :             :                     return false;
     215                 :             :                 }
     216   [ +  +  -  + ]:          12 :             } else if (!input.time_locktime.has_value() && input.height_locktime.has_value()) {
     217         [ #  # ]:           0 :                 time_lock.reset(); // Transaction can no longer have a time locktime
     218         [ #  # ]:           0 :                 if (height_lock == std::nullopt) {
     219                 :             :                     return false;
     220                 :             :                 }
     221                 :             :             }
     222   [ +  +  +  + ]:          13 :             if (input.time_locktime && time_lock.has_value()) {
     223                 :           3 :                 time_lock = std::max(time_lock, input.time_locktime);
     224                 :             :             }
     225   [ +  +  +  + ]:          13 :             if (input.height_locktime && height_lock.has_value()) {
     226                 :           1 :                 height_lock = std::max(height_lock, input.height_locktime);
     227                 :             :             }
     228         [ +  + ]:          13 :             if (input.HasSignatures()) {
     229                 :           1 :                 has_sigs = true;
     230                 :             :             }
     231                 :             :         }
     232         [ +  - ]:           3 :         uint32_t new_timelock = fallback_locktime.value_or(0);
     233   [ +  +  -  + ]:           3 :         if (height_lock.has_value() && *height_lock > 0) {
     234                 :             :             new_timelock = *height_lock;
     235   [ +  -  -  + ]:           2 :         } else if (time_lock.has_value() && *time_lock > 0) {
     236                 :             :             new_timelock = *time_lock;
     237                 :             :         }
     238   [ +  +  -  + ]:           3 :         if (has_sigs && *old_timelock != new_timelock) {
     239                 :             :             return false;
     240                 :             :         }
     241                 :             :     }
     242                 :             : 
     243                 :             :     // Add the input to the end
     244                 :           5 :     inputs.push_back(psbtin);
     245                 :           5 :     return true;
     246                 :             : }
     247                 :             : 
     248                 :          15 : bool PartiallySignedTransaction::AddOutput(const PSBTOutput& psbtout)
     249                 :             : {
     250                 :             :     // The output being added must be for this PSBT's version
     251         [ +  + ]:          15 :     if (psbtout.GetVersion() != GetVersion()) {
     252                 :             :         return false;
     253                 :             :     }
     254                 :             : 
     255         [ +  + ]:          14 :     if (GetVersion() < 2) {
     256                 :             :         // This is a v0 psbt, do the v0 AddOutput
     257                 :          11 :         outputs.push_back(psbtout);
     258                 :          11 :         return true;
     259                 :             :     }
     260                 :             : 
     261                 :             :     // No global tx, must be PSBTv2
     262                 :             :     // Check outputs are modifiable
     263   [ +  -  +  + ]:           3 :     if (!m_tx_modifiable.has_value() || !m_tx_modifiable->test(1)) {
     264                 :             :         return false;
     265                 :             :     }
     266                 :           2 :     outputs.push_back(psbtout);
     267                 :             : 
     268                 :           2 :     return true;
     269                 :             : }
     270                 :             : 
     271                 :        5856 : bool PSBTInput::GetUTXO(CTxOut& utxo) const
     272                 :             : {
     273         [ +  + ]:        5856 :     if (non_witness_utxo) {
     274   [ -  +  +  + ]:        5111 :         if (prev_out >= non_witness_utxo->vout.size()) {
     275                 :             :             return false;
     276                 :             :         }
     277         [ +  - ]:        5110 :         if (non_witness_utxo->GetHash() != prev_txid) {
     278                 :             :             return false;
     279                 :             :         }
     280                 :        5110 :         utxo = non_witness_utxo->vout[prev_out];
     281         [ +  + ]:         745 :     } else if (!witness_utxo.IsNull()) {
     282                 :         707 :         utxo = witness_utxo;
     283                 :             :     } else {
     284                 :             :         return false;
     285                 :             :     }
     286                 :             :     return true;
     287                 :             : }
     288                 :             : 
     289                 :       51041 : COutPoint PSBTInput::GetOutPoint() const
     290                 :             : {
     291                 :       51041 :     return COutPoint(prev_txid, prev_out);
     292                 :             : }
     293                 :             : 
     294                 :       24526 : void PSBTInput::FillSignatureData(SignatureData& sigdata) const
     295                 :             : {
     296   [ -  +  -  + ]:       24526 :     if (!final_script_sig.empty()) {
     297                 :           0 :         sigdata.scriptSig = final_script_sig;
     298                 :           0 :         sigdata.complete = true;
     299                 :             :     }
     300         [ -  + ]:       24526 :     if (!final_script_witness.IsNull()) {
     301                 :           0 :         sigdata.scriptWitness = final_script_witness;
     302                 :           0 :         sigdata.complete = true;
     303                 :             :     }
     304         [ +  - ]:       24526 :     if (sigdata.complete) {
     305                 :             :         return;
     306                 :             :     }
     307                 :             : 
     308                 :       24526 :     sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
     309   [ +  +  +  + ]:       24595 :     if (!redeem_script.empty()) {
     310                 :        4422 :         sigdata.redeem_script = redeem_script;
     311                 :             :     }
     312   [ +  +  +  + ]:       24829 :     if (!witness_script.empty()) {
     313                 :         331 :         sigdata.witness_script = witness_script;
     314                 :             :     }
     315         [ +  + ]:       39247 :     for (const auto& key_pair : hd_keypaths) {
     316                 :       14721 :         sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
     317                 :             :     }
     318         [ +  + ]:       24526 :     if (!m_tap_key_sig.empty()) {
     319                 :         190 :         sigdata.taproot_key_path_sig = m_tap_key_sig;
     320                 :             :     }
     321         [ +  + ]:       25049 :     for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
     322                 :         523 :         sigdata.taproot_script_sigs.emplace(pubkey_leaf, sig);
     323                 :             :     }
     324         [ +  + ]:       49052 :     if (!m_tap_internal_key.IsNull()) {
     325                 :        3674 :         sigdata.tr_spenddata.internal_key = m_tap_internal_key;
     326                 :             :     }
     327         [ +  + ]:       49052 :     if (!m_tap_merkle_root.IsNull()) {
     328                 :        2780 :         sigdata.tr_spenddata.merkle_root = m_tap_merkle_root;
     329                 :             :     }
     330         [ +  + ]:       28666 :     for (const auto& [leaf_script, control_block] : m_tap_scripts) {
     331                 :        4140 :         sigdata.tr_spenddata.scripts.emplace(leaf_script, control_block);
     332                 :             :     }
     333         [ +  + ]:       42990 :     for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
     334                 :       18464 :         sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
     335                 :       18464 :         sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
     336                 :             :     }
     337         [ -  + ]:       24526 :     for (const auto& [hash, preimage] : ripemd160_preimages) {
     338         [ #  # ]:           0 :         sigdata.ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     339                 :             :     }
     340         [ +  + ]:       24538 :     for (const auto& [hash, preimage] : sha256_preimages) {
     341         [ +  - ]:          24 :         sigdata.sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     342                 :             :     }
     343         [ -  + ]:       24526 :     for (const auto& [hash, preimage] : hash160_preimages) {
     344         [ #  # ]:           0 :         sigdata.hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     345                 :             :     }
     346         [ -  + ]:       24526 :     for (const auto& [hash, preimage] : hash256_preimages) {
     347         [ #  # ]:           0 :         sigdata.hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     348                 :             :     }
     349                 :       24526 :     sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
     350         [ +  + ]:       28264 :     for (const auto& [agg_key_lh, pubnonces] : m_musig2_pubnonces) {
     351                 :        3738 :         sigdata.musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
     352                 :             :     }
     353         [ +  + ]:       25459 :     for (const auto& [agg_key_lh, psigs] : m_musig2_partial_sigs) {
     354                 :         933 :         sigdata.musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
     355                 :             :     }
     356                 :             : }
     357                 :             : 
     358                 :       24469 : void PSBTInput::FromSignatureData(const SignatureData& sigdata)
     359                 :             : {
     360         [ +  + ]:       24469 :     if (sigdata.complete) {
     361                 :        1754 :         partial_sigs.clear();
     362                 :        1754 :         hd_keypaths.clear();
     363                 :        1754 :         redeem_script.clear();
     364                 :        1754 :         witness_script.clear();
     365                 :             : 
     366   [ +  +  +  + ]:        2014 :         if (!sigdata.scriptSig.empty()) {
     367                 :         775 :             final_script_sig = sigdata.scriptSig;
     368                 :             :         }
     369         [ +  + ]:        1754 :         if (!sigdata.scriptWitness.IsNull()) {
     370                 :        1494 :             final_script_witness = sigdata.scriptWitness;
     371                 :             :         }
     372                 :        1754 :         return;
     373                 :             :     }
     374                 :             : 
     375                 :       22715 :     partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
     376   [ +  +  +  +  :       22784 :     if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
             +  +  +  + ]
     377                 :         543 :         redeem_script = sigdata.redeem_script;
     378                 :             :     }
     379   [ +  +  +  +  :       22993 :     if (witness_script.empty() && !sigdata.witness_script.empty()) {
             +  +  +  + ]
     380                 :          34 :         witness_script = sigdata.witness_script;
     381                 :             :     }
     382         [ +  + ]:       37493 :     for (const auto& entry : sigdata.misc_pubkeys) {
     383                 :       14778 :         hd_keypaths.emplace(entry.second);
     384                 :             :     }
     385         [ +  + ]:       22715 :     if (!sigdata.taproot_key_path_sig.empty()) {
     386                 :         216 :         m_tap_key_sig = sigdata.taproot_key_path_sig;
     387                 :             :     }
     388         [ +  + ]:       23305 :     for (const auto& [pubkey_leaf, sig] : sigdata.taproot_script_sigs) {
     389                 :         590 :         m_tap_script_sigs.emplace(pubkey_leaf, sig);
     390                 :             :     }
     391         [ +  + ]:       45430 :     if (!sigdata.tr_spenddata.internal_key.IsNull()) {
     392                 :        3569 :         m_tap_internal_key = sigdata.tr_spenddata.internal_key;
     393                 :             :     }
     394         [ +  + ]:       45430 :     if (!sigdata.tr_spenddata.merkle_root.IsNull()) {
     395                 :        2689 :         m_tap_merkle_root = sigdata.tr_spenddata.merkle_root;
     396                 :             :     }
     397         [ +  + ]:       26717 :     for (const auto& [leaf_script, control_block] : sigdata.tr_spenddata.scripts) {
     398                 :        4002 :         m_tap_scripts.emplace(leaf_script, control_block);
     399                 :             :     }
     400         [ +  + ]:       40770 :     for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
     401                 :       18055 :         m_tap_bip32_paths.emplace(pubkey, leaf_origin);
     402                 :             :     }
     403                 :       22715 :     m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
     404         [ +  + ]:       26585 :     for (const auto& [agg_key_lh, pubnonces] : sigdata.musig2_pubnonces) {
     405                 :        3870 :         m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
     406                 :             :     }
     407         [ +  + ]:       23719 :     for (const auto& [agg_key_lh, psigs] : sigdata.musig2_partial_sigs) {
     408                 :        1004 :         m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
     409                 :             :     }
     410         [ -  + ]:       22715 :     for (const auto& [hash, preimage] : sigdata.ripemd160_preimages) {
     411                 :           0 :         ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     412                 :             :     }
     413         [ +  + ]:       22726 :     for (const auto& [hash, preimage] : sigdata.sha256_preimages) {
     414                 :          22 :         sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     415                 :             :     }
     416         [ -  + ]:       22715 :     for (const auto& [hash, preimage] : sigdata.hash160_preimages) {
     417                 :           0 :         hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     418                 :             :     }
     419         [ -  + ]:       22715 :     for (const auto& [hash, preimage] : sigdata.hash256_preimages) {
     420                 :           0 :         hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     421                 :             :     }
     422                 :             : }
     423                 :             : 
     424                 :         204 : bool PSBTInput::Merge(const PSBTInput& input)
     425                 :             : {
     426   [ +  +  +  + ]:         204 :     if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
     427   [ +  +  +  + ]:         204 :     if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
     428                 :           1 :         witness_utxo = input.witness_utxo;
     429                 :             :     }
     430                 :             : 
     431                 :         204 :     partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
     432                 :         204 :     ripemd160_preimages.insert(input.ripemd160_preimages.begin(), input.ripemd160_preimages.end());
     433                 :         204 :     sha256_preimages.insert(input.sha256_preimages.begin(), input.sha256_preimages.end());
     434                 :         204 :     hash160_preimages.insert(input.hash160_preimages.begin(), input.hash160_preimages.end());
     435                 :         204 :     hash256_preimages.insert(input.hash256_preimages.begin(), input.hash256_preimages.end());
     436                 :         204 :     hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
     437                 :         204 :     m_proprietary.insert(input.m_proprietary.begin(), input.m_proprietary.end());
     438                 :         204 :     unknown.insert(input.unknown.begin(), input.unknown.end());
     439                 :         204 :     m_tap_script_sigs.insert(input.m_tap_script_sigs.begin(), input.m_tap_script_sigs.end());
     440                 :             :     // Merge by control block, the serialized key (BIP 371), to avoid duplicate keys. Keep the
     441                 :             :     // leaf script already present; BIP 174 lets the Combiner pick arbitrarily on conflict.
     442                 :         204 :     std::set<std::vector<unsigned char>> seen_control_blocks;
     443   [ +  -  +  + ]:         365 :     for (const auto& [_, control_blocks] : m_tap_scripts) {
     444         [ +  - ]:         161 :         seen_control_blocks.insert(control_blocks.begin(), control_blocks.end());
     445                 :             :     }
     446         [ +  + ]:         364 :     for (const auto& [leaf, control_blocks] : input.m_tap_scripts) {
     447         [ +  + ]:         321 :         for (const auto& control_block : control_blocks) {
     448   [ +  -  +  +  :         161 :             if (seen_control_blocks.insert(control_block).second) m_tap_scripts[leaf].insert(control_block);
             +  -  +  - ]
     449                 :             :         }
     450                 :             :     }
     451         [ +  - ]:         204 :     m_tap_bip32_paths.insert(input.m_tap_bip32_paths.begin(), input.m_tap_bip32_paths.end());
     452                 :             : 
     453   [ +  +  +  +  :         205 :     if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
             -  +  -  + ]
     454   [ +  +  +  +  :         206 :     if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
             -  +  -  + ]
     455   [ -  +  +  -  :         204 :     if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
             -  +  -  + ]
     456   [ +  +  +  +  :         204 :     if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
                   +  - ]
     457   [ +  -  -  +  :         204 :     if (m_tap_key_sig.empty() && !input.m_tap_key_sig.empty()) m_tap_key_sig = input.m_tap_key_sig;
                   -  - ]
     458   [ +  +  -  + ]:         466 :     if (m_tap_internal_key.IsNull() && !input.m_tap_internal_key.IsNull()) m_tap_internal_key = input.m_tap_internal_key;
     459   [ +  +  -  + ]:         507 :     if (m_tap_merkle_root.IsNull() && !input.m_tap_merkle_root.IsNull()) m_tap_merkle_root = input.m_tap_merkle_root;
     460         [ +  - ]:         204 :     m_musig2_participants.insert(input.m_musig2_participants.begin(), input.m_musig2_participants.end());
     461   [ +  -  +  + ]:         437 :     for (const auto& [agg_key_lh, pubnonces] : input.m_musig2_pubnonces) {
     462   [ +  -  +  - ]:         233 :         m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
     463                 :             :     }
     464   [ +  -  +  + ]:         309 :     for (const auto& [agg_key_lh, psigs] : input.m_musig2_partial_sigs) {
     465   [ +  -  +  - ]:         105 :         m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
     466                 :             :     }
     467   [ -  +  -  - ]:         204 :     if (sequence == std::nullopt && input.sequence != std::nullopt) sequence = input.sequence;
     468   [ +  -  -  + ]:         204 :     if (time_locktime == std::nullopt && input.time_locktime != std::nullopt) time_locktime = input.time_locktime;
     469   [ +  -  -  + ]:         204 :     if (height_locktime == std::nullopt && input.height_locktime != std::nullopt) height_locktime = input.height_locktime;
     470                 :             : 
     471                 :         204 :     return true;
     472                 :         204 : }
     473                 :             : 
     474                 :          13 : bool PSBTInput::HasSignatures() const
     475                 :             : {
     476         [ -  + ]:          13 :     return !final_script_sig.empty()
     477         [ +  - ]:          12 :            || !final_script_witness.IsNull()
     478         [ +  - ]:          12 :            || !partial_sigs.empty()
     479         [ +  - ]:          12 :            || !m_tap_key_sig.empty()
     480         [ +  - ]:          12 :            || !m_tap_script_sigs.empty()
     481   [ +  +  -  + ]:          25 :            || !m_musig2_partial_sigs.empty();
     482                 :             : }
     483                 :             : 
     484                 :        1140 : void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
     485                 :             : {
     486   [ -  +  +  + ]:        1140 :     if (!redeem_script.empty()) {
     487                 :           7 :         sigdata.redeem_script = redeem_script;
     488                 :             :     }
     489   [ +  +  +  + ]:        1148 :     if (!witness_script.empty()) {
     490                 :           8 :         sigdata.witness_script = witness_script;
     491                 :             :     }
     492         [ +  + ]:        1498 :     for (const auto& key_pair : hd_keypaths) {
     493                 :         358 :         sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
     494                 :             :     }
     495   [ +  +  +  - ]:        1140 :     if (!m_tap_tree.empty() && m_tap_internal_key.IsFullyValid()) {
     496                 :         145 :         TaprootBuilder builder;
     497   [ -  +  +  + ]:         470 :         for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
     498   [ -  +  +  - ]:         325 :             builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
     499                 :             :         }
     500         [ -  + ]:         145 :         assert(builder.IsComplete());
     501         [ +  - ]:         145 :         builder.Finalize(m_tap_internal_key);
     502         [ +  - ]:         145 :         TaprootSpendData spenddata = builder.GetSpendData();
     503                 :             : 
     504                 :         145 :         sigdata.tr_spenddata.internal_key = m_tap_internal_key;
     505   [ +  -  +  - ]:         145 :         sigdata.tr_spenddata.Merge(spenddata);
     506         [ +  - ]:         145 :         sigdata.tr_builder = builder;
     507                 :         145 :     }
     508         [ +  + ]:        1877 :     for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
     509                 :         737 :         sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
     510                 :         737 :         sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
     511                 :             :     }
     512                 :        1140 :     sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
     513                 :        1140 : }
     514                 :             : 
     515                 :        1140 : void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
     516                 :             : {
     517   [ -  +  +  +  :        1140 :     if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
             -  +  +  + ]
     518                 :          25 :         redeem_script = sigdata.redeem_script;
     519                 :             :     }
     520   [ +  +  +  +  :        1160 :     if (witness_script.empty() && !sigdata.witness_script.empty()) {
             +  +  +  + ]
     521                 :          14 :         witness_script = sigdata.witness_script;
     522                 :             :     }
     523         [ +  + ]:        1970 :     for (const auto& entry : sigdata.misc_pubkeys) {
     524                 :         830 :         hd_keypaths.emplace(entry.second);
     525                 :             :     }
     526         [ +  + ]:        2280 :     if (!sigdata.tr_spenddata.internal_key.IsNull()) {
     527                 :         283 :         m_tap_internal_key = sigdata.tr_spenddata.internal_key;
     528                 :             :     }
     529   [ +  +  +  + ]:        1140 :     if (sigdata.tr_builder.has_value() && sigdata.tr_builder->HasScripts()) {
     530                 :         209 :         m_tap_tree = sigdata.tr_builder->GetTreeTuples();
     531                 :             :     }
     532         [ +  + ]:        2164 :     for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
     533                 :        1024 :         m_tap_bip32_paths.emplace(pubkey, leaf_origin);
     534                 :             :     }
     535                 :        1140 :     m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
     536                 :        1140 : }
     537                 :             : 
     538                 :         388 : bool PSBTOutput::Merge(const PSBTOutput& output)
     539                 :             : {
     540                 :         388 :     hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
     541                 :         388 :     m_proprietary.insert(output.m_proprietary.begin(), output.m_proprietary.end());
     542                 :         388 :     unknown.insert(output.unknown.begin(), output.unknown.end());
     543                 :         388 :     m_tap_bip32_paths.insert(output.m_tap_bip32_paths.begin(), output.m_tap_bip32_paths.end());
     544                 :             : 
     545   [ -  +  +  -  :         388 :     if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
             -  +  -  + ]
     546   [ +  +  +  +  :         389 :     if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
             -  +  -  + ]
     547   [ +  +  -  + ]:        1018 :     if (m_tap_internal_key.IsNull() && !output.m_tap_internal_key.IsNull()) m_tap_internal_key = output.m_tap_internal_key;
     548   [ +  +  -  + ]:         388 :     if (m_tap_tree.empty() && !output.m_tap_tree.empty()) m_tap_tree = output.m_tap_tree;
     549                 :         388 :     m_musig2_participants.insert(output.m_musig2_participants.begin(), output.m_musig2_participants.end());
     550                 :             : 
     551                 :         388 :     return true;
     552                 :             : }
     553                 :             : 
     554                 :       60862 : bool PSBTInputSigned(const PSBTInput& input)
     555                 :             : {
     556   [ +  +  +  +  :       62857 :     return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
                   +  + ]
     557                 :             : }
     558                 :             : 
     559                 :       29919 : bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
     560                 :             : {
     561                 :       29919 :     CTxOut utxo;
     562   [ -  +  -  + ]:       29919 :     assert(input_index < psbt.inputs.size());
     563         [ +  + ]:       29919 :     const PSBTInput& input = psbt.inputs[input_index];
     564                 :             : 
     565         [ +  + ]:       29919 :     if (input.non_witness_utxo) {
     566                 :             :         // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
     567         [ +  - ]:       27725 :         COutPoint prevout = input.GetOutPoint();
     568   [ -  +  +  - ]:       27725 :         if (prevout.n >= input.non_witness_utxo->vout.size()) {
     569                 :             :             return false;
     570                 :             :         }
     571         [ +  - ]:       57644 :         if (input.non_witness_utxo->GetHash() != prevout.hash) {
     572                 :             :             return false;
     573                 :             :         }
     574                 :       27725 :         utxo = input.non_witness_utxo->vout[prevout.n];
     575         [ +  + ]:        2194 :     } else if (!input.witness_utxo.IsNull()) {
     576                 :        2156 :         utxo = input.witness_utxo;
     577                 :             :     } else {
     578                 :             :         return false;
     579                 :             :     }
     580                 :             : 
     581         [ +  - ]:       29881 :     std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
     582         [ +  - ]:       29881 :     if (!unsigned_tx) {
     583                 :             :         return false;
     584                 :             :     }
     585         [ +  + ]:       29881 :     const CMutableTransaction& tx = *unsigned_tx;
     586         [ +  + ]:       29881 :     if (txdata) {
     587         [ +  - ]:       29875 :         return VerifyScript(input.final_script_sig, utxo.scriptPubKey, &input.final_script_witness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker{&tx, input_index, utxo.nValue, *txdata, MissingDataBehavior::FAIL});
     588                 :             :     } else {
     589         [ +  - ]:           6 :         return VerifyScript(input.final_script_sig, utxo.scriptPubKey, &input.final_script_witness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker{&tx, input_index, utxo.nValue, MissingDataBehavior::FAIL});
     590                 :             :     }
     591                 :       59800 : }
     592                 :             : 
     593                 :           0 : size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt) {
     594                 :           0 :     size_t count = 0;
     595         [ #  # ]:           0 :     for (const auto& input : psbt.inputs) {
     596         [ #  # ]:           0 :         if (!PSBTInputSigned(input)) {
     597                 :           0 :             count++;
     598                 :             :         }
     599                 :             :     }
     600                 :             : 
     601                 :           0 :     return count;
     602                 :             : }
     603                 :             : 
     604                 :        1140 : void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index)
     605                 :             : {
     606                 :        1140 :     std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
     607         [ -  + ]:        1140 :     if (!unsigned_tx) {
     608                 :           0 :         return;
     609                 :             :     }
     610         [ +  - ]:        1140 :     const CTxOut& out = unsigned_tx->vout.at(index);
     611         [ +  - ]:        1140 :     PSBTOutput& psbt_out = psbt.outputs.at(index);
     612                 :             : 
     613                 :             :     // Fill a SignatureData with output info
     614                 :        1140 :     SignatureData sigdata;
     615         [ +  - ]:        1140 :     psbt_out.FillSignatureData(sigdata);
     616                 :             : 
     617                 :             :     // Construct a would-be spend of this output, to update sigdata with.
     618                 :             :     // Note that ProduceSignature is used to fill in metadata (not actual signatures),
     619                 :             :     // so provider does not need to provide any private keys (it can be a HidingSigningProvider).
     620         [ +  - ]:        1140 :     CMutableTransaction tx{};
     621         [ +  - ]:        1140 :     tx.vin.emplace_back();
     622         [ +  - ]:        1140 :     MutableTransactionSignatureCreator creator(tx, /*input_idx=*/0, out.nValue, {.sighash_type = SIGHASH_ALL});
     623         [ +  - ]:        1140 :     ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
     624                 :             : 
     625                 :             :     // Put redeem_script, witness_script, key paths, into PSBTOutput.
     626         [ +  - ]:        1140 :     psbt_out.FromSignatureData(sigdata);
     627         [ +  - ]:        3420 : }
     628                 :             : 
     629                 :        1996 : std::optional<PrecomputedTransactionData> PrecomputePSBTData(const PartiallySignedTransaction& psbt)
     630                 :             : {
     631                 :        1996 :     std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
     632         [ -  + ]:        1996 :     if (!unsigned_tx) {
     633                 :           0 :         return std::nullopt;
     634                 :             :     }
     635                 :        1996 :     const CMutableTransaction& tx = *unsigned_tx;
     636                 :        1996 :     bool have_all_spent_outputs = true;
     637                 :        1996 :     std::vector<CTxOut> utxos;
     638         [ +  + ]:        7834 :     for (const PSBTInput& input : psbt.inputs) {
     639   [ +  -  +  -  :        5838 :         if (!input.GetUTXO(utxos.emplace_back())) have_all_spent_outputs = false;
                   +  + ]
     640                 :             :     }
     641                 :        1996 :     PrecomputedTransactionData txdata;
     642         [ +  + ]:        1996 :     if (have_all_spent_outputs) {
     643         [ +  - ]:        1964 :         txdata.Init(tx, std::move(utxos), true);
     644                 :             :     } else {
     645         [ +  - ]:          32 :         txdata.Init(tx, {}, true);
     646                 :             :     }
     647                 :        1996 :     return txdata;
     648                 :        3992 : }
     649                 :             : 
     650                 :       25992 : util::Expected<void, PSBTError> SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options,  SignatureData* out_sigdata)
     651                 :             : {
     652                 :       25992 :     PSBTInput& input = psbt.inputs.at(index);
     653                 :       25992 :     std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
     654         [ -  + ]:       25992 :     if (!unsigned_tx) {
     655                 :           0 :         return util::Unexpected{PSBTError::INVALID_TX};
     656                 :             :     }
     657         [ +  - ]:       25992 :     const CMutableTransaction& tx = *unsigned_tx;
     658                 :             : 
     659   [ +  -  +  + ]:       25992 :     if (PSBTInputSignedAndVerified(psbt, index, txdata)) {
     660                 :        1466 :         return {};
     661                 :             :     }
     662                 :             : 
     663                 :             :     // Fill SignatureData with input info
     664                 :       24526 :     SignatureData sigdata;
     665         [ +  - ]:       24526 :     input.FillSignatureData(sigdata);
     666                 :             : 
     667                 :             :     // Get UTXO
     668                 :       24526 :     bool require_witness_sig = false;
     669                 :       24526 :     CTxOut utxo;
     670                 :             : 
     671         [ +  + ]:       24526 :     if (input.non_witness_utxo) {
     672                 :             :         // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
     673         [ +  - ]:       23290 :         COutPoint prevout = input.GetOutPoint();
     674   [ -  +  -  + ]:       23290 :         if (prevout.n >= input.non_witness_utxo->vout.size()) {
     675                 :           0 :             return util::Unexpected{PSBTError::MISSING_INPUTS};
     676                 :             :         }
     677         [ +  - ]:       23290 :         if (input.non_witness_utxo->GetHash() != prevout.hash) {
     678                 :           0 :             return util::Unexpected{PSBTError::MISSING_INPUTS};
     679                 :             :         }
     680                 :       23290 :         utxo = input.non_witness_utxo->vout[prevout.n];
     681         [ +  + ]:        1236 :     } else if (!input.witness_utxo.IsNull()) {
     682                 :        1226 :         utxo = input.witness_utxo;
     683                 :             :         // When we're taking our information from a witness UTXO, we can't verify it is actually data from
     684                 :             :         // the output being spent. This is safe in case a witness signature is produced (which includes this
     685                 :             :         // information directly in the hash), but not for non-witness signatures. Remember that we require
     686                 :             :         // a witness signature in this situation.
     687                 :        1226 :         require_witness_sig = true;
     688                 :             :     } else {
     689                 :          10 :         return util::Unexpected{PSBTError::MISSING_INPUTS};
     690                 :             :     }
     691                 :             : 
     692                 :             :     // Get the sighash type
     693                 :             :     // If both the field and the parameter are provided, they must match
     694                 :             :     // If only the parameter is provided, use it and add it to the PSBT if it is other than SIGHASH_DEFAULT
     695                 :             :     // for all input types, and not SIGHASH_ALL for non-taproot input types.
     696                 :             :     // If neither are provided, use SIGHASH_DEFAULT if it is taproot, and SIGHASH_ALL for everything else.
     697   [ +  -  +  +  :       44047 :     int sighash{options.sighash_type.value_or(utxo.scriptPubKey.IsPayToTaproot() ? SIGHASH_DEFAULT : SIGHASH_ALL)};
                   +  + ]
     698                 :             : 
     699                 :             :     // For user safety, the desired sighash must be provided if the PSBT wants something other than the default set in the previous line.
     700   [ +  +  +  + ]:       24516 :     if (input.sighash_type && input.sighash_type != sighash) {
     701                 :          14 :         return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     702                 :             :     }
     703                 :             :     // Set the PSBT sighash field when sighash is not DEFAULT or ALL
     704                 :             :     // DEFAULT is allowed for non-taproot inputs since DEFAULT may be passed for them (e.g. the psbt being signed also has taproot inputs)
     705                 :             :     // Note that signing already aliases DEFAULT to ALL for non-taproot inputs.
     706   [ +  -  +  +  :       44019 :     if (utxo.scriptPubKey.IsPayToTaproot() ? sighash != SIGHASH_DEFAULT :
                   +  + ]
     707                 :       19517 :                                             (sighash != SIGHASH_DEFAULT && sighash != SIGHASH_ALL)) {
     708                 :         158 :         input.sighash_type = sighash;
     709                 :             :     }
     710                 :             : 
     711                 :             :     // Check all existing signatures use the sighash type
     712         [ +  + ]:       24502 :     if (sighash == SIGHASH_DEFAULT) {
     713   [ +  +  -  +  :        4847 :         if (!input.m_tap_key_sig.empty() && input.m_tap_key_sig.size() != 64) {
                   +  - ]
     714                 :           0 :             return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     715                 :             :         }
     716   [ -  +  +  + ]:        5370 :         for (const auto& [_, sig] : input.m_tap_script_sigs) {
     717   [ -  +  -  + ]:         523 :             if (sig.size() != 64) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     718                 :             :         }
     719                 :             :     } else {
     720   [ +  +  -  +  :       19655 :         if (!input.m_tap_key_sig.empty() && (input.m_tap_key_sig.size() != 65 || input.m_tap_key_sig.back() != sighash)) {
             +  -  +  + ]
     721                 :           2 :             return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     722                 :             :         }
     723   [ -  -  -  + ]:       19653 :         for (const auto& [_, sig] : input.m_tap_script_sigs) {
     724   [ #  #  #  #  :           0 :             if (sig.size() != 65 || sig.back() != sighash) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
                   #  # ]
     725                 :             :         }
     726   [ +  +  +  + ]:       20034 :         for (const auto& [_, sig] : input.partial_sigs) {
     727         [ +  + ]:         383 :             if (sig.second.back() != sighash) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     728                 :             :         }
     729                 :             :     }
     730                 :             : 
     731                 :       24498 :     sigdata.witness = false;
     732                 :       24498 :     bool sig_complete;
     733         [ +  + ]:       24498 :     if (txdata == nullptr) {
     734         [ +  - ]:           3 :         sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
     735                 :             :     } else {
     736         [ +  - ]:       24495 :         MutableTransactionSignatureCreator creator(tx, index, utxo.nValue, txdata, {.sighash_type = sighash});
     737         [ +  - ]:       24495 :         sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
     738                 :       24495 :     }
     739                 :             :     // Verify that a witness signature was produced in case one was required.
     740   [ +  +  +  + ]:       24498 :     if (require_witness_sig && !sigdata.witness) return util::Unexpected{PSBTError::INCOMPLETE};
     741                 :             : 
     742                 :             :     // If we are not finalizing, set sigdata.complete to false to not set the scriptWitness
     743   [ +  +  +  + ]:       24469 :     if (!options.finalize && sigdata.complete) sigdata.complete = false;
     744                 :             : 
     745         [ +  - ]:       24469 :     input.FromSignatureData(sigdata);
     746                 :             : 
     747                 :             :     // If we have a witness signature, put a witness UTXO.
     748         [ +  + ]:       24469 :     if (sigdata.witness) {
     749                 :       19698 :         input.witness_utxo = utxo;
     750                 :             :         // We can remove the non_witness_utxo if and only if there are no non-segwit or segwit v0
     751                 :             :         // inputs in this transaction. Since this requires inspecting the entire transaction, this
     752                 :             :         // is something for the caller to deal with (i.e. FillPSBT).
     753                 :             :     }
     754                 :             : 
     755                 :             :     // Fill in the missing info
     756         [ +  + ]:       24469 :     if (out_sigdata) {
     757         [ +  - ]:           6 :         out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
     758         [ +  - ]:           6 :         out_sigdata->missing_sigs = sigdata.missing_sigs;
     759                 :           6 :         out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
     760                 :           6 :         out_sigdata->missing_witness_script = sigdata.missing_witness_script;
     761                 :             :     }
     762                 :             : 
     763         [ +  + ]:       24469 :     if (!sig_complete) return util::Unexpected{PSBTError::INCOMPLETE};
     764                 :        2448 :     return {};
     765                 :       50518 : }
     766                 :             : 
     767                 :        1371 : void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx)
     768                 :             : {
     769                 :             :     // Figure out if any non_witness_utxos should be dropped
     770                 :        1371 :     std::vector<unsigned int> to_drop;
     771   [ -  +  +  + ]:        2226 :     for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
     772         [ +  - ]:        1584 :         const auto& input = psbtx.inputs.at(i);
     773                 :        1584 :         int wit_ver;
     774                 :        1584 :         std::vector<unsigned char> wit_prog;
     775   [ +  +  +  -  :        1584 :         if (input.witness_utxo.IsNull() || !input.witness_utxo.scriptPubKey.IsWitnessProgram(wit_ver, wit_prog)) {
                   +  + ]
     776                 :             :             // There's a non-segwit input, so we cannot drop any non_witness_utxos
     777         [ -  + ]:         251 :             to_drop.clear();
     778                 :             :             break;
     779                 :             :         }
     780         [ +  + ]:        1333 :         if (wit_ver == 0) {
     781                 :             :             // Segwit v0, so we cannot drop any non_witness_utxos
     782         [ -  + ]:         466 :             to_drop.clear();
     783                 :             :             break;
     784                 :             :         }
     785                 :             :         // non_witness_utxos cannot be dropped if the sighash type includes SIGHASH_ANYONECANPAY
     786                 :             :         // Since callers should have called SignPSBTInput which updates the sighash type in the PSBT, we only
     787                 :             :         // need to look at that field. If it is not present, then we can assume SIGHASH_DEFAULT or SIGHASH_ALL.
     788   [ +  +  +  + ]:         867 :         if (input.sighash_type != std::nullopt && (*input.sighash_type & 0x80) == SIGHASH_ANYONECANPAY) {
     789         [ -  + ]:         729 :             to_drop.clear();
     790                 :             :             break;
     791                 :             :         }
     792                 :             : 
     793         [ +  + ]:         855 :         if (input.non_witness_utxo) {
     794         [ +  - ]:         558 :             to_drop.push_back(i);
     795                 :             :         }
     796                 :        1584 :     }
     797                 :             : 
     798                 :             :     // Drop the non_witness_utxos that we can drop
     799         [ +  + ]:        1929 :     for (unsigned int i : to_drop) {
     800   [ +  -  -  + ]:         558 :         psbtx.inputs.at(i).non_witness_utxo = nullptr;
     801                 :             :     }
     802                 :        1371 : }
     803                 :             : 
     804                 :         585 : bool FinalizePSBT(PartiallySignedTransaction& psbtx)
     805                 :             : {
     806                 :             :     // Finalize input signatures -- in case we have partial signatures that add up to a complete
     807                 :             :     //   signature, but have not combined them yet (e.g. because the combiner that created this
     808                 :             :     //   PartiallySignedTransaction did not understand them), this will combine them into a final
     809                 :             :     //   script.
     810                 :         585 :     bool complete = true;
     811                 :         585 :     std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbtx);
     812         [ +  - ]:         585 :     if (!txdata_res) {
     813                 :             :         return false;
     814                 :             :     }
     815                 :             :     const PrecomputedTransactionData& txdata = *txdata_res;
     816   [ -  +  +  + ]:        2446 :     for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
     817         [ +  - ]:        1861 :         PSBTInput& input = psbtx.inputs.at(i);
     818         [ +  - ]:        1861 :         const auto sign_result = SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, {.sighash_type = input.sighash_type, .finalize = true}, /*out_sigdata=*/nullptr);
     819                 :        1861 :         complete &= sign_result.has_value();
     820                 :             :     }
     821                 :             : 
     822                 :             :     return complete;
     823                 :         585 : }
     824                 :             : 
     825                 :         582 : bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result)
     826                 :             : {
     827                 :             :     // It's not safe to extract a PSBT that isn't finalized, and there's no easy way to check
     828                 :             :     //   whether a PSBT is finalized without finalizing it, so we just do this.
     829         [ +  + ]:         582 :     if (!FinalizePSBT(psbtx)) {
     830                 :             :         return false;
     831                 :             :     }
     832                 :             : 
     833                 :         541 :     std::optional<CMutableTransaction> unsigned_tx = psbtx.GetUnsignedTx();
     834         [ +  - ]:         541 :     if (!unsigned_tx) {
     835                 :             :         return false;
     836                 :             :     }
     837         [ +  - ]:         541 :     result = *unsigned_tx;
     838   [ -  +  +  + ]:        2309 :     for (unsigned int i = 0; i < result.vin.size(); ++i) {
     839                 :        1768 :         result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
     840         [ +  - ]:        1768 :         result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
     841                 :             :     }
     842                 :             :     return true;
     843                 :         541 : }
     844                 :             : 
     845                 :         108 : std::optional<PartiallySignedTransaction> CombinePSBTs(const std::vector<PartiallySignedTransaction>& psbtxs)
     846                 :             : {
     847                 :         108 :     PartiallySignedTransaction out = psbtxs[0]; // Copy the first one
     848                 :             : 
     849                 :             :     // Merge
     850         [ +  + ]:         309 :     for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
     851   [ +  -  +  + ]:         202 :         if (!out.Merge(*it)) {
     852                 :           1 :             return std::nullopt;
     853                 :             :         }
     854                 :             :     }
     855                 :         107 :     return out;
     856                 :         108 : }
     857                 :             : 
     858                 :          20 : std::string PSBTRoleName(PSBTRole role) {
     859   [ +  +  +  +  :          20 :     switch (role) {
                   +  - ]
     860                 :           3 :     case PSBTRole::CREATOR: return "creator";
     861                 :           9 :     case PSBTRole::UPDATER: return "updater";
     862                 :           2 :     case PSBTRole::SIGNER: return "signer";
     863                 :           4 :     case PSBTRole::FINALIZER: return "finalizer";
     864                 :           2 :     case PSBTRole::EXTRACTOR: return "extractor";
     865                 :             :     } // no default case, so the compiler can warn about missing cases
     866                 :           0 :     assert(false);
     867                 :             : }
     868                 :             : 
     869                 :        1823 : util::Result<PartiallySignedTransaction> DecodeBase64PSBT(const std::string& base64_tx)
     870                 :             : {
     871         [ -  + ]:        1823 :     auto tx_data = DecodeBase64(base64_tx);
     872         [ +  + ]:        1823 :     if (!tx_data) {
     873   [ +  -  +  - ]:          12 :         return util::Error{Untranslated("invalid base64")};
     874                 :             :     }
     875         [ +  - ]:        1819 :     return DecodeRawPSBT(MakeByteSpan(*tx_data));
     876                 :        1823 : }
     877                 :             : 
     878                 :        1819 : util::Result<PartiallySignedTransaction> DecodeRawPSBT(std::span<const std::byte> tx_data)
     879                 :             : {
     880         [ +  + ]:        1819 :     SpanReader ss_data{tx_data};
     881                 :        1819 :     try {
     882         [ +  + ]:        1819 :         PartiallySignedTransaction psbt(deserialize, ss_data);
     883         [ -  + ]:        1732 :         if (!ss_data.empty()) {
     884   [ #  #  #  # ]:           0 :             return util::Error{Untranslated("extra data after PSBT")};
     885                 :             :         }
     886                 :        1732 :         return psbt;
     887         [ -  + ]:        1819 :     } catch (const std::exception& e) {
     888   [ +  -  +  - ]:         261 :         return util::Error{Untranslated(e.what())};
     889                 :          87 :     }
     890                 :             : }
     891                 :             : 
     892                 :       74958 : uint32_t PartiallySignedTransaction::GetVersion() const
     893                 :             : {
     894         [ +  + ]:       74958 :     if (m_version != std::nullopt) {
     895                 :       73713 :         return *m_version;
     896                 :             :     }
     897                 :             :     return 0;
     898                 :             : }
        

Generated by: LCOV version 2.0-1