LCOV - code coverage report
Current view: top level - src - psbt.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 86.1 % 509 438
Test Date: 2026-08-29 05:53:03 Functions: 96.9 % 32 31
Branches: 66.1 % 802 530

             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         [ +  + ]:        1580 : PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx, uint32_t version) : m_version(version)
      22                 :             : {
      23   [ +  +  -  + ]:        1580 :     assert(m_version == 0 || m_version == 2);
      24                 :             : 
      25                 :        1580 :     tx_version = tx.version;
      26         [ -  + ]:        1580 :     fallback_locktime = tx.nLockTime;
      27   [ -  +  +  - ]:        1580 :     inputs.reserve(tx.vin.size());
      28         [ +  + ]:        3407 :     for (const CTxIn& input : tx.vin) {
      29   [ +  -  +  - ]:        1827 :         inputs.emplace_back(GetVersion(), input.prevout.hash, input.prevout.n, input.nSequence);
      30                 :             :     }
      31   [ -  +  +  - ]:        1580 :     outputs.reserve(tx.vout.size());
      32         [ +  + ]:       11333 :     for (const CTxOut& output : tx.vout) {
      33   [ +  -  +  - ]:        9753 :         outputs.emplace_back(GetVersion(), output.nValue, output.scriptPubKey);
      34                 :             :     }
      35                 :        1580 : }
      36                 :             : 
      37                 :       21812 : bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt)
      38                 :             : {
      39                 :             :     // Prohibited to merge two PSBTs over different transactions
      40                 :       21812 :     std::optional<Txid> this_id = GetUniqueID();
      41                 :       21812 :     std::optional<Txid> psbt_id = psbt.GetUniqueID();
      42   [ +  -  +  -  :       21812 :     if (!this_id || !psbt_id || this_id != psbt_id) {
                   +  + ]
      43                 :             :         return false;
      44                 :             :     }
      45         [ +  - ]:       20634 :     if (GetVersion() != psbt.GetVersion()) {
      46                 :             :         return false;
      47                 :             :     }
      48                 :             : 
      49   [ -  +  +  + ]:       50700 :     for (unsigned int i = 0; i < inputs.size(); ++i) {
      50         [ +  - ]:       30066 :         if (!inputs[i].Merge(psbt.inputs[i])) {
      51                 :             :             return false;
      52                 :             :         }
      53                 :             :     }
      54   [ -  +  +  + ]:       46670 :     for (unsigned int i = 0; i < outputs.size(); ++i) {
      55         [ +  - ]:       26036 :         if (!outputs[i].Merge(psbt.outputs[i])) {
      56                 :             :             return false;
      57                 :             :         }
      58                 :             :     }
      59                 :       20634 :     MergeGlobalXPubs(psbt);
      60   [ -  +  -  - ]:       20634 :     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   [ +  -  -  + ]:       20634 :     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                 :       20634 :     m_proprietary.insert(psbt.m_proprietary.begin(), psbt.m_proprietary.end());
      75                 :       20634 :     unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
      76                 :             : 
      77                 :       20634 :     return true;
      78                 :             : }
      79                 :             : 
      80                 :       20640 : void PartiallySignedTransaction::MergeGlobalXPubs(const PartiallySignedTransaction& psbt)
      81                 :             : {
      82         [ +  + ]:       25667 :     for (const auto& [origin, xpubs] : psbt.m_xpubs) {
      83         [ +  + ]:       11444 :         for (const CExtPubKey& xpub : xpubs) {
      84                 :       77298 :             const bool known{std::ranges::any_of(m_xpubs, [&](const auto& entry) { return entry.second.contains(xpub); })};
      85         [ +  + ]:        6417 :             if (!known) m_xpubs[origin].insert(xpub);
      86                 :             :         }
      87                 :             :     }
      88                 :       20640 : }
      89                 :             : 
      90                 :      206914 : std::optional<uint32_t> PartiallySignedTransaction::ComputeTimeLock() const
      91                 :             : {
      92         [ -  + ]:      206914 :     if (GetVersion() >= 2) {
      93                 :           0 :         std::optional<uint32_t> time_lock{0};
      94                 :           0 :         std::optional<uint32_t> height_lock{0};
      95         [ #  # ]:           0 :         for (const PSBTInput& input : inputs) {
      96   [ #  #  #  # ]:           0 :             if (input.time_locktime.has_value() && !input.height_locktime.has_value()) {
      97         [ #  # ]:           0 :                 height_lock.reset(); // Transaction can no longer have a height locktime
      98         [ #  # ]:           0 :                 if (!time_lock.has_value()) {
      99                 :           0 :                     return std::nullopt;
     100                 :             :                 }
     101   [ #  #  #  # ]:           0 :             } else if (!input.time_locktime.has_value() && input.height_locktime.has_value()) {
     102         [ #  # ]:           0 :                 time_lock.reset(); // Transaction can no longer have a time locktime
     103         [ #  # ]:           0 :                 if (!height_lock.has_value()) {
     104                 :           0 :                     return std::nullopt;
     105                 :             :                 }
     106                 :             :             }
     107   [ #  #  #  # ]:           0 :             if (input.time_locktime && time_lock.has_value()) {
     108                 :           0 :                 time_lock = std::max(time_lock, input.time_locktime);
     109                 :             :             }
     110   [ #  #  #  # ]:           0 :             if (input.height_locktime && height_lock.has_value()) {
     111                 :           0 :                 height_lock = std::max(height_lock, input.height_locktime);
     112                 :             :             }
     113                 :             :         }
     114   [ #  #  #  # ]:           0 :         if (height_lock.has_value() && *height_lock > 0) {
     115                 :           0 :             return *height_lock;
     116                 :             :         }
     117   [ #  #  #  # ]:           0 :         if (time_lock.has_value() && *time_lock > 0) {
     118                 :           0 :             return *time_lock;
     119                 :             :         }
     120                 :             :     }
     121         [ +  - ]:      413828 :     return fallback_locktime.value_or(0);
     122                 :             : }
     123                 :             : 
     124                 :      206914 : std::optional<CMutableTransaction> PartiallySignedTransaction::GetUnsignedTx() const
     125                 :             : {
     126                 :      206914 :     CMutableTransaction mtx;
     127                 :      206914 :     mtx.version = tx_version;
     128         [ +  - ]:      206914 :     std::optional<uint32_t> locktime = ComputeTimeLock();
     129         [ -  + ]:      206914 :     if (!locktime) {
     130                 :           0 :         return std::nullopt;
     131                 :             :     }
     132                 :      206914 :     mtx.nLockTime = *locktime;
     133                 :      206914 :     uint32_t max_sequence = CTxIn::SEQUENCE_FINAL;
     134         [ +  + ]:      644663 :     for (const PSBTInput& input : inputs) {
     135                 :      437749 :         CTxIn txin;
     136                 :      437749 :         txin.prevout.hash = input.prev_txid;
     137                 :      437749 :         txin.prevout.n = input.prev_out;
     138         [ +  - ]:      437749 :         txin.nSequence = input.sequence.value_or(max_sequence);
     139         [ +  - ]:      437749 :         mtx.vin.push_back(txin);
     140                 :      437749 :     }
     141         [ +  + ]:      476579 :     for (const PSBTOutput& output : outputs) {
     142                 :      269665 :         CTxOut txout;
     143                 :      269665 :         txout.nValue = output.amount;
     144                 :      269665 :         txout.scriptPubKey = output.script;
     145         [ +  - ]:      269665 :         mtx.vout.push_back(txout);
     146                 :      269665 :     }
     147                 :      206914 :     return mtx;
     148                 :      206914 : }
     149                 :             : 
     150                 :       43624 : std::optional<Txid> PartiallySignedTransaction::GetUniqueID() const
     151                 :             : {
     152                 :             :     // Get the unsigned transaction
     153                 :       43624 :     std::optional<CMutableTransaction> mtx = GetUnsignedTx();
     154         [ -  + ]:       43624 :     if (!mtx) {
     155                 :           0 :         return std::nullopt;
     156                 :             :     }
     157   [ +  -  -  + ]:       43624 :     if (GetVersion() >= 2) {
     158         [ #  # ]:           0 :         for (CTxIn& txin : mtx->vin) {
     159                 :           0 :             txin.nSequence = 0;
     160                 :             :         }
     161                 :             :     }
     162         [ +  - ]:       43624 :     return mtx->GetHash();
     163                 :       43624 : }
     164                 :             : 
     165                 :       13986 : bool PartiallySignedTransaction::AddInput(const PSBTInput& psbtin)
     166                 :             : {
     167                 :             :     // The input being added must be for this PSBT's version
     168         [ +  - ]:       13986 :     if (psbtin.GetVersion() != GetVersion()) {
     169                 :             :         return false;
     170                 :             :     }
     171                 :             : 
     172                 :             :     // Prevent duplicate inputs
     173         [ +  - ]:       13986 :     if (std::find_if(inputs.begin(), inputs.end(),
     174   [ +  -  +  + ]:       83916 :         [psbtin](const PSBTInput& psbt) {
     175   [ +  +  +  + ]:       38532 :             return psbt.prev_txid == psbtin.prev_txid && psbt.prev_out == psbtin.prev_out;
     176                 :             :         }
     177                 :       27972 :     ) != inputs.end()) {
     178                 :             :         return false;
     179                 :             :     }
     180                 :             : 
     181         [ +  - ]:         963 :     if (GetVersion() < 2) {
     182                 :             :         // This is a v0 psbt, so do the v0 AddInput
     183                 :         963 :         inputs.push_back(psbtin);
     184                 :         963 :         inputs.back().partial_sigs.clear();
     185                 :         963 :         inputs.back().final_script_sig.clear();
     186                 :         963 :         inputs.back().final_script_witness.SetNull();
     187                 :         963 :         return true;
     188                 :             :     }
     189                 :             : 
     190                 :             :     // Check inputs modifiable flag
     191   [ #  #  #  # ]:           0 :     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   [ #  #  #  # ]:           0 :     bool iterate_inputs = psbtin.time_locktime != std::nullopt || psbtin.height_locktime != std::nullopt;
     201                 :           0 :     if (iterate_inputs) {
     202                 :           0 :         std::optional<uint32_t> old_timelock = ComputeTimeLock();
     203         [ #  # ]:           0 :         if (!old_timelock) {
     204                 :             :             return false;
     205                 :             :         }
     206                 :             : 
     207                 :           0 :         std::optional<uint32_t> time_lock = psbtin.time_locktime;
     208                 :           0 :         std::optional<uint32_t> height_lock = psbtin.height_locktime;
     209                 :           0 :         bool has_sigs = false;
     210         [ #  # ]:           0 :         for (const PSBTInput& input : inputs) {
     211   [ #  #  #  # ]:           0 :             if (input.time_locktime.has_value() && !input.height_locktime.has_value()) {
     212         [ #  # ]:           0 :                 height_lock.reset(); // Transaction can no longer have a height locktime
     213         [ #  # ]:           0 :                 if (time_lock == std::nullopt) {
     214                 :             :                     return false;
     215                 :             :                 }
     216   [ #  #  #  # ]:           0 :             } 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   [ #  #  #  # ]:           0 :             if (input.time_locktime && time_lock.has_value()) {
     223                 :           0 :                 time_lock = std::max(time_lock, input.time_locktime);
     224                 :             :             }
     225   [ #  #  #  # ]:           0 :             if (input.height_locktime && height_lock.has_value()) {
     226                 :           0 :                 height_lock = std::max(height_lock, input.height_locktime);
     227                 :             :             }
     228         [ #  # ]:           0 :             if (input.HasSignatures()) {
     229                 :           0 :                 has_sigs = true;
     230                 :             :             }
     231                 :             :         }
     232         [ #  # ]:           0 :         uint32_t new_timelock = fallback_locktime.value_or(0);
     233   [ #  #  #  # ]:           0 :         if (height_lock.has_value() && *height_lock > 0) {
     234                 :             :             new_timelock = *height_lock;
     235   [ #  #  #  # ]:           0 :         } else if (time_lock.has_value() && *time_lock > 0) {
     236                 :             :             new_timelock = *time_lock;
     237                 :             :         }
     238   [ #  #  #  # ]:           0 :         if (has_sigs && *old_timelock != new_timelock) {
     239                 :             :             return false;
     240                 :             :         }
     241                 :             :     }
     242                 :             : 
     243                 :             :     // Add the input to the end
     244                 :           0 :     inputs.push_back(psbtin);
     245                 :           0 :     return true;
     246                 :             : }
     247                 :             : 
     248                 :       14402 : bool PartiallySignedTransaction::AddOutput(const PSBTOutput& psbtout)
     249                 :             : {
     250                 :             :     // The output being added must be for this PSBT's version
     251         [ +  - ]:       14402 :     if (psbtout.GetVersion() != GetVersion()) {
     252                 :             :         return false;
     253                 :             :     }
     254                 :             : 
     255         [ +  - ]:       14402 :     if (GetVersion() < 2) {
     256                 :             :         // This is a v0 psbt, do the v0 AddOutput
     257                 :       14402 :         outputs.push_back(psbtout);
     258                 :       14402 :         return true;
     259                 :             :     }
     260                 :             : 
     261                 :             :     // No global tx, must be PSBTv2
     262                 :             :     // Check outputs are modifiable
     263   [ #  #  #  # ]:           0 :     if (!m_tx_modifiable.has_value() || !m_tx_modifiable->test(1)) {
     264                 :             :         return false;
     265                 :             :     }
     266                 :           0 :     outputs.push_back(psbtout);
     267                 :             : 
     268                 :           0 :     return true;
     269                 :             : }
     270                 :             : 
     271                 :       75652 : bool PSBTInput::GetUTXO(CTxOut& utxo) const
     272                 :             : {
     273         [ +  + ]:       75652 :     if (non_witness_utxo) {
     274   [ -  +  +  - ]:        1778 :         if (prev_out >= non_witness_utxo->vout.size()) {
     275                 :             :             return false;
     276                 :             :         }
     277         [ +  - ]:        1778 :         if (non_witness_utxo->GetHash() != prev_txid) {
     278                 :             :             return false;
     279                 :             :         }
     280                 :        1778 :         utxo = non_witness_utxo->vout[prev_out];
     281         [ +  + ]:       73874 :     } else if (!witness_utxo.IsNull()) {
     282                 :       43430 :         utxo = witness_utxo;
     283                 :             :     } else {
     284                 :             :         return false;
     285                 :             :     }
     286                 :             :     return true;
     287                 :             : }
     288                 :             : 
     289                 :        4449 : COutPoint PSBTInput::GetOutPoint() const
     290                 :             : {
     291                 :        4449 :     return COutPoint(prev_txid, prev_out);
     292                 :             : }
     293                 :             : 
     294                 :       55589 : void PSBTInput::FillSignatureData(SignatureData& sigdata) const
     295                 :             : {
     296   [ +  +  +  + ]:       63066 :     if (!final_script_sig.empty()) {
     297                 :        9072 :         sigdata.scriptSig = final_script_sig;
     298                 :        9072 :         sigdata.complete = true;
     299                 :             :     }
     300         [ +  + ]:       55589 :     if (!final_script_witness.IsNull()) {
     301                 :        1278 :         sigdata.scriptWitness = final_script_witness;
     302                 :        1278 :         sigdata.complete = true;
     303                 :             :     }
     304         [ +  + ]:       55589 :     if (sigdata.complete) {
     305                 :             :         return;
     306                 :             :     }
     307                 :             : 
     308                 :       45245 :     sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
     309   [ +  +  +  + ]:       45950 :     if (!redeem_script.empty()) {
     310                 :        2018 :         sigdata.redeem_script = redeem_script;
     311                 :             :     }
     312   [ +  +  +  + ]:       46183 :     if (!witness_script.empty()) {
     313                 :        1521 :         sigdata.witness_script = witness_script;
     314                 :             :     }
     315         [ +  + ]:       53858 :     for (const auto& key_pair : hd_keypaths) {
     316                 :        8613 :         sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
     317                 :             :     }
     318         [ +  + ]:       45245 :     if (!m_tap_key_sig.empty()) {
     319                 :        1564 :         sigdata.taproot_key_path_sig = m_tap_key_sig;
     320                 :             :     }
     321         [ +  + ]:       50778 :     for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
     322                 :        5533 :         sigdata.taproot_script_sigs.emplace(pubkey_leaf, sig);
     323                 :             :     }
     324         [ +  + ]:       90490 :     if (!m_tap_internal_key.IsNull()) {
     325                 :         362 :         sigdata.tr_spenddata.internal_key = m_tap_internal_key;
     326                 :             :     }
     327         [ +  + ]:       90490 :     if (!m_tap_merkle_root.IsNull()) {
     328                 :         314 :         sigdata.tr_spenddata.merkle_root = m_tap_merkle_root;
     329                 :             :     }
     330         [ +  + ]:       79180 :     for (const auto& [leaf_script, control_block] : m_tap_scripts) {
     331                 :       33935 :         sigdata.tr_spenddata.scripts.emplace(leaf_script, control_block);
     332                 :             :     }
     333         [ +  + ]:       54594 :     for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
     334                 :        9349 :         sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
     335                 :        9349 :         sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
     336                 :             :     }
     337         [ +  + ]:       49117 :     for (const auto& [hash, preimage] : ripemd160_preimages) {
     338         [ +  - ]:        7744 :         sigdata.ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     339                 :             :     }
     340         [ +  + ]:       63850 :     for (const auto& [hash, preimage] : sha256_preimages) {
     341         [ +  - ]:       37210 :         sigdata.sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     342                 :             :     }
     343         [ +  + ]:       65061 :     for (const auto& [hash, preimage] : hash160_preimages) {
     344         [ +  - ]:       39632 :         sigdata.hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     345                 :             :     }
     346         [ +  + ]:       55117 :     for (const auto& [hash, preimage] : hash256_preimages) {
     347         [ +  - ]:       19744 :         sigdata.hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     348                 :             :     }
     349                 :       45245 :     sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
     350         [ +  + ]:       48766 :     for (const auto& [agg_key_lh, pubnonces] : m_musig2_pubnonces) {
     351                 :        3521 :         sigdata.musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
     352                 :             :     }
     353         [ +  + ]:       48236 :     for (const auto& [agg_key_lh, psigs] : m_musig2_partial_sigs) {
     354                 :        2991 :         sigdata.musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
     355                 :             :     }
     356                 :             : }
     357                 :             : 
     358                 :       23850 : void PSBTInput::FromSignatureData(const SignatureData& sigdata)
     359                 :             : {
     360         [ +  + ]:       23850 :     if (sigdata.complete) {
     361                 :        3577 :         partial_sigs.clear();
     362                 :        3577 :         hd_keypaths.clear();
     363                 :        3577 :         redeem_script.clear();
     364                 :        3577 :         witness_script.clear();
     365                 :             : 
     366   [ +  +  +  + ]:        5728 :         if (!sigdata.scriptSig.empty()) {
     367                 :        2756 :             final_script_sig = sigdata.scriptSig;
     368                 :             :         }
     369         [ +  + ]:        3577 :         if (!sigdata.scriptWitness.IsNull()) {
     370                 :         877 :             final_script_witness = sigdata.scriptWitness;
     371                 :             :         }
     372                 :        3577 :         return;
     373                 :             :     }
     374                 :             : 
     375                 :       20273 :     partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
     376   [ +  +  +  +  :       20690 :     if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
             +  +  +  + ]
     377                 :         453 :         redeem_script = sigdata.redeem_script;
     378                 :             :     }
     379   [ +  +  +  +  :       20744 :     if (witness_script.empty() && !sigdata.witness_script.empty()) {
             +  +  +  + ]
     380                 :         316 :         witness_script = sigdata.witness_script;
     381                 :             :     }
     382         [ +  + ]:       27186 :     for (const auto& entry : sigdata.misc_pubkeys) {
     383                 :        6913 :         hd_keypaths.emplace(entry.second);
     384                 :             :     }
     385         [ +  + ]:       20273 :     if (!sigdata.taproot_key_path_sig.empty()) {
     386                 :        1055 :         m_tap_key_sig = sigdata.taproot_key_path_sig;
     387                 :             :     }
     388         [ +  + ]:       22261 :     for (const auto& [pubkey_leaf, sig] : sigdata.taproot_script_sigs) {
     389                 :        1988 :         m_tap_script_sigs.emplace(pubkey_leaf, sig);
     390                 :             :     }
     391         [ +  + ]:       40546 :     if (!sigdata.tr_spenddata.internal_key.IsNull()) {
     392                 :         133 :         m_tap_internal_key = sigdata.tr_spenddata.internal_key;
     393                 :             :     }
     394         [ +  + ]:       40546 :     if (!sigdata.tr_spenddata.merkle_root.IsNull()) {
     395                 :         181 :         m_tap_merkle_root = sigdata.tr_spenddata.merkle_root;
     396                 :             :     }
     397         [ +  + ]:       34387 :     for (const auto& [leaf_script, control_block] : sigdata.tr_spenddata.scripts) {
     398                 :       14114 :         m_tap_scripts.emplace(leaf_script, control_block);
     399                 :             :     }
     400         [ +  + ]:       23877 :     for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
     401                 :        3604 :         m_tap_bip32_paths.emplace(pubkey, leaf_origin);
     402                 :             :     }
     403                 :       20273 :     m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
     404         [ +  + ]:       22326 :     for (const auto& [agg_key_lh, pubnonces] : sigdata.musig2_pubnonces) {
     405                 :        2053 :         m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
     406                 :             :     }
     407         [ +  + ]:       21447 :     for (const auto& [agg_key_lh, psigs] : sigdata.musig2_partial_sigs) {
     408                 :        1174 :         m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
     409                 :             :     }
     410         [ +  + ]:       21896 :     for (const auto& [hash, preimage] : sigdata.ripemd160_preimages) {
     411                 :        3246 :         ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     412                 :             :     }
     413         [ +  + ]:       25265 :     for (const auto& [hash, preimage] : sigdata.sha256_preimages) {
     414                 :        9984 :         sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     415                 :             :     }
     416         [ +  + ]:       26170 :     for (const auto& [hash, preimage] : sigdata.hash160_preimages) {
     417                 :       11794 :         hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     418                 :             :     }
     419         [ +  + ]:       22856 :     for (const auto& [hash, preimage] : sigdata.hash256_preimages) {
     420                 :        5166 :         hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     421                 :             :     }
     422                 :             : }
     423                 :             : 
     424                 :       30066 : bool PSBTInput::Merge(const PSBTInput& input)
     425                 :             : {
     426   [ +  +  +  + ]:       30066 :     if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
     427   [ +  +  +  + ]:       30066 :     if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
     428                 :         195 :         witness_utxo = input.witness_utxo;
     429                 :             :     }
     430                 :             : 
     431                 :       30066 :     partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
     432                 :       30066 :     ripemd160_preimages.insert(input.ripemd160_preimages.begin(), input.ripemd160_preimages.end());
     433                 :       30066 :     sha256_preimages.insert(input.sha256_preimages.begin(), input.sha256_preimages.end());
     434                 :       30066 :     hash160_preimages.insert(input.hash160_preimages.begin(), input.hash160_preimages.end());
     435                 :       30066 :     hash256_preimages.insert(input.hash256_preimages.begin(), input.hash256_preimages.end());
     436                 :       30066 :     hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
     437                 :       30066 :     m_proprietary.insert(input.m_proprietary.begin(), input.m_proprietary.end());
     438                 :       30066 :     unknown.insert(input.unknown.begin(), input.unknown.end());
     439                 :       30066 :     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                 :       30066 :     std::set<std::vector<unsigned char>> seen_control_blocks;
     443   [ +  -  +  + ]:       50076 :     for (const auto& [_, control_blocks] : m_tap_scripts) {
     444         [ +  - ]:       20010 :         seen_control_blocks.insert(control_blocks.begin(), control_blocks.end());
     445                 :             :     }
     446         [ +  + ]:       50185 :     for (const auto& [leaf, control_blocks] : input.m_tap_scripts) {
     447         [ +  + ]:       41718 :         for (const auto& control_block : control_blocks) {
     448   [ +  -  +  +  :       21599 :             if (seen_control_blocks.insert(control_block).second) m_tap_scripts[leaf].insert(control_block);
             +  -  +  - ]
     449                 :             :         }
     450                 :             :     }
     451         [ +  - ]:       30066 :     m_tap_bip32_paths.insert(input.m_tap_bip32_paths.begin(), input.m_tap_bip32_paths.end());
     452                 :             : 
     453   [ +  +  +  +  :       30452 :     if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
             +  +  +  + ]
     454   [ +  +  +  +  :       35144 :     if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
             +  +  +  + ]
     455   [ +  +  +  +  :       33957 :     if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
             +  +  +  + ]
     456   [ +  +  +  +  :       30066 :     if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
                   +  - ]
     457   [ +  +  +  +  :       30066 :     if (m_tap_key_sig.empty() && !input.m_tap_key_sig.empty()) m_tap_key_sig = input.m_tap_key_sig;
                   +  - ]
     458   [ +  +  +  + ]:       89953 :     if (m_tap_internal_key.IsNull() && !input.m_tap_internal_key.IsNull()) m_tap_internal_key = input.m_tap_internal_key;
     459   [ +  +  +  + ]:       85770 :     if (m_tap_merkle_root.IsNull() && !input.m_tap_merkle_root.IsNull()) m_tap_merkle_root = input.m_tap_merkle_root;
     460         [ +  - ]:       30066 :     m_musig2_participants.insert(input.m_musig2_participants.begin(), input.m_musig2_participants.end());
     461   [ +  -  +  + ]:       32185 :     for (const auto& [agg_key_lh, pubnonces] : input.m_musig2_pubnonces) {
     462   [ +  -  +  - ]:        2119 :         m_musig2_pubnonces[agg_key_lh].insert(pubnonces.begin(), pubnonces.end());
     463                 :             :     }
     464   [ +  -  +  + ]:       32617 :     for (const auto& [agg_key_lh, psigs] : input.m_musig2_partial_sigs) {
     465   [ +  -  +  - ]:        2551 :         m_musig2_partial_sigs[agg_key_lh].insert(psigs.begin(), psigs.end());
     466                 :             :     }
     467   [ -  +  -  - ]:       30066 :     if (sequence == std::nullopt && input.sequence != std::nullopt) sequence = input.sequence;
     468   [ +  -  -  + ]:       30066 :     if (time_locktime == std::nullopt && input.time_locktime != std::nullopt) time_locktime = input.time_locktime;
     469   [ +  -  -  + ]:       30066 :     if (height_locktime == std::nullopt && input.height_locktime != std::nullopt) height_locktime = input.height_locktime;
     470                 :             : 
     471                 :       30066 :     return true;
     472                 :       30066 : }
     473                 :             : 
     474                 :           0 : bool PSBTInput::HasSignatures() const
     475                 :             : {
     476         [ #  # ]:           0 :     return !final_script_sig.empty()
     477         [ #  # ]:           0 :            || !final_script_witness.IsNull()
     478         [ #  # ]:           0 :            || !partial_sigs.empty()
     479         [ #  # ]:           0 :            || !m_tap_key_sig.empty()
     480         [ #  # ]:           0 :            || !m_tap_script_sigs.empty()
     481   [ #  #  #  # ]:           0 :            || !m_musig2_partial_sigs.empty();
     482                 :             : }
     483                 :             : 
     484                 :       13990 : void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
     485                 :             : {
     486   [ +  +  +  + ]:       14062 :     if (!redeem_script.empty()) {
     487                 :         354 :         sigdata.redeem_script = redeem_script;
     488                 :             :     }
     489   [ +  +  +  + ]:       14198 :     if (!witness_script.empty()) {
     490                 :         412 :         sigdata.witness_script = witness_script;
     491                 :             :     }
     492         [ +  + ]:       16290 :     for (const auto& key_pair : hd_keypaths) {
     493                 :        2300 :         sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
     494                 :             :     }
     495   [ +  +  +  + ]:       13990 :     if (!m_tap_tree.empty() && m_tap_internal_key.IsFullyValid()) {
     496                 :         548 :         TaprootBuilder builder;
     497   [ -  +  +  + ]:        2784 :         for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
     498   [ -  +  +  - ]:        2236 :             builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
     499                 :             :         }
     500         [ -  + ]:         548 :         assert(builder.IsComplete());
     501         [ +  - ]:         548 :         builder.Finalize(m_tap_internal_key);
     502         [ +  - ]:         548 :         TaprootSpendData spenddata = builder.GetSpendData();
     503                 :             : 
     504                 :         548 :         sigdata.tr_spenddata.internal_key = m_tap_internal_key;
     505   [ +  -  +  - ]:         548 :         sigdata.tr_spenddata.Merge(spenddata);
     506         [ +  - ]:         548 :         sigdata.tr_builder = builder;
     507                 :         548 :     }
     508         [ +  + ]:       14774 :     for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
     509                 :         784 :         sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
     510                 :         784 :         sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
     511                 :             :     }
     512                 :       13990 :     sigdata.musig2_pubkeys.insert(m_musig2_participants.begin(), m_musig2_participants.end());
     513                 :       13990 : }
     514                 :             : 
     515                 :       13990 : void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
     516                 :             : {
     517   [ +  +  +  +  :       14062 :     if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
             +  +  +  + ]
     518                 :         346 :         redeem_script = sigdata.redeem_script;
     519                 :             :     }
     520   [ +  +  +  +  :       14198 :     if (witness_script.empty() && !sigdata.witness_script.empty()) {
             +  +  +  + ]
     521                 :         404 :         witness_script = sigdata.witness_script;
     522                 :             :     }
     523         [ +  + ]:       16290 :     for (const auto& entry : sigdata.misc_pubkeys) {
     524                 :        2300 :         hd_keypaths.emplace(entry.second);
     525                 :             :     }
     526         [ +  + ]:       27980 :     if (!sigdata.tr_spenddata.internal_key.IsNull()) {
     527                 :         548 :         m_tap_internal_key = sigdata.tr_spenddata.internal_key;
     528                 :             :     }
     529   [ +  +  +  - ]:       13990 :     if (sigdata.tr_builder.has_value() && sigdata.tr_builder->HasScripts()) {
     530                 :         548 :         m_tap_tree = sigdata.tr_builder->GetTreeTuples();
     531                 :             :     }
     532         [ +  + ]:       14774 :     for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
     533                 :         784 :         m_tap_bip32_paths.emplace(pubkey, leaf_origin);
     534                 :             :     }
     535                 :       13990 :     m_musig2_participants.insert(sigdata.musig2_pubkeys.begin(), sigdata.musig2_pubkeys.end());
     536                 :       13990 : }
     537                 :             : 
     538                 :       26036 : bool PSBTOutput::Merge(const PSBTOutput& output)
     539                 :             : {
     540                 :       26036 :     hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
     541                 :       26036 :     m_proprietary.insert(output.m_proprietary.begin(), output.m_proprietary.end());
     542                 :       26036 :     unknown.insert(output.unknown.begin(), output.unknown.end());
     543                 :       26036 :     m_tap_bip32_paths.insert(output.m_tap_bip32_paths.begin(), output.m_tap_bip32_paths.end());
     544                 :             : 
     545   [ +  +  +  +  :       26190 :     if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
             +  +  +  + ]
     546   [ +  +  +  +  :       26490 :     if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
             +  +  +  + ]
     547   [ +  +  +  + ]:       76478 :     if (m_tap_internal_key.IsNull() && !output.m_tap_internal_key.IsNull()) m_tap_internal_key = output.m_tap_internal_key;
     548   [ +  +  +  + ]:       26036 :     if (m_tap_tree.empty() && !output.m_tap_tree.empty()) m_tap_tree = output.m_tap_tree;
     549                 :       26036 :     m_musig2_participants.insert(output.m_musig2_participants.begin(), output.m_musig2_participants.end());
     550                 :             : 
     551                 :       26036 :     return true;
     552                 :             : }
     553                 :             : 
     554                 :       34441 : bool PSBTInputSigned(const PSBTInput& input)
     555                 :             : {
     556   [ +  +  +  +  :       38091 :     return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
                   +  + ]
     557                 :             : }
     558                 :             : 
     559                 :       55730 : bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
     560                 :             : {
     561                 :       55730 :     CTxOut utxo;
     562   [ -  +  -  + ]:       55730 :     assert(input_index < psbt.inputs.size());
     563         [ +  + ]:       55730 :     const PSBTInput& input = psbt.inputs[input_index];
     564                 :             : 
     565         [ +  + ]:       55730 :     if (input.non_witness_utxo) {
     566                 :             :         // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
     567         [ +  - ]:        1415 :         COutPoint prevout = input.GetOutPoint();
     568   [ -  +  +  - ]:        1415 :         if (prevout.n >= input.non_witness_utxo->vout.size()) {
     569                 :             :             return false;
     570                 :             :         }
     571         [ +  - ]:       57145 :         if (input.non_witness_utxo->GetHash() != prevout.hash) {
     572                 :             :             return false;
     573                 :             :         }
     574                 :        1415 :         utxo = input.non_witness_utxo->vout[prevout.n];
     575         [ +  + ]:       54315 :     } else if (!input.witness_utxo.IsNull()) {
     576                 :       32840 :         utxo = input.witness_utxo;
     577                 :             :     } else {
     578                 :             :         return false;
     579                 :             :     }
     580                 :             : 
     581         [ +  - ]:       34255 :     std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
     582         [ +  - ]:       34255 :     if (!unsigned_tx) {
     583                 :             :         return false;
     584                 :             :     }
     585         [ +  + ]:       34255 :     const CMutableTransaction& tx = *unsigned_tx;
     586         [ +  + ]:       34255 :     if (txdata) {
     587         [ +  - ]:       31121 :         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         [ +  - ]:        3134 :         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                 :       89985 : }
     592                 :             : 
     593                 :        8168 : size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt) {
     594                 :        8168 :     size_t count = 0;
     595         [ +  + ]:       22016 :     for (const auto& input : psbt.inputs) {
     596         [ +  + ]:       13848 :         if (!PSBTInputSigned(input)) {
     597                 :       11396 :             count++;
     598                 :             :         }
     599                 :             :     }
     600                 :             : 
     601                 :        8168 :     return count;
     602                 :             : }
     603                 :             : 
     604                 :         176 : void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index)
     605                 :             : {
     606                 :         176 :     std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
     607         [ -  + ]:         176 :     if (!unsigned_tx) {
     608                 :           0 :         return;
     609                 :             :     }
     610         [ +  - ]:         176 :     const CTxOut& out = unsigned_tx->vout.at(index);
     611         [ +  - ]:         176 :     PSBTOutput& psbt_out = psbt.outputs.at(index);
     612                 :             : 
     613                 :             :     // Fill a SignatureData with output info
     614                 :         176 :     SignatureData sigdata;
     615         [ +  - ]:         176 :     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         [ +  - ]:         176 :     CMutableTransaction tx{};
     621         [ +  - ]:         176 :     tx.vin.emplace_back();
     622         [ +  - ]:         176 :     MutableTransactionSignatureCreator creator(tx, /*input_idx=*/0, out.nValue, {.sighash_type = SIGHASH_ALL});
     623         [ +  - ]:         176 :     ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
     624                 :             : 
     625                 :             :     // Put redeem_script, witness_script, key paths, into PSBTOutput.
     626         [ +  - ]:         176 :     psbt_out.FromSignatureData(sigdata);
     627         [ +  - ]:         528 : }
     628                 :             : 
     629                 :       34232 : std::optional<PrecomputedTransactionData> PrecomputePSBTData(const PartiallySignedTransaction& psbt)
     630                 :             : {
     631                 :       34232 :     std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
     632         [ -  + ]:       34232 :     if (!unsigned_tx) {
     633                 :           0 :         return std::nullopt;
     634                 :             :     }
     635                 :       34232 :     const CMutableTransaction& tx = *unsigned_tx;
     636                 :       34232 :     bool have_all_spent_outputs = true;
     637                 :       34232 :     std::vector<CTxOut> utxos;
     638         [ +  + ]:       81466 :     for (const PSBTInput& input : psbt.inputs) {
     639   [ +  -  +  -  :       47234 :         if (!input.GetUTXO(utxos.emplace_back())) have_all_spent_outputs = false;
                   +  + ]
     640                 :             :     }
     641                 :       34232 :     PrecomputedTransactionData txdata;
     642         [ +  + ]:       34232 :     if (have_all_spent_outputs) {
     643         [ +  - ]:       24873 :         txdata.Init(tx, std::move(utxos), true);
     644                 :             :     } else {
     645         [ +  - ]:        9359 :         txdata.Init(tx, {}, true);
     646                 :             :     }
     647                 :       34232 :     return txdata;
     648                 :       68464 : }
     649                 :             : 
     650                 :       44102 : util::Expected<void, PSBTError> SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options,  SignatureData* out_sigdata)
     651                 :             : {
     652                 :       44102 :     PSBTInput& input = psbt.inputs.at(index);
     653                 :       44102 :     std::optional<CMutableTransaction> unsigned_tx = psbt.GetUnsignedTx();
     654         [ -  + ]:       44102 :     if (!unsigned_tx) {
     655                 :           0 :         return util::Unexpected{PSBTError::INVALID_TX};
     656                 :             :     }
     657         [ +  - ]:       44102 :     const CMutableTransaction& tx = *unsigned_tx;
     658                 :             : 
     659   [ +  -  +  + ]:       44102 :     if (PSBTInputSignedAndVerified(psbt, index, txdata)) {
     660                 :        2361 :         return {};
     661                 :             :     }
     662                 :             : 
     663                 :             :     // Fill SignatureData with input info
     664                 :       41741 :     SignatureData sigdata;
     665         [ +  - ]:       41741 :     input.FillSignatureData(sigdata);
     666                 :             : 
     667                 :             :     // Get UTXO
     668                 :       41741 :     bool require_witness_sig = false;
     669                 :       41741 :     CTxOut utxo;
     670                 :             : 
     671         [ +  + ]:       41741 :     if (input.non_witness_utxo) {
     672                 :             :         // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
     673         [ +  - ]:        1124 :         COutPoint prevout = input.GetOutPoint();
     674   [ -  +  -  + ]:        1124 :         if (prevout.n >= input.non_witness_utxo->vout.size()) {
     675                 :           0 :             return util::Unexpected{PSBTError::MISSING_INPUTS};
     676                 :             :         }
     677         [ +  - ]:        1124 :         if (input.non_witness_utxo->GetHash() != prevout.hash) {
     678                 :           0 :             return util::Unexpected{PSBTError::MISSING_INPUTS};
     679                 :             :         }
     680                 :        1124 :         utxo = input.non_witness_utxo->vout[prevout.n];
     681         [ +  + ]:       40617 :     } else if (!input.witness_utxo.IsNull()) {
     682                 :       24347 :         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                 :       24347 :         require_witness_sig = true;
     688                 :             :     } else {
     689                 :       16270 :         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   [ +  -  +  +  :       46203 :     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   [ +  +  +  + ]:       25471 :     if (input.sighash_type && input.sighash_type != sighash) {
     701                 :          68 :         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   [ +  -  +  +  :       46070 :     if (utxo.scriptPubKey.IsPayToTaproot() ? sighash != SIGHASH_DEFAULT :
                   +  + ]
     707                 :       20667 :                                             (sighash != SIGHASH_DEFAULT && sighash != SIGHASH_ALL)) {
     708                 :        1521 :         input.sighash_type = sighash;
     709                 :             :     }
     710                 :             : 
     711                 :             :     // Check all existing signatures use the sighash type
     712         [ +  + ]:       25403 :     if (sighash == SIGHASH_DEFAULT) {
     713   [ +  +  -  +  :        4943 :         if (!input.m_tap_key_sig.empty() && input.m_tap_key_sig.size() != 64) {
                   +  + ]
     714                 :          29 :             return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     715                 :             :         }
     716   [ -  +  +  + ]:        5300 :         for (const auto& [_, sig] : input.m_tap_script_sigs) {
     717   [ -  +  +  + ]:         419 :             if (sig.size() != 64) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     718                 :             :         }
     719                 :             :     } else {
     720   [ +  +  -  +  :       20460 :         if (!input.m_tap_key_sig.empty() && (input.m_tap_key_sig.size() != 65 || input.m_tap_key_sig.back() != sighash)) {
             +  +  +  + ]
     721                 :         234 :             return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     722                 :             :         }
     723   [ -  +  +  + ]:       20409 :         for (const auto& [_, sig] : input.m_tap_script_sigs) {
     724   [ -  +  +  +  :         734 :             if (sig.size() != 65 || sig.back() != sighash) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
                   +  + ]
     725                 :             :         }
     726   [ +  +  +  + ]:       21039 :         for (const auto& [_, sig] : input.partial_sigs) {
     727         [ +  + ]:        1406 :             if (sig.second.back() != sighash) return util::Unexpected{PSBTError::SIGHASH_MISMATCH};
     728                 :             :         }
     729                 :             :     }
     730                 :             : 
     731                 :       24514 :     sigdata.witness = false;
     732                 :       24514 :     bool sig_complete;
     733         [ +  + ]:       24514 :     if (txdata == nullptr) {
     734         [ +  - ]:        2554 :         sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
     735                 :             :     } else {
     736         [ +  - ]:       21960 :         MutableTransactionSignatureCreator creator(tx, index, utxo.nValue, txdata, {.sighash_type = sighash});
     737         [ +  - ]:       21960 :         sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
     738                 :       21960 :     }
     739                 :             :     // Verify that a witness signature was produced in case one was required.
     740   [ +  +  +  + ]:       24514 :     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   [ +  +  -  + ]:       10002 :     if (!options.finalize && sigdata.complete) sigdata.complete = false;
     744                 :             : 
     745         [ +  - ]:       10002 :     input.FromSignatureData(sigdata);
     746                 :             : 
     747                 :             :     // If we have a witness signature, put a witness UTXO.
     748         [ +  + ]:       10002 :     if (sigdata.witness) {
     749                 :        9201 :         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         [ +  + ]:       10002 :     if (out_sigdata) {
     757         [ +  - ]:        2441 :         out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
     758         [ +  - ]:        2441 :         out_sigdata->missing_sigs = sigdata.missing_sigs;
     759                 :        2441 :         out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
     760                 :        2441 :         out_sigdata->missing_witness_script = sigdata.missing_witness_script;
     761                 :             :     }
     762                 :             : 
     763         [ +  + ]:       10002 :     if (!sig_complete) return util::Unexpected{PSBTError::INCOMPLETE};
     764                 :        1125 :     return {};
     765                 :       85843 : }
     766                 :             : 
     767                 :        8579 : void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx)
     768                 :             : {
     769                 :             :     // Figure out if any non_witness_utxos should be dropped
     770                 :        8579 :     std::vector<unsigned int> to_drop;
     771   [ -  +  +  + ]:       10264 :     for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
     772         [ +  - ]:        7720 :         const auto& input = psbtx.inputs.at(i);
     773                 :        7720 :         int wit_ver;
     774                 :        7720 :         std::vector<unsigned char> wit_prog;
     775   [ +  +  +  -  :        7720 :         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         [ +  + ]:        5350 :             to_drop.clear();
     778                 :             :             break;
     779                 :             :         }
     780         [ +  + ]:        2370 :         if (wit_ver == 0) {
     781                 :             :             // Segwit v0, so we cannot drop any non_witness_utxos
     782         [ +  + ]:         683 :             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   [ +  +  +  + ]:        1687 :         if (input.sighash_type != std::nullopt && (*input.sighash_type & 0x80) == SIGHASH_ANYONECANPAY) {
     789         [ -  + ]:        6035 :             to_drop.clear();
     790                 :             :             break;
     791                 :             :         }
     792                 :             : 
     793         [ +  + ]:        1685 :         if (input.non_witness_utxo) {
     794         [ +  - ]:           5 :             to_drop.push_back(i);
     795                 :             :         }
     796                 :        7720 :     }
     797                 :             : 
     798                 :             :     // Drop the non_witness_utxos that we can drop
     799         [ +  + ]:        8581 :     for (unsigned int i : to_drop) {
     800   [ +  -  -  + ]:           2 :         psbtx.inputs.at(i).non_witness_utxo = nullptr;
     801                 :             :     }
     802                 :        8579 : }
     803                 :             : 
     804                 :       16680 : 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                 :       16680 :     bool complete = true;
     811                 :       16680 :     std::optional<PrecomputedTransactionData> txdata_res = PrecomputePSBTData(psbtx);
     812         [ +  - ]:       16680 :     if (!txdata_res) {
     813                 :             :         return false;
     814                 :             :     }
     815                 :             :     const PrecomputedTransactionData& txdata = *txdata_res;
     816   [ -  +  +  + ]:       44691 :     for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
     817         [ +  - ]:       28011 :         PSBTInput& input = psbtx.inputs.at(i);
     818         [ +  - ]:       28011 :         const auto sign_result = SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, {.sighash_type = input.sighash_type, .finalize = true}, /*out_sigdata=*/nullptr);
     819                 :       28011 :         complete &= sign_result.has_value();
     820                 :             :     }
     821                 :             : 
     822                 :             :     return complete;
     823                 :       16680 : }
     824                 :             : 
     825                 :        8512 : 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         [ +  + ]:        8512 :     if (!FinalizePSBT(psbtx)) {
     830                 :             :         return false;
     831                 :             :     }
     832                 :             : 
     833                 :        1531 :     std::optional<CMutableTransaction> unsigned_tx = psbtx.GetUnsignedTx();
     834         [ +  - ]:        1531 :     if (!unsigned_tx) {
     835                 :             :         return false;
     836                 :             :     }
     837         [ +  - ]:        1531 :     result = *unsigned_tx;
     838   [ -  +  +  + ]:        2290 :     for (unsigned int i = 0; i < result.vin.size(); ++i) {
     839                 :         759 :         result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
     840         [ +  - ]:         759 :         result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
     841                 :             :     }
     842                 :             :     return true;
     843                 :        1531 : }
     844                 :             : 
     845                 :        8437 : std::optional<PartiallySignedTransaction> CombinePSBTs(const std::vector<PartiallySignedTransaction>& psbtxs)
     846                 :             : {
     847                 :        8437 :     PartiallySignedTransaction out = psbtxs[0]; // Copy the first one
     848                 :             : 
     849                 :             :     // Merge
     850         [ +  + ]:       21458 :     for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
     851   [ +  -  +  + ]:       13644 :         if (!out.Merge(*it)) {
     852                 :         623 :             return std::nullopt;
     853                 :             :         }
     854                 :             :     }
     855                 :        7814 :     return out;
     856                 :        8437 : }
     857                 :             : 
     858                 :       18023 : std::string PSBTRoleName(PSBTRole role) {
     859   [ +  +  +  +  :       18023 :     switch (role) {
                   +  - ]
     860                 :        3669 :     case PSBTRole::CREATOR: return "creator";
     861                 :       12504 :     case PSBTRole::UPDATER: return "updater";
     862                 :         433 :     case PSBTRole::SIGNER: return "signer";
     863                 :         218 :     case PSBTRole::FINALIZER: return "finalizer";
     864                 :        1199 :     case PSBTRole::EXTRACTOR: return "extractor";
     865                 :             :     } // no default case, so the compiler can warn about missing cases
     866                 :           0 :     assert(false);
     867                 :             : }
     868                 :             : 
     869                 :       15021 : util::Result<PartiallySignedTransaction> DecodeBase64PSBT(const std::string& base64_tx)
     870                 :             : {
     871         [ -  + ]:       15021 :     auto tx_data = DecodeBase64(base64_tx);
     872         [ +  + ]:       15021 :     if (!tx_data) {
     873   [ +  -  +  - ]:         174 :         return util::Error{Untranslated("invalid base64")};
     874                 :             :     }
     875         [ +  - ]:       14963 :     return DecodeRawPSBT(MakeByteSpan(*tx_data));
     876                 :       15021 : }
     877                 :             : 
     878                 :       33446 : util::Result<PartiallySignedTransaction> DecodeRawPSBT(std::span<const std::byte> tx_data)
     879                 :             : {
     880         [ +  + ]:       33446 :     SpanReader ss_data{tx_data};
     881                 :       33446 :     try {
     882         [ +  + ]:       33446 :         PartiallySignedTransaction psbt(deserialize, ss_data);
     883         [ +  + ]:       21816 :         if (!ss_data.empty()) {
     884   [ +  -  +  - ]:        1587 :             return util::Error{Untranslated("extra data after PSBT")};
     885                 :             :         }
     886                 :       21287 :         return psbt;
     887         [ -  + ]:       33446 :     } catch (const std::exception& e) {
     888   [ +  -  +  - ]:       34890 :         return util::Error{Untranslated(e.what())};
     889                 :       11630 :     }
     890                 :             : }
     891                 :             : 
     892                 :      514655 : uint32_t PartiallySignedTransaction::GetVersion() const
     893                 :             : {
     894         [ +  + ]:      514655 :     if (m_version != std::nullopt) {
     895                 :       12481 :         return *m_version;
     896                 :             :     }
     897                 :             :     return 0;
     898                 :             : }
        

Generated by: LCOV version 2.5.0-full