LCOV - code coverage report
Current view: top level - src - psbt.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 92.8 % 334 310
Test Date: 2025-06-01 06:26:32 Functions: 85.7 % 28 24
Branches: 68.3 % 502 343

             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 <script/signingprovider.h>
      11                 :             : #include <util/check.h>
      12                 :             : #include <util/strencodings.h>
      13                 :             : 
      14                 :             : using common::PSBTError;
      15                 :             : 
      16         [ +  - ]:         339 : PartiallySignedTransaction::PartiallySignedTransaction(const CMutableTransaction& tx) : tx(tx)
      17                 :             : {
      18         [ +  - ]:         339 :     inputs.resize(tx.vin.size());
      19         [ +  - ]:         339 :     outputs.resize(tx.vout.size());
      20         [ -  - ]:         339 : }
      21                 :             : 
      22                 :           0 : bool PartiallySignedTransaction::IsNull() const
      23                 :             : {
      24   [ #  #  #  #  :           0 :     return !tx && inputs.empty() && outputs.empty() && unknown.empty();
             #  #  #  # ]
      25                 :             : }
      26                 :             : 
      27                 :           8 : bool PartiallySignedTransaction::Merge(const PartiallySignedTransaction& psbt)
      28                 :             : {
      29                 :             :     // Prohibited to merge two PSBTs over different transactions
      30         [ +  + ]:           8 :     if (tx->GetHash() != psbt.tx->GetHash()) {
      31                 :             :         return false;
      32                 :             :     }
      33                 :             : 
      34         [ +  + ]:          16 :     for (unsigned int i = 0; i < inputs.size(); ++i) {
      35                 :           9 :         inputs[i].Merge(psbt.inputs[i]);
      36                 :             :     }
      37         [ +  + ]:          17 :     for (unsigned int i = 0; i < outputs.size(); ++i) {
      38                 :          10 :         outputs[i].Merge(psbt.outputs[i]);
      39                 :             :     }
      40         [ -  + ]:           7 :     for (auto& xpub_pair : psbt.m_xpubs) {
      41         [ #  # ]:           0 :         if (m_xpubs.count(xpub_pair.first) == 0) {
      42                 :           0 :             m_xpubs[xpub_pair.first] = xpub_pair.second;
      43                 :             :         } else {
      44                 :           0 :             m_xpubs[xpub_pair.first].insert(xpub_pair.second.begin(), xpub_pair.second.end());
      45                 :             :         }
      46                 :             :     }
      47                 :           7 :     unknown.insert(psbt.unknown.begin(), psbt.unknown.end());
      48                 :             : 
      49                 :           7 :     return true;
      50                 :             : }
      51                 :             : 
      52                 :          18 : bool PartiallySignedTransaction::AddInput(const CTxIn& txin, PSBTInput& psbtin)
      53                 :             : {
      54         [ +  + ]:          18 :     if (std::find(tx->vin.begin(), tx->vin.end(), txin) != tx->vin.end()) {
      55                 :             :         return false;
      56                 :             :     }
      57                 :          17 :     tx->vin.push_back(txin);
      58                 :          17 :     psbtin.partial_sigs.clear();
      59                 :          17 :     psbtin.final_script_sig.clear();
      60                 :          17 :     psbtin.final_script_witness.SetNull();
      61                 :          17 :     inputs.push_back(psbtin);
      62                 :          17 :     return true;
      63                 :             : }
      64                 :             : 
      65                 :           9 : bool PartiallySignedTransaction::AddOutput(const CTxOut& txout, const PSBTOutput& psbtout)
      66                 :             : {
      67                 :           9 :     tx->vout.push_back(txout);
      68                 :           9 :     outputs.push_back(psbtout);
      69                 :           9 :     return true;
      70                 :             : }
      71                 :             : 
      72                 :        4435 : bool PartiallySignedTransaction::GetInputUTXO(CTxOut& utxo, int input_index) const
      73                 :             : {
      74         [ +  + ]:        4435 :     const PSBTInput& input = inputs[input_index];
      75         [ +  + ]:        4435 :     uint32_t prevout_index = tx->vin[input_index].prevout.n;
      76         [ +  + ]:        4435 :     if (input.non_witness_utxo) {
      77         [ +  + ]:        3815 :         if (prevout_index >= input.non_witness_utxo->vout.size()) {
      78                 :             :             return false;
      79                 :             :         }
      80         [ +  - ]:        3814 :         if (input.non_witness_utxo->GetHash() != tx->vin[input_index].prevout.hash) {
      81                 :             :             return false;
      82                 :             :         }
      83                 :        3814 :         utxo = input.non_witness_utxo->vout[prevout_index];
      84         [ +  + ]:         620 :     } else if (!input.witness_utxo.IsNull()) {
      85                 :         592 :         utxo = input.witness_utxo;
      86                 :             :     } else {
      87                 :             :         return false;
      88                 :             :     }
      89                 :             :     return true;
      90                 :             : }
      91                 :             : 
      92                 :           0 : bool PSBTInput::IsNull() const
      93                 :             : {
      94   [ #  #  #  #  :           0 :     return !non_witness_utxo && witness_utxo.IsNull() && partial_sigs.empty() && unknown.empty() && hd_keypaths.empty() && redeem_script.empty() && witness_script.empty();
          #  #  #  #  #  
          #  #  #  #  #  
             #  #  #  # ]
      95                 :             : }
      96                 :             : 
      97                 :       18452 : void PSBTInput::FillSignatureData(SignatureData& sigdata) const
      98                 :             : {
      99   [ -  +  -  + ]:       18452 :     if (!final_script_sig.empty()) {
     100                 :           0 :         sigdata.scriptSig = final_script_sig;
     101                 :           0 :         sigdata.complete = true;
     102                 :             :     }
     103         [ -  + ]:       18452 :     if (!final_script_witness.IsNull()) {
     104                 :           0 :         sigdata.scriptWitness = final_script_witness;
     105                 :           0 :         sigdata.complete = true;
     106                 :             :     }
     107         [ +  - ]:       18452 :     if (sigdata.complete) {
     108                 :             :         return;
     109                 :             :     }
     110                 :             : 
     111                 :       18452 :     sigdata.signatures.insert(partial_sigs.begin(), partial_sigs.end());
     112   [ +  +  +  + ]:       18588 :     if (!redeem_script.empty()) {
     113                 :        4359 :         sigdata.redeem_script = redeem_script;
     114                 :             :     }
     115   [ +  +  +  + ]:       18731 :     if (!witness_script.empty()) {
     116                 :         283 :         sigdata.witness_script = witness_script;
     117                 :             :     }
     118         [ +  + ]:       30359 :     for (const auto& key_pair : hd_keypaths) {
     119                 :       11907 :         sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
     120                 :             :     }
     121         [ +  + ]:       18452 :     if (!m_tap_key_sig.empty()) {
     122                 :         194 :         sigdata.taproot_key_path_sig = m_tap_key_sig;
     123                 :             :     }
     124         [ +  + ]:       19072 :     for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
     125                 :         620 :         sigdata.taproot_script_sigs.emplace(pubkey_leaf, sig);
     126                 :             :     }
     127         [ +  + ]:       18452 :     if (!m_tap_internal_key.IsNull()) {
     128                 :        1262 :         sigdata.tr_spenddata.internal_key = m_tap_internal_key;
     129                 :             :     }
     130         [ +  + ]:       18452 :     if (!m_tap_merkle_root.IsNull()) {
     131                 :        1118 :         sigdata.tr_spenddata.merkle_root = m_tap_merkle_root;
     132                 :             :     }
     133         [ +  + ]:       20195 :     for (const auto& [leaf_script, control_block] : m_tap_scripts) {
     134                 :        1743 :         sigdata.tr_spenddata.scripts.emplace(leaf_script, control_block);
     135                 :             :     }
     136         [ +  + ]:       22108 :     for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
     137                 :        3656 :         sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
     138                 :        3656 :         sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
     139                 :             :     }
     140         [ -  + ]:       18452 :     for (const auto& [hash, preimage] : ripemd160_preimages) {
     141         [ #  # ]:           0 :         sigdata.ripemd160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     142                 :             :     }
     143         [ +  + ]:       18464 :     for (const auto& [hash, preimage] : sha256_preimages) {
     144         [ +  - ]:          24 :         sigdata.sha256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     145                 :             :     }
     146         [ -  + ]:       18452 :     for (const auto& [hash, preimage] : hash160_preimages) {
     147         [ #  # ]:           0 :         sigdata.hash160_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     148                 :             :     }
     149         [ -  + ]:       18452 :     for (const auto& [hash, preimage] : hash256_preimages) {
     150         [ #  # ]:           0 :         sigdata.hash256_preimages.emplace(std::vector<unsigned char>(hash.begin(), hash.end()), preimage);
     151                 :             :     }
     152                 :             : }
     153                 :             : 
     154                 :       18401 : void PSBTInput::FromSignatureData(const SignatureData& sigdata)
     155                 :             : {
     156         [ +  + ]:       18401 :     if (sigdata.complete) {
     157                 :        1362 :         partial_sigs.clear();
     158                 :        1362 :         hd_keypaths.clear();
     159                 :        1362 :         redeem_script.clear();
     160                 :        1362 :         witness_script.clear();
     161                 :             : 
     162   [ +  +  +  + ]:        1604 :         if (!sigdata.scriptSig.empty()) {
     163                 :         748 :             final_script_sig = sigdata.scriptSig;
     164                 :             :         }
     165         [ +  + ]:        1362 :         if (!sigdata.scriptWitness.IsNull()) {
     166                 :        1128 :             final_script_witness = sigdata.scriptWitness;
     167                 :             :         }
     168                 :        1362 :         return;
     169                 :             :     }
     170                 :             : 
     171                 :       17039 :     partial_sigs.insert(sigdata.signatures.begin(), sigdata.signatures.end());
     172   [ +  +  +  +  :       17156 :     if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
             +  +  +  + ]
     173                 :         542 :         redeem_script = sigdata.redeem_script;
     174                 :             :     }
     175   [ +  +  +  +  :       17294 :     if (witness_script.empty() && !sigdata.witness_script.empty()) {
             +  +  +  + ]
     176                 :          33 :         witness_script = sigdata.witness_script;
     177                 :             :     }
     178         [ +  + ]:       29000 :     for (const auto& entry : sigdata.misc_pubkeys) {
     179                 :       11961 :         hd_keypaths.emplace(entry.second);
     180                 :             :     }
     181         [ +  + ]:       17039 :     if (!sigdata.taproot_key_path_sig.empty()) {
     182                 :         224 :         m_tap_key_sig = sigdata.taproot_key_path_sig;
     183                 :             :     }
     184         [ +  + ]:       17718 :     for (const auto& [pubkey_leaf, sig] : sigdata.taproot_script_sigs) {
     185                 :         679 :         m_tap_script_sigs.emplace(pubkey_leaf, sig);
     186                 :             :     }
     187         [ +  + ]:       17039 :     if (!sigdata.tr_spenddata.internal_key.IsNull()) {
     188                 :        1195 :         m_tap_internal_key = sigdata.tr_spenddata.internal_key;
     189                 :             :     }
     190         [ +  + ]:       17039 :     if (!sigdata.tr_spenddata.merkle_root.IsNull()) {
     191                 :        1057 :         m_tap_merkle_root = sigdata.tr_spenddata.merkle_root;
     192                 :             :     }
     193         [ +  + ]:       18689 :     for (const auto& [leaf_script, control_block] : sigdata.tr_spenddata.scripts) {
     194                 :        1650 :         m_tap_scripts.emplace(leaf_script, control_block);
     195                 :             :     }
     196         [ +  + ]:       20510 :     for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
     197                 :        3471 :         m_tap_bip32_paths.emplace(pubkey, leaf_origin);
     198                 :             :     }
     199                 :             : }
     200                 :             : 
     201                 :           9 : void PSBTInput::Merge(const PSBTInput& input)
     202                 :             : {
     203   [ +  +  +  + ]:           9 :     if (!non_witness_utxo && input.non_witness_utxo) non_witness_utxo = input.non_witness_utxo;
     204   [ +  +  +  + ]:           9 :     if (witness_utxo.IsNull() && !input.witness_utxo.IsNull()) {
     205                 :           1 :         witness_utxo = input.witness_utxo;
     206                 :             :     }
     207                 :             : 
     208                 :           9 :     partial_sigs.insert(input.partial_sigs.begin(), input.partial_sigs.end());
     209                 :           9 :     ripemd160_preimages.insert(input.ripemd160_preimages.begin(), input.ripemd160_preimages.end());
     210                 :           9 :     sha256_preimages.insert(input.sha256_preimages.begin(), input.sha256_preimages.end());
     211                 :           9 :     hash160_preimages.insert(input.hash160_preimages.begin(), input.hash160_preimages.end());
     212                 :           9 :     hash256_preimages.insert(input.hash256_preimages.begin(), input.hash256_preimages.end());
     213                 :           9 :     hd_keypaths.insert(input.hd_keypaths.begin(), input.hd_keypaths.end());
     214                 :           9 :     unknown.insert(input.unknown.begin(), input.unknown.end());
     215                 :           9 :     m_tap_script_sigs.insert(input.m_tap_script_sigs.begin(), input.m_tap_script_sigs.end());
     216                 :           9 :     m_tap_scripts.insert(input.m_tap_scripts.begin(), input.m_tap_scripts.end());
     217                 :           9 :     m_tap_bip32_paths.insert(input.m_tap_bip32_paths.begin(), input.m_tap_bip32_paths.end());
     218                 :             : 
     219   [ +  +  +  +  :          11 :     if (redeem_script.empty() && !input.redeem_script.empty()) redeem_script = input.redeem_script;
             -  +  -  + ]
     220   [ +  +  +  +  :          11 :     if (witness_script.empty() && !input.witness_script.empty()) witness_script = input.witness_script;
             -  +  -  + ]
     221   [ -  +  +  -  :           9 :     if (final_script_sig.empty() && !input.final_script_sig.empty()) final_script_sig = input.final_script_sig;
             -  +  -  + ]
     222   [ +  +  +  + ]:           9 :     if (final_script_witness.IsNull() && !input.final_script_witness.IsNull()) final_script_witness = input.final_script_witness;
     223   [ +  -  -  + ]:           9 :     if (m_tap_key_sig.empty() && !input.m_tap_key_sig.empty()) m_tap_key_sig = input.m_tap_key_sig;
     224   [ +  +  -  + ]:           9 :     if (m_tap_internal_key.IsNull() && !input.m_tap_internal_key.IsNull()) m_tap_internal_key = input.m_tap_internal_key;
     225   [ +  +  -  + ]:           9 :     if (m_tap_merkle_root.IsNull() && !input.m_tap_merkle_root.IsNull()) m_tap_merkle_root = input.m_tap_merkle_root;
     226                 :           9 : }
     227                 :             : 
     228                 :         843 : void PSBTOutput::FillSignatureData(SignatureData& sigdata) const
     229                 :             : {
     230   [ -  +  +  + ]:         843 :     if (!redeem_script.empty()) {
     231                 :           5 :         sigdata.redeem_script = redeem_script;
     232                 :             :     }
     233   [ +  +  +  + ]:         851 :     if (!witness_script.empty()) {
     234                 :           8 :         sigdata.witness_script = witness_script;
     235                 :             :     }
     236         [ +  + ]:        1122 :     for (const auto& key_pair : hd_keypaths) {
     237                 :         279 :         sigdata.misc_pubkeys.emplace(key_pair.first.GetID(), key_pair);
     238                 :             :     }
     239   [ +  +  +  - ]:         843 :     if (!m_tap_tree.empty() && m_tap_internal_key.IsFullyValid()) {
     240                 :         105 :         TaprootBuilder builder;
     241   [ +  -  +  + ]:         378 :         for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
     242         [ +  - ]:         273 :             builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
     243                 :             :         }
     244         [ -  + ]:         105 :         assert(builder.IsComplete());
     245         [ +  - ]:         105 :         builder.Finalize(m_tap_internal_key);
     246         [ +  - ]:         105 :         TaprootSpendData spenddata = builder.GetSpendData();
     247                 :             : 
     248                 :         105 :         sigdata.tr_spenddata.internal_key = m_tap_internal_key;
     249   [ +  -  +  - ]:         210 :         sigdata.tr_spenddata.Merge(spenddata);
     250                 :         105 :     }
     251         [ +  + ]:        1173 :     for (const auto& [pubkey, leaf_origin] : m_tap_bip32_paths) {
     252                 :         330 :         sigdata.taproot_misc_pubkeys.emplace(pubkey, leaf_origin);
     253                 :         330 :         sigdata.tap_pubkeys.emplace(Hash160(pubkey), pubkey);
     254                 :             :     }
     255                 :         843 : }
     256                 :             : 
     257                 :         843 : void PSBTOutput::FromSignatureData(const SignatureData& sigdata)
     258                 :             : {
     259   [ -  +  +  +  :         843 :     if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
             -  +  +  + ]
     260                 :          21 :         redeem_script = sigdata.redeem_script;
     261                 :             :     }
     262   [ +  +  +  +  :         861 :     if (witness_script.empty() && !sigdata.witness_script.empty()) {
             +  +  +  + ]
     263                 :          10 :         witness_script = sigdata.witness_script;
     264                 :             :     }
     265         [ +  + ]:        1508 :     for (const auto& entry : sigdata.misc_pubkeys) {
     266                 :         665 :         hd_keypaths.emplace(entry.second);
     267                 :             :     }
     268         [ +  + ]:         843 :     if (!sigdata.tr_spenddata.internal_key.IsNull()) {
     269                 :         187 :         m_tap_internal_key = sigdata.tr_spenddata.internal_key;
     270                 :             :     }
     271   [ +  +  +  + ]:         843 :     if (sigdata.tr_builder.has_value() && sigdata.tr_builder->HasScripts()) {
     272                 :         158 :         m_tap_tree = sigdata.tr_builder->GetTreeTuples();
     273                 :             :     }
     274         [ +  + ]:        1344 :     for (const auto& [pubkey, leaf_origin] : sigdata.taproot_misc_pubkeys) {
     275                 :         501 :         m_tap_bip32_paths.emplace(pubkey, leaf_origin);
     276                 :             :     }
     277                 :         843 : }
     278                 :             : 
     279                 :           0 : bool PSBTOutput::IsNull() const
     280                 :             : {
     281   [ #  #  #  #  :           0 :     return redeem_script.empty() && witness_script.empty() && hd_keypaths.empty() && unknown.empty();
          #  #  #  #  #  
                #  #  # ]
     282                 :             : }
     283                 :             : 
     284                 :          10 : void PSBTOutput::Merge(const PSBTOutput& output)
     285                 :             : {
     286                 :          10 :     hd_keypaths.insert(output.hd_keypaths.begin(), output.hd_keypaths.end());
     287                 :          10 :     unknown.insert(output.unknown.begin(), output.unknown.end());
     288                 :          10 :     m_tap_bip32_paths.insert(output.m_tap_bip32_paths.begin(), output.m_tap_bip32_paths.end());
     289                 :             : 
     290   [ -  +  +  -  :          10 :     if (redeem_script.empty() && !output.redeem_script.empty()) redeem_script = output.redeem_script;
             -  +  -  + ]
     291   [ +  +  +  +  :          11 :     if (witness_script.empty() && !output.witness_script.empty()) witness_script = output.witness_script;
             -  +  -  + ]
     292   [ +  +  -  + ]:          10 :     if (m_tap_internal_key.IsNull() && !output.m_tap_internal_key.IsNull()) m_tap_internal_key = output.m_tap_internal_key;
     293   [ +  +  -  + ]:          10 :     if (m_tap_tree.empty() && !output.m_tap_tree.empty()) m_tap_tree = output.m_tap_tree;
     294                 :          10 : }
     295                 :             : 
     296                 :       45352 : bool PSBTInputSigned(const PSBTInput& input)
     297                 :             : {
     298   [ +  +  +  +  :       46941 :     return !input.final_script_sig.empty() || !input.final_script_witness.IsNull();
                   +  + ]
     299                 :             : }
     300                 :             : 
     301                 :       22534 : bool PSBTInputSignedAndVerified(const PartiallySignedTransaction psbt, unsigned int input_index, const PrecomputedTransactionData* txdata)
     302                 :             : {
     303                 :       22534 :     CTxOut utxo;
     304         [ -  + ]:       22534 :     assert(psbt.inputs.size() >= input_index);
     305         [ +  + ]:       22534 :     const PSBTInput& input = psbt.inputs[input_index];
     306                 :             : 
     307         [ +  + ]:       22534 :     if (input.non_witness_utxo) {
     308                 :             :         // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
     309         [ +  - ]:       20897 :         COutPoint prevout = psbt.tx->vin[input_index].prevout;
     310         [ +  - ]:       20897 :         if (prevout.n >= input.non_witness_utxo->vout.size()) {
     311                 :             :             return false;
     312                 :             :         }
     313         [ +  - ]:       20897 :         if (input.non_witness_utxo->GetHash() != prevout.hash) {
     314                 :             :             return false;
     315                 :             :         }
     316                 :       20897 :         utxo = input.non_witness_utxo->vout[prevout.n];
     317         [ +  + ]:        1637 :     } else if (!input.witness_utxo.IsNull()) {
     318                 :        1609 :         utxo = input.witness_utxo;
     319                 :             :     } else {
     320                 :             :         return false;
     321                 :             :     }
     322                 :             : 
     323         [ +  + ]:       22506 :     if (txdata) {
     324         [ +  - ]:       22503 :         return VerifyScript(input.final_script_sig, utxo.scriptPubKey, &input.final_script_witness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker{&(*psbt.tx), input_index, utxo.nValue, *txdata, MissingDataBehavior::FAIL});
     325                 :             :     } else {
     326         [ +  - ]:           3 :         return VerifyScript(input.final_script_sig, utxo.scriptPubKey, &input.final_script_witness, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker{&(*psbt.tx), input_index, utxo.nValue, MissingDataBehavior::FAIL});
     327                 :             :     }
     328                 :       22534 : }
     329                 :             : 
     330                 :           0 : size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt) {
     331                 :           0 :     size_t count = 0;
     332         [ #  # ]:           0 :     for (const auto& input : psbt.inputs) {
     333         [ #  # ]:           0 :         if (!PSBTInputSigned(input)) {
     334                 :           0 :             count++;
     335                 :             :         }
     336                 :             :     }
     337                 :             : 
     338                 :           0 :     return count;
     339                 :             : }
     340                 :             : 
     341                 :         843 : void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index)
     342                 :             : {
     343                 :         843 :     CMutableTransaction& tx = *Assert(psbt.tx);
     344                 :         843 :     const CTxOut& out = tx.vout.at(index);
     345                 :         843 :     PSBTOutput& psbt_out = psbt.outputs.at(index);
     346                 :             : 
     347                 :             :     // Fill a SignatureData with output info
     348                 :         843 :     SignatureData sigdata;
     349         [ +  - ]:         843 :     psbt_out.FillSignatureData(sigdata);
     350                 :             : 
     351                 :             :     // Construct a would-be spend of this output, to update sigdata with.
     352                 :             :     // Note that ProduceSignature is used to fill in metadata (not actual signatures),
     353                 :             :     // so provider does not need to provide any private keys (it can be a HidingSigningProvider).
     354         [ +  - ]:         843 :     MutableTransactionSignatureCreator creator(tx, /*input_idx=*/0, out.nValue, SIGHASH_ALL);
     355         [ +  - ]:         843 :     ProduceSignature(provider, creator, out.scriptPubKey, sigdata);
     356                 :             : 
     357                 :             :     // Put redeem_script, witness_script, key paths, into PSBTOutput.
     358         [ +  - ]:         843 :     psbt_out.FromSignatureData(sigdata);
     359                 :         843 : }
     360                 :             : 
     361                 :        1336 : PrecomputedTransactionData PrecomputePSBTData(const PartiallySignedTransaction& psbt)
     362                 :             : {
     363                 :        1336 :     const CMutableTransaction& tx = *psbt.tx;
     364                 :        1336 :     bool have_all_spent_outputs = true;
     365                 :        1336 :     std::vector<CTxOut> utxos(tx.vin.size());
     366         [ +  + ]:        5761 :     for (size_t idx = 0; idx < tx.vin.size(); ++idx) {
     367   [ +  -  +  + ]:        4425 :         if (!psbt.GetInputUTXO(utxos[idx], idx)) have_all_spent_outputs = false;
     368                 :             :     }
     369                 :        1336 :     PrecomputedTransactionData txdata;
     370         [ +  + ]:        1336 :     if (have_all_spent_outputs) {
     371         [ +  - ]:        1308 :         txdata.Init(tx, std::move(utxos), true);
     372                 :             :     } else {
     373         [ +  - ]:          28 :         txdata.Init(tx, {}, true);
     374                 :             :     }
     375                 :        1336 :     return txdata;
     376                 :        1336 : }
     377                 :             : 
     378                 :       19584 : PSBTError SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, std::optional<int> sighash,  SignatureData* out_sigdata, bool finalize)
     379                 :             : {
     380                 :       19584 :     PSBTInput& input = psbt.inputs.at(index);
     381                 :       19584 :     const CMutableTransaction& tx = *psbt.tx;
     382                 :             : 
     383   [ +  -  +  + ]:       19584 :     if (PSBTInputSignedAndVerified(psbt, index, txdata)) {
     384                 :             :         return PSBTError::OK;
     385                 :             :     }
     386                 :             : 
     387                 :             :     // Fill SignatureData with input info
     388                 :       18452 :     SignatureData sigdata;
     389         [ +  - ]:       18452 :     input.FillSignatureData(sigdata);
     390                 :             : 
     391                 :             :     // Get UTXO
     392                 :       18452 :     bool require_witness_sig = false;
     393                 :       18452 :     CTxOut utxo;
     394                 :             : 
     395         [ +  + ]:       18452 :     if (input.non_witness_utxo) {
     396                 :             :         // If we're taking our information from a non-witness UTXO, verify that it matches the prevout.
     397         [ +  - ]:       17449 :         COutPoint prevout = tx.vin[index].prevout;
     398         [ +  - ]:       17449 :         if (prevout.n >= input.non_witness_utxo->vout.size()) {
     399                 :             :             return PSBTError::MISSING_INPUTS;
     400                 :             :         }
     401         [ +  - ]:       17449 :         if (input.non_witness_utxo->GetHash() != prevout.hash) {
     402                 :             :             return PSBTError::MISSING_INPUTS;
     403                 :             :         }
     404                 :       17449 :         utxo = input.non_witness_utxo->vout[prevout.n];
     405         [ +  + ]:        1003 :     } else if (!input.witness_utxo.IsNull()) {
     406                 :         999 :         utxo = input.witness_utxo;
     407                 :             :         // When we're taking our information from a witness UTXO, we can't verify it is actually data from
     408                 :             :         // the output being spent. This is safe in case a witness signature is produced (which includes this
     409                 :             :         // information directly in the hash), but not for non-witness signatures. Remember that we require
     410                 :             :         // a witness signature in this situation.
     411                 :         999 :         require_witness_sig = true;
     412                 :             :     } else {
     413                 :             :         return PSBTError::MISSING_INPUTS;
     414                 :             :     }
     415                 :             : 
     416                 :             :     // Get the sighash type
     417                 :             :     // If both the field and the parameter are provided, they must match
     418                 :             :     // If only the parameter is provided, use it and add it to the PSBT if it is other than SIGHASH_DEFAULT
     419                 :             :     // for all input types, and not SIGHASH_ALL for non-taproot input types.
     420                 :             :     // If neither are provided, use SIGHASH_DEFAULT if it is taproot, and SIGHASH_ALL for everything else.
     421   [ +  +  +  -  :       34716 :     if (!sighash) sighash = utxo.scriptPubKey.IsPayToTaproot() ? SIGHASH_DEFAULT : SIGHASH_ALL;
                   +  + ]
     422         [ +  - ]:       18448 :     Assert(sighash.has_value());
     423                 :             :     // For user safety, the desired sighash must be provided if the PSBT wants something other than the default set in the previous line.
     424   [ +  +  +  - ]:       36900 :     if (input.sighash_type && input.sighash_type != sighash) {
     425                 :             :         return PSBTError::SIGHASH_MISMATCH;
     426                 :             :     }
     427                 :             :     // Set the PSBT sighash field when sighash is not DEFAULT or ALL
     428                 :             :     // DEFAULT is allowed for non-taproot inputs since DEFAULT may be passed for them (e.g. the psbt being signed also has taproot inputs)
     429                 :             :     // Note that signing already aliases DEFAULT to ALL for non-taproot inputs.
     430   [ +  -  +  +  :       18434 :     if (utxo.scriptPubKey.IsPayToTaproot() ? sighash != SIGHASH_DEFAULT :
                   +  - ]
     431   [ +  -  +  - ]:       33464 :                                             (sighash != SIGHASH_DEFAULT && sighash != SIGHASH_ALL)) {
     432                 :          34 :         input.sighash_type = sighash;
     433                 :             :     }
     434                 :             : 
     435                 :             :     // Check all existing signatures use the sighash type
     436         [ +  - ]:       18434 :     if (sighash == SIGHASH_DEFAULT) {
     437   [ +  +  +  - ]:        1687 :         if (!input.m_tap_key_sig.empty() && input.m_tap_key_sig.size() != 64) {
     438                 :             :             return PSBTError::SIGHASH_MISMATCH;
     439                 :             :         }
     440   [ +  -  +  + ]:        2307 :         for (const auto& [_, sig] : input.m_tap_script_sigs) {
     441         [ +  - ]:         620 :             if (sig.size() != 64) return PSBTError::SIGHASH_MISMATCH;
     442                 :             :         }
     443                 :             :     } else {
     444   [ +  +  +  -  :       16747 :         if (!input.m_tap_key_sig.empty() && (input.m_tap_key_sig.size() != 65 || input.m_tap_key_sig.back() != *sighash)) {
                   +  + ]
     445                 :             :             return PSBTError::SIGHASH_MISMATCH;
     446                 :             :         }
     447   [ -  -  -  + ]:       16745 :         for (const auto& [_, sig] : input.m_tap_script_sigs) {
     448   [ #  #  #  # ]:           0 :             if (sig.size() != 65 || sig.back() != *sighash) return PSBTError::SIGHASH_MISMATCH;
     449                 :             :         }
     450   [ +  +  +  + ]:       17106 :         for (const auto& [_, sig] : input.partial_sigs) {
     451         [ +  + ]:         363 :             if (sig.second.back() != *sighash) return PSBTError::SIGHASH_MISMATCH;
     452                 :             :         }
     453                 :             :     }
     454                 :             : 
     455                 :       18430 :     sigdata.witness = false;
     456                 :       18430 :     bool sig_complete;
     457         [ +  + ]:       18430 :     if (txdata == nullptr) {
     458         [ +  - ]:           1 :         sig_complete = ProduceSignature(provider, DUMMY_SIGNATURE_CREATOR, utxo.scriptPubKey, sigdata);
     459                 :             :     } else {
     460         [ +  - ]:       18429 :         MutableTransactionSignatureCreator creator(tx, index, utxo.nValue, txdata, *sighash);
     461         [ +  - ]:       18429 :         sig_complete = ProduceSignature(provider, creator, utxo.scriptPubKey, sigdata);
     462                 :       18429 :     }
     463                 :             :     // Verify that a witness signature was produced in case one was required.
     464   [ +  +  +  + ]:       18430 :     if (require_witness_sig && !sigdata.witness) return PSBTError::INCOMPLETE;
     465                 :             : 
     466                 :             :     // If we are not finalizing, set sigdata.complete to false to not set the scriptWitness
     467   [ +  +  +  + ]:       18401 :     if (!finalize && sigdata.complete) sigdata.complete = false;
     468                 :             : 
     469         [ +  - ]:       18401 :     input.FromSignatureData(sigdata);
     470                 :             : 
     471                 :             :     // If we have a witness signature, put a witness UTXO.
     472         [ +  + ]:       18401 :     if (sigdata.witness) {
     473                 :       13877 :         input.witness_utxo = utxo;
     474                 :             :         // We can remove the non_witness_utxo if and only if there are no non-segwit or segwit v0
     475                 :             :         // inputs in this transaction. Since this requires inspecting the entire transaction, this
     476                 :             :         // is something for the caller to deal with (i.e. FillPSBT).
     477                 :             :     }
     478                 :             : 
     479                 :             :     // Fill in the missing info
     480         [ +  + ]:       18401 :     if (out_sigdata) {
     481         [ +  - ]:           3 :         out_sigdata->missing_pubkeys = sigdata.missing_pubkeys;
     482         [ +  - ]:           3 :         out_sigdata->missing_sigs = sigdata.missing_sigs;
     483                 :           3 :         out_sigdata->missing_redeem_script = sigdata.missing_redeem_script;
     484                 :           3 :         out_sigdata->missing_witness_script = sigdata.missing_witness_script;
     485                 :             :     }
     486                 :             : 
     487         [ +  + ]:       18401 :     return sig_complete ? PSBTError::OK : PSBTError::INCOMPLETE;
     488                 :       18452 : }
     489                 :             : 
     490                 :         890 : void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx)
     491                 :             : {
     492                 :             :     // Figure out if any non_witness_utxos should be dropped
     493                 :         890 :     std::vector<unsigned int> to_drop;
     494         [ +  + ]:        1434 :     for (unsigned int i = 0; i < psbtx.inputs.size(); ++i) {
     495         [ +  - ]:        1090 :         const auto& input = psbtx.inputs.at(i);
     496                 :        1090 :         int wit_ver;
     497                 :        1090 :         std::vector<unsigned char> wit_prog;
     498   [ +  +  +  -  :        1090 :         if (input.witness_utxo.IsNull() || !input.witness_utxo.scriptPubKey.IsWitnessProgram(wit_ver, wit_prog)) {
                   +  + ]
     499                 :             :             // There's a non-segwit input, so we cannot drop any non_witness_utxos
     500         [ -  + ]:         188 :             to_drop.clear();
     501                 :             :             break;
     502                 :             :         }
     503         [ +  + ]:         902 :         if (wit_ver == 0) {
     504                 :             :             // Segwit v0, so we cannot drop any non_witness_utxos
     505         [ -  + ]:         358 :             to_drop.clear();
     506                 :             :             break;
     507                 :             :         }
     508                 :             :         // non_witness_utxos cannot be dropped if the sighash type includes SIGHASH_ANYONECANPAY
     509                 :             :         // Since callers should have called SignPSBTInput which updates the sighash type in the PSBT, we only
     510                 :             :         // need to look at that field. If it is not present, then we can assume SIGHASH_DEFAULT or SIGHASH_ALL.
     511   [ +  +  +  - ]:         544 :         if (input.sighash_type != std::nullopt && (*input.sighash_type & 0x80) == SIGHASH_ANYONECANPAY) {
     512         [ -  - ]:         546 :             to_drop.clear();
     513                 :             :             break;
     514                 :             :         }
     515                 :             : 
     516         [ +  + ]:         544 :         if (input.non_witness_utxo) {
     517         [ +  - ]:         271 :             to_drop.push_back(i);
     518                 :             :         }
     519                 :        1090 :     }
     520                 :             : 
     521                 :             :     // Drop the non_witness_utxos that we can drop
     522         [ +  + ]:        1161 :     for (unsigned int i : to_drop) {
     523   [ +  -  -  + ]:         271 :         psbtx.inputs.at(i).non_witness_utxo = nullptr;
     524                 :             :     }
     525                 :         890 : }
     526                 :             : 
     527                 :         424 : bool FinalizePSBT(PartiallySignedTransaction& psbtx)
     528                 :             : {
     529                 :             :     // Finalize input signatures -- in case we have partial signatures that add up to a complete
     530                 :             :     //   signature, but have not combined them yet (e.g. because the combiner that created this
     531                 :             :     //   PartiallySignedTransaction did not understand them), this will combine them into a final
     532                 :             :     //   script.
     533                 :         424 :     bool complete = true;
     534                 :         424 :     const PrecomputedTransactionData txdata = PrecomputePSBTData(psbtx);
     535         [ +  + ]:        1868 :     for (unsigned int i = 0; i < psbtx.tx->vin.size(); ++i) {
     536         [ +  - ]:        1444 :         PSBTInput& input = psbtx.inputs.at(i);
     537         [ +  - ]:        1444 :         complete &= (SignPSBTInput(DUMMY_SIGNING_PROVIDER, psbtx, i, &txdata, input.sighash_type, nullptr, true) == PSBTError::OK);
     538                 :             :     }
     539                 :             : 
     540                 :         424 :     return complete;
     541                 :         424 : }
     542                 :             : 
     543                 :         421 : bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result)
     544                 :             : {
     545                 :             :     // It's not safe to extract a PSBT that isn't finalized, and there's no easy way to check
     546                 :             :     //   whether a PSBT is finalized without finalizing it, so we just do this.
     547         [ +  + ]:         421 :     if (!FinalizePSBT(psbtx)) {
     548                 :             :         return false;
     549                 :             :     }
     550                 :             : 
     551                 :         389 :     result = *psbtx.tx;
     552         [ +  + ]:        1758 :     for (unsigned int i = 0; i < result.vin.size(); ++i) {
     553                 :        1369 :         result.vin[i].scriptSig = psbtx.inputs[i].final_script_sig;
     554                 :        1369 :         result.vin[i].scriptWitness = psbtx.inputs[i].final_script_witness;
     555                 :             :     }
     556                 :             :     return true;
     557                 :             : }
     558                 :             : 
     559                 :           8 : bool CombinePSBTs(PartiallySignedTransaction& out, const std::vector<PartiallySignedTransaction>& psbtxs)
     560                 :             : {
     561                 :           8 :     out = psbtxs[0]; // Copy the first one
     562                 :             : 
     563                 :             :     // Merge
     564         [ +  + ]:          15 :     for (auto it = std::next(psbtxs.begin()); it != psbtxs.end(); ++it) {
     565         [ +  + ]:           8 :         if (!out.Merge(*it)) {
     566                 :             :             return false;
     567                 :             :         }
     568                 :             :     }
     569                 :             :     return true;
     570                 :             : }
     571                 :             : 
     572                 :          11 : std::string PSBTRoleName(PSBTRole role) {
     573   [ +  +  +  +  :          11 :     switch (role) {
                   +  - ]
     574                 :           3 :     case PSBTRole::CREATOR: return "creator";
     575                 :           2 :     case PSBTRole::UPDATER: return "updater";
     576                 :           2 :     case PSBTRole::SIGNER: return "signer";
     577                 :           2 :     case PSBTRole::FINALIZER: return "finalizer";
     578                 :           2 :     case PSBTRole::EXTRACTOR: return "extractor";
     579                 :             :         // no default case, so the compiler can warn about missing cases
     580                 :             :     }
     581                 :           0 :     assert(false);
     582                 :             : }
     583                 :             : 
     584                 :         916 : bool DecodeBase64PSBT(PartiallySignedTransaction& psbt, const std::string& base64_tx, std::string& error)
     585                 :             : {
     586                 :         916 :     auto tx_data = DecodeBase64(base64_tx);
     587         [ +  + ]:         916 :     if (!tx_data) {
     588         [ +  - ]:         916 :         error = "invalid base64";
     589                 :             :         return false;
     590                 :             :     }
     591         [ +  - ]:         914 :     return DecodeRawPSBT(psbt, MakeByteSpan(*tx_data), error);
     592                 :         916 : }
     593                 :             : 
     594                 :         914 : bool DecodeRawPSBT(PartiallySignedTransaction& psbt, std::span<const std::byte> tx_data, std::string& error)
     595                 :             : {
     596                 :         914 :     DataStream ss_data{tx_data};
     597                 :         914 :     try {
     598         [ +  + ]:         914 :         ss_data >> psbt;
     599         [ -  + ]:         859 :         if (!ss_data.empty()) {
     600         [ -  - ]:         914 :             error = "extra data after PSBT";
     601                 :             :             return false;
     602                 :             :         }
     603         [ -  + ]:          55 :     } catch (const std::exception& e) {
     604         [ +  - ]:          55 :         error = e.what();
     605                 :          55 :         return false;
     606                 :          55 :     }
     607                 :             :     return true;
     608                 :         914 : }
     609                 :             : 
     610                 :         903 : uint32_t PartiallySignedTransaction::GetVersion() const
     611                 :             : {
     612         [ +  + ]:         903 :     if (m_version != std::nullopt) {
     613                 :           1 :         return *m_version;
     614                 :             :     }
     615                 :             :     return 0;
     616                 :             : }
        

Generated by: LCOV version 2.0-1