LCOV - code coverage report
Current view: top level - src - psbt.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 69.0 % 509 351
Test Date: 2026-10-09 06:11:59 Functions: 84.4 % 32 27
Branches: 45.4 % 802 364

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

Generated by: LCOV version 2.0-1