LCOV - code coverage report
Current view: top level - src/script - sign.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 94.6 % 597 565
Test Date: 2026-08-01 07:05:06 Functions: 87.8 % 49 43
Branches: 61.1 % 1076 657

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-present The Bitcoin Core developers
       3                 :             : // Distributed under the MIT software license, see the accompanying
       4                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :             : 
       6                 :             : #include <script/sign.h>
       7                 :             : 
       8                 :             : #include <addresstype.h>
       9                 :             : #include <coins.h>
      10                 :             : #include <consensus/amount.h>
      11                 :             : #include <hash.h>
      12                 :             : #include <key.h>
      13                 :             : #include <musig.h>
      14                 :             : #include <policy/policy.h>
      15                 :             : #include <prevector.h>
      16                 :             : #include <primitives/transaction.h>
      17                 :             : #include <script/keyorigin.h>
      18                 :             : #include <script/miniscript.h>
      19                 :             : #include <script/script.h>
      20                 :             : #include <script/script_error.h>
      21                 :             : #include <script/signingprovider.h>
      22                 :             : #include <script/solver.h>
      23                 :             : #include <script/verify_flags.h>
      24                 :             : #include <serialize.h>
      25                 :             : #include <uint256.h>
      26                 :             : #include <util/check.h>
      27                 :             : #include <util/translation.h>
      28                 :             : #include <util/vector.h>
      29                 :             : 
      30                 :             : #include <algorithm>
      31                 :             : #include <array>
      32                 :             : #include <cstddef>
      33                 :             : #include <functional>
      34                 :             : #include <iterator>
      35                 :             : #include <span>
      36                 :             : #include <string>
      37                 :             : 
      38                 :             : typedef std::vector<unsigned char> valtype;
      39                 :             : 
      40                 :        5691 : MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, const SignOptions& options)
      41                 :        5691 :     : m_txto{tx}, nIn{input_idx}, m_options{options}, amount{amount}, checker{&m_txto, nIn, amount, MissingDataBehavior::FAIL},
      42                 :        5691 :       m_txdata(nullptr)
      43                 :             : {
      44                 :        5691 : }
      45                 :             : 
      46                 :       66893 : MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, const PrecomputedTransactionData* txdata, const SignOptions& options)
      47                 :       66893 :     : m_txto{tx}, nIn{input_idx}, m_options{options}, amount{amount},
      48         [ +  - ]:       66893 :       checker{txdata ? MutableTransactionSignatureChecker{&m_txto, nIn, amount, *txdata, MissingDataBehavior::FAIL} :
      49                 :             :                        MutableTransactionSignatureChecker{&m_txto, nIn, amount, MissingDataBehavior::FAIL}},
      50         [ +  - ]:       66893 :       m_txdata(txdata)
      51                 :             : {
      52                 :       66893 : }
      53                 :             : 
      54                 :       31782 : bool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
      55                 :             : {
      56         [ -  + ]:       31782 :     assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
      57                 :             : 
      58                 :       31782 :     CKey key;
      59   [ +  -  +  + ]:       31782 :     if (!provider.GetKey(address, key))
      60                 :             :         return false;
      61                 :             : 
      62                 :             :     // Signing with uncompressed keys is disabled in witness scripts
      63   [ +  +  +  + ]:       16388 :     if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())
      64                 :             :         return false;
      65                 :             : 
      66                 :             :     // Signing without known amount does not work in witness scripts.
      67   [ +  +  +  - ]:       16384 :     if (sigversion == SigVersion::WITNESS_V0 && !MoneyRange(amount)) return false;
      68                 :             : 
      69                 :             :     // BASE/WITNESS_V0 signatures don't support explicit SIGHASH_DEFAULT, use SIGHASH_ALL instead.
      70         [ +  + ]:       16384 :     const int hashtype = m_options.sighash_type == SIGHASH_DEFAULT ? SIGHASH_ALL : m_options.sighash_type;
      71                 :             : 
      72         [ +  - ]:       16384 :     uint256 hash = SignatureHash(scriptCode, m_txto, nIn, hashtype, amount, sigversion, m_txdata);
      73   [ +  -  +  - ]:       16384 :     if (!key.Sign(hash, vchSig))
      74                 :             :         return false;
      75         [ +  - ]:       31782 :     vchSig.push_back((unsigned char)hashtype);
      76                 :             :     return true;
      77                 :       31782 : }
      78                 :             : 
      79                 :        1548 : std::optional<uint256> MutableTransactionSignatureCreator::ComputeSchnorrSignatureHash(const uint256* leaf_hash, SigVersion sigversion) const
      80                 :             : {
      81         [ -  + ]:        1548 :     assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
      82                 :             : 
      83                 :             :     // BIP341/BIP342 signing needs lots of precomputed transaction data. While some
      84                 :             :     // (non-SIGHASH_DEFAULT) sighash modes exist that can work with just some subset
      85                 :             :     // of data present, for now, only support signing when everything is provided.
      86   [ +  -  +  -  :        1548 :     if (!m_txdata || !m_txdata->m_bip341_taproot_ready || !m_txdata->m_spent_outputs_ready) return std::nullopt;
                   -  + ]
      87                 :             : 
      88         [ +  + ]:        1548 :     ScriptExecutionData execdata;
      89                 :        1548 :     execdata.m_annex_init = true;
      90                 :        1548 :     execdata.m_annex_present = false; // Only support annex-less signing for now.
      91         [ +  + ]:        1548 :     if (sigversion == SigVersion::TAPSCRIPT) {
      92                 :         729 :         execdata.m_codeseparator_pos_init = true;
      93                 :         729 :         execdata.m_codeseparator_pos = 0xFFFFFFFF; // Only support non-OP_CODESEPARATOR BIP342 signing for now.
      94         [ -  + ]:         729 :         if (!leaf_hash) return std::nullopt; // BIP342 signing needs leaf hash.
      95                 :         729 :         execdata.m_tapleaf_hash_init = true;
      96                 :         729 :         execdata.m_tapleaf_hash = *leaf_hash;
      97                 :             :     }
      98                 :        1548 :     uint256 hash;
      99         [ -  + ]:        1548 :     if (!SignatureHashSchnorr(hash, execdata, m_txto, nIn, m_options.sighash_type, sigversion, *m_txdata, MissingDataBehavior::FAIL)) return std::nullopt;
     100                 :        1548 :     return hash;
     101                 :             : }
     102                 :             : 
     103                 :      121388 : bool MutableTransactionSignatureCreator::CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion) const
     104                 :             : {
     105                 :      121388 :     CKey key;
     106   [ +  -  +  + ]:      121388 :     if (!provider.GetKeyByXOnly(pubkey, key)) return false;
     107                 :             : 
     108         [ +  - ]:        1080 :     std::optional<uint256> hash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
     109         [ +  - ]:        1080 :     if (!hash.has_value()) return false;
     110                 :             : 
     111         [ +  - ]:        1080 :     sig.resize(64);
     112                 :             :     // Use uint256{} as aux_rnd for now.
     113   [ -  +  +  -  :        1080 :     if (!key.SignSchnorr(*hash, sig, merkle_root, {})) return false;
                   +  - ]
     114   [ +  +  +  - ]:      121388 :     if (m_options.sighash_type) sig.push_back(m_options.sighash_type);
     115                 :             :     return true;
     116                 :      121388 : }
     117                 :             : 
     118                 :        4932 : std::vector<uint8_t> MutableTransactionSignatureCreator::CreateMuSig2Nonce(const SigningProvider& provider, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion, const SignatureData& sigdata) const
     119                 :             : {
     120         [ -  + ]:        4932 :     assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
     121                 :             : 
     122                 :             :     // Retrieve the private key
     123                 :        4932 :     CKey key;
     124   [ +  -  +  -  :        4932 :     if (!provider.GetKey(part_pubkey.GetID(), key)) return {};
                   +  + ]
     125                 :             : 
     126                 :             :     // Retrieve participant pubkeys
     127                 :         151 :     auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey);
     128         [ -  + ]:         151 :     if (it == sigdata.musig2_pubkeys.end()) return {};
     129                 :         151 :     const std::vector<CPubKey>& pubkeys = it->second;
     130         [ -  + ]:         151 :     if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {};
     131                 :             : 
     132                 :             :     // Compute sighash
     133         [ +  - ]:         151 :     std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
     134         [ -  + ]:         151 :     if (!sighash.has_value()) return {};
     135                 :             : 
     136         [ +  - ]:         151 :     MuSig2SecNonce secnonce;
     137         [ +  - ]:         151 :     std::vector<uint8_t> out = ::CreateMuSig2Nonce(secnonce, *sighash, key, aggregate_pubkey, pubkeys);
     138         [ -  + ]:         151 :     if (out.empty()) return {};
     139                 :             : 
     140                 :             :     // Store the secnonce in the SigningProvider
     141   [ +  -  +  - ]:         151 :     provider.SetMuSig2SecNonce(MuSig2SessionID(script_pubkey, part_pubkey, *sighash, out), std::move(secnonce));
     142                 :             : 
     143                 :         151 :     return out;
     144                 :        5083 : }
     145                 :             : 
     146                 :       10304 : bool MutableTransactionSignatureCreator::CreateMuSig2PartialSig(const SigningProvider& provider, uint256& partial_sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const
     147                 :             : {
     148         [ -  + ]:       10304 :     assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
     149                 :             : 
     150                 :             :     // Retrieve private key
     151                 :       10304 :     CKey key;
     152   [ +  -  +  -  :       10304 :     if (!provider.GetKey(part_pubkey.GetID(), key)) return false;
                   +  + ]
     153                 :             : 
     154                 :             :     // Retrieve participant pubkeys
     155                 :         533 :     auto it = sigdata.musig2_pubkeys.find(aggregate_pubkey);
     156         [ +  - ]:         533 :     if (it == sigdata.musig2_pubkeys.end()) return false;
     157                 :         533 :     const std::vector<CPubKey>& pubkeys = it->second;
     158         [ +  - ]:         533 :     if (std::find(pubkeys.begin(), pubkeys.end(), part_pubkey) == pubkeys.end()) return {};
     159                 :             : 
     160                 :             :     // Retrieve pubnonces
     161         [ +  + ]:         533 :     auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256());
     162                 :         533 :     auto pubnonce_it = sigdata.musig2_pubnonces.find(this_leaf_aggkey);
     163         [ +  + ]:         533 :     if (pubnonce_it == sigdata.musig2_pubnonces.end()) return false;
     164         [ -  + ]:         469 :     const std::map<CPubKey, std::vector<uint8_t>>& pubnonces = pubnonce_it->second;
     165                 :             : 
     166                 :             :     // Check if enough pubnonces
     167   [ -  +  +  + ]:         469 :     if (pubnonces.size() != pubkeys.size()) return false;
     168                 :             : 
     169                 :             :     // Compute sighash
     170         [ +  - ]:         248 :     std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
     171         [ +  - ]:         248 :     if (!sighash.has_value()) return false;
     172                 :             : 
     173                 :             :     // Retrieve the secnonce
     174                 :         248 :     auto part_pubnonce_it = pubnonces.find(part_pubkey);
     175         [ +  - ]:         248 :     if (part_pubnonce_it == pubnonces.end()) return false;
     176         [ +  - ]:         248 :     uint256 session_id = MuSig2SessionID(script_pubkey, part_pubkey, *sighash, part_pubnonce_it->second);
     177         [ +  - ]:         248 :     std::optional<std::reference_wrapper<MuSig2SecNonce>> secnonce = provider.GetMuSig2SecNonce(session_id);
     178   [ +  +  +  -  :         248 :     if (!secnonce || !secnonce->get().IsValid()) return false;
                   -  + ]
     179                 :             : 
     180                 :             :     // Compute the sig
     181         [ +  - ]:         140 :     std::optional<uint256> sig = ::CreateMuSig2PartialSig(*sighash, key, aggregate_pubkey, pubkeys, pubnonces, *secnonce, tweaks);
     182         [ +  - ]:         140 :     if (!sig) return false;
     183         [ +  - ]:         140 :     partial_sig = std::move(*sig);
     184                 :             : 
     185                 :             :     // Delete the secnonce now that we're done with it
     186   [ +  -  -  + ]:         140 :     assert(!secnonce->get().IsValid());
     187         [ +  - ]:         140 :     provider.DeleteMuSig2Session(session_id);
     188                 :             : 
     189                 :             :     return true;
     190                 :       10304 : }
     191                 :             : 
     192                 :        3768 : bool MutableTransactionSignatureCreator::CreateMuSig2AggregateSig(const std::vector<CPubKey>& participants, std::vector<uint8_t>& sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const
     193                 :             : {
     194         [ -  + ]:        3768 :     assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
     195   [ -  +  +  - ]:        3768 :     if (!participants.size()) return false;
     196                 :             : 
     197                 :             :     // Retrieve pubnonces and partial sigs
     198         [ +  + ]:        3768 :     auto this_leaf_aggkey = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256());
     199                 :        3768 :     auto pubnonce_it = sigdata.musig2_pubnonces.find(this_leaf_aggkey);
     200         [ +  + ]:        3768 :     if (pubnonce_it == sigdata.musig2_pubnonces.end()) return false;
     201                 :        3446 :     const std::map<CPubKey, std::vector<uint8_t>>& pubnonces = pubnonce_it->second;
     202                 :        3446 :     auto partial_sigs_it = sigdata.musig2_partial_sigs.find(this_leaf_aggkey);
     203         [ +  + ]:        3446 :     if (partial_sigs_it == sigdata.musig2_partial_sigs.end()) return false;
     204         [ -  + ]:         751 :     const std::map<CPubKey, uint256>& partial_sigs = partial_sigs_it->second;
     205                 :             : 
     206                 :             :     // Check if enough pubnonces and partial sigs
     207   [ -  +  +  - ]:         751 :     if (pubnonces.size() != participants.size()) return false;
     208         [ +  + ]:         751 :     if (partial_sigs.size() != participants.size()) return false;
     209                 :             : 
     210                 :             :     // Compute sighash
     211                 :          69 :     std::optional<uint256> sighash = ComputeSchnorrSignatureHash(leaf_hash, sigversion);
     212         [ +  - ]:          69 :     if (!sighash.has_value()) return false;
     213                 :             : 
     214                 :          69 :     std::optional<std::vector<uint8_t>> res = ::CreateMuSig2AggregateSig(participants, aggregate_pubkey, tweaks, *sighash, pubnonces, partial_sigs);
     215         [ +  - ]:          69 :     if (!res) return false;
     216         [ +  - ]:          69 :     sig = res.value();
     217   [ +  +  +  - ]:          69 :     if (m_options.sighash_type) sig.push_back(m_options.sighash_type);
     218                 :             : 
     219                 :             :     return true;
     220                 :          69 : }
     221                 :             : 
     222                 :        7846 : static bool GetCScript(const SigningProvider& provider, const SignatureData& sigdata, const CScriptID& scriptid, CScript& script)
     223                 :             : {
     224         [ +  + ]:        7846 :     if (provider.GetCScript(scriptid, script)) {
     225                 :             :         return true;
     226                 :             :     }
     227                 :             :     // Look for scripts in SignatureData
     228         [ +  + ]:        5768 :     if (CScriptID(sigdata.redeem_script) == scriptid) {
     229                 :        3927 :         script = sigdata.redeem_script;
     230                 :        3927 :         return true;
     231         [ +  + ]:        1841 :     } else if (CScriptID(sigdata.witness_script) == scriptid) {
     232                 :         317 :         script = sigdata.witness_script;
     233                 :         317 :         return true;
     234                 :             :     }
     235                 :             :     return false;
     236                 :             : }
     237                 :             : 
     238                 :       60247 : static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey)
     239                 :             : {
     240                 :             :     // Look for pubkey in all partial sigs
     241                 :       60247 :     const auto it = sigdata.signatures.find(address);
     242         [ +  + ]:       60247 :     if (it != sigdata.signatures.end()) {
     243                 :          58 :         pubkey = it->second.first;
     244                 :          58 :         return true;
     245                 :             :     }
     246                 :             :     // Look for pubkey in pubkey lists
     247                 :       60189 :     const auto& pk_it = sigdata.misc_pubkeys.find(address);
     248         [ +  + ]:       60189 :     if (pk_it != sigdata.misc_pubkeys.end()) {
     249                 :       13659 :         pubkey = pk_it->second.first;
     250                 :       13659 :         return true;
     251                 :             :     }
     252                 :       46530 :     const auto& tap_pk_it = sigdata.tap_pubkeys.find(address);
     253         [ +  + ]:       46530 :     if (tap_pk_it != sigdata.tap_pubkeys.end()) {
     254                 :         290 :         pubkey = tap_pk_it->second.GetEvenCorrespondingCPubKey();
     255                 :         290 :         return true;
     256                 :             :     }
     257                 :             :     // Query the underlying provider
     258                 :       46240 :     return provider.GetPubKey(address, pubkey);
     259                 :             : }
     260                 :             : 
     261                 :       32358 : static bool CreateSig(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const CPubKey& pubkey, const CScript& scriptcode, SigVersion sigversion)
     262                 :             : {
     263                 :       32358 :     CKeyID keyid = pubkey.GetID();
     264                 :       32358 :     const auto it = sigdata.signatures.find(keyid);
     265         [ +  + ]:       32358 :     if (it != sigdata.signatures.end()) {
     266                 :         572 :         sig_out = it->second.second;
     267                 :         572 :         return true;
     268                 :             :     }
     269         [ +  - ]:       31786 :     KeyOriginInfo info;
     270   [ +  -  +  + ]:       31786 :     if (provider.GetKeyOrigin(keyid, info)) {
     271         [ +  - ]:       23168 :         sigdata.misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));
     272                 :             :     }
     273   [ +  -  +  + ]:       31786 :     if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {
     274   [ +  -  +  - ]:       32776 :         auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out));
     275         [ -  + ]:       16388 :         assert(i.second);
     276                 :             :         return true;
     277                 :             :     }
     278                 :             :     // Could not make signature or signature not found, add keyid to missing
     279         [ +  - ]:       15398 :     sigdata.missing_sigs.push_back(keyid);
     280                 :             :     return false;
     281                 :       31786 : }
     282                 :             : 
     283                 :      120308 : static bool SignMuSig2(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const XOnlyPubKey& script_pubkey, const uint256* merkle_root, const uint256* leaf_hash, SigVersion sigversion)
     284                 :             : {
     285         [ -  + ]:      120308 :     Assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
     286                 :             : 
     287                 :             :     // Lookup derivation paths for the script pubkey
     288                 :      120308 :     KeyOriginInfo agg_info;
     289                 :      120308 :     auto misc_pk_it = sigdata.taproot_misc_pubkeys.find(script_pubkey);
     290         [ +  + ]:      120308 :     if (misc_pk_it != sigdata.taproot_misc_pubkeys.end()) {
     291         [ +  - ]:      109576 :         agg_info = misc_pk_it->second.second;
     292                 :             :     }
     293                 :             : 
     294   [ -  +  +  + ]:      131906 :     for (const auto& [agg_pub, part_pks] : sigdata.musig2_pubkeys) {
     295         [ -  + ]:       11598 :         if (part_pks.empty()) continue;
     296                 :             : 
     297                 :             :         // Fill participant derivation path info
     298         [ +  + ]:       43216 :         for (const auto& part_pk : part_pks) {
     299         [ +  - ]:       31618 :             KeyOriginInfo part_info;
     300   [ +  -  +  -  :       31618 :             if (provider.GetKeyOrigin(part_pk.GetID(), part_info)) {
                   +  + ]
     301                 :        6406 :                 XOnlyPubKey xonly_part(part_pk);
     302                 :        6406 :                 auto it = sigdata.taproot_misc_pubkeys.find(xonly_part);
     303         [ +  + ]:        6406 :                 if (it == sigdata.taproot_misc_pubkeys.end()) {
     304   [ +  -  +  - ]:         133 :                     it = sigdata.taproot_misc_pubkeys.emplace(xonly_part, std::make_pair(std::set<uint256>(), part_info)).first;
     305                 :             :                 }
     306   [ +  +  +  - ]:        6406 :                 if (leaf_hash) it->second.first.insert(*leaf_hash);
     307                 :             :             }
     308                 :       31618 :         }
     309                 :             : 
     310                 :             :         // The pubkey in the script may not be the actual aggregate of the participants, but derived from it.
     311                 :             :         // Check the derivation, and compute the BIP 32 derivation tweaks
     312                 :       11598 :         std::vector<std::pair<uint256, bool>> tweaks;
     313                 :       11598 :         CPubKey plain_pub = agg_pub;
     314         [ +  + ]:       11598 :         if (XOnlyPubKey(agg_pub) != script_pubkey) {
     315         [ +  + ]:       10406 :             if (agg_info.path.empty()) continue;
     316   [ +  -  +  + ]:        4860 :             if (agg_info.fingerprint != agg_pub.GetID().fingerprint()) {
     317                 :        2284 :                 continue;
     318                 :             :             }
     319                 :             :             // Get the BIP32 derivation tweaks
     320         [ +  - ]:        2576 :             CExtPubKey extpub = CreateMuSig2SyntheticXpub(agg_pub);
     321         [ +  + ]:        7728 :             for (const int i : agg_info.path) {
     322   [ +  -  +  - ]:        5152 :                 auto& [t, xonly] = tweaks.emplace_back();
     323                 :        5152 :                 xonly = false;
     324   [ +  -  -  + ]:        5152 :                 if (!extpub.Derive(extpub, i, &t)) {
     325                 :           0 :                     return false;
     326                 :             :                 }
     327                 :             :             }
     328         [ -  + ]:        2576 :             Assert(XOnlyPubKey(extpub.pubkey) == script_pubkey);
     329                 :        2576 :             plain_pub = extpub.pubkey;
     330                 :        2576 :         }
     331                 :             : 
     332                 :             :         // Add the merkle root tweak
     333         [ +  + ]:        3768 :         if (sigversion == SigVersion::TAPROOT && merkle_root) {
     334   [ +  +  +  -  :        2052 :             tweaks.emplace_back(script_pubkey.ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root), true);
                   +  - ]
     335   [ +  +  +  - ]:        1134 :             std::optional<std::pair<XOnlyPubKey, bool>> tweaked = script_pubkey.CreateTapTweak(merkle_root->IsNull() ? nullptr : merkle_root);
     336         [ +  - ]:         918 :             if (!Assume(tweaked)) return false;
     337   [ +  -  +  + ]:        1836 :             plain_pub = tweaked->first.GetCPubKeys().at(tweaked->second ? 1 : 0);
     338                 :             :         }
     339                 :             : 
     340                 :             :         // First try to aggregate
     341   [ +  -  +  + ]:        3768 :         if (creator.CreateMuSig2AggregateSig(part_pks, sig_out, agg_pub, plain_pub, leaf_hash, tweaks, sigversion, sigdata)) {
     342         [ +  + ]:          69 :             if (sigversion == SigVersion::TAPROOT) {
     343         [ +  - ]:          30 :                 sigdata.taproot_key_path_sig = sig_out;
     344                 :             :             } else {
     345         [ +  - ]:          39 :                 auto lookup_key = std::make_pair(script_pubkey, leaf_hash ? *leaf_hash : uint256());
     346   [ +  -  +  - ]:          39 :                 sigdata.taproot_script_sigs[lookup_key] = sig_out;
     347                 :             :             }
     348                 :          69 :             continue;
     349                 :          69 :         }
     350                 :             :         // Cannot aggregate, try making partial sigs for every participant
     351         [ +  + ]:        3699 :         auto pub_key_leaf_hash = std::make_pair(plain_pub, leaf_hash ? *leaf_hash : uint256());
     352         [ +  + ]:       14003 :         for (const CPubKey& part_pk : part_pks) {
     353                 :       10304 :             uint256 partial_sig;
     354   [ +  -  +  +  :       10444 :             if (creator.CreateMuSig2PartialSig(provider, partial_sig, agg_pub, plain_pub, part_pk, leaf_hash, tweaks, sigversion, sigdata) && Assume(!partial_sig.IsNull())) {
                   +  - ]
     355   [ +  -  +  - ]:         140 :                 sigdata.musig2_partial_sigs[pub_key_leaf_hash].emplace(part_pk, partial_sig);
     356                 :             :             }
     357                 :             :         }
     358                 :             :         // If there are any partial signatures, continue with next aggregate pubkey
     359                 :        3699 :         auto partial_sigs_it = sigdata.musig2_partial_sigs.find(pub_key_leaf_hash);
     360   [ +  +  -  + ]:        3699 :         if (partial_sigs_it != sigdata.musig2_partial_sigs.end() && !partial_sigs_it->second.empty()) {
     361                 :         822 :             continue;
     362                 :             :         }
     363                 :             :         // No partial sigs, try to make pubnonces
     364         [ +  - ]:        2877 :         std::map<CPubKey, std::vector<uint8_t>>& pubnonces = sigdata.musig2_pubnonces[pub_key_leaf_hash];
     365         [ +  + ]:       10835 :         for (const CPubKey& part_pk : part_pks) {
     366         [ +  + ]:        7958 :             if (pubnonces.contains(part_pk)) continue;
     367         [ +  - ]:        4932 :             std::vector<uint8_t> pubnonce = creator.CreateMuSig2Nonce(provider, agg_pub, plain_pub, part_pk, leaf_hash, merkle_root, sigversion, sigdata);
     368         [ +  + ]:        4932 :             if (pubnonce.empty()) continue;
     369         [ +  - ]:         151 :             pubnonces[part_pk] = std::move(pubnonce);
     370                 :        4932 :         }
     371                 :       11598 :     }
     372                 :             :     return true;
     373                 :      120308 : }
     374                 :             : 
     375                 :      105997 : static bool CreateTaprootScriptSig(const BaseSignatureCreator& creator, SignatureData& sigdata, const SigningProvider& provider, std::vector<unsigned char>& sig_out, const XOnlyPubKey& pubkey, const uint256& leaf_hash, SigVersion sigversion)
     376                 :             : {
     377         [ +  - ]:      105997 :     KeyOriginInfo info;
     378   [ +  -  +  + ]:      105997 :     if (provider.GetKeyOriginByXOnly(pubkey, info)) {
     379                 :       46600 :         auto it = sigdata.taproot_misc_pubkeys.find(pubkey);
     380         [ +  + ]:       46600 :         if (it == sigdata.taproot_misc_pubkeys.end()) {
     381   [ +  -  +  - ]:        1412 :             sigdata.taproot_misc_pubkeys.emplace(pubkey, std::make_pair(std::set<uint256>({leaf_hash}), info));
     382                 :             :         } else {
     383         [ +  - ]:       45894 :             it->second.first.insert(leaf_hash);
     384                 :             :         }
     385                 :             :     }
     386                 :             : 
     387                 :      105997 :     auto lookup_key = std::make_pair(pubkey, leaf_hash);
     388                 :      105997 :     auto it = sigdata.taproot_script_sigs.find(lookup_key);
     389         [ +  + ]:      105997 :     if (it != sigdata.taproot_script_sigs.end()) {
     390         [ +  - ]:         431 :         sig_out = it->second;
     391                 :             :         return true;
     392                 :             :     }
     393                 :             : 
     394   [ +  -  +  + ]:      105566 :     if (creator.CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash, nullptr, sigversion)) {
     395   [ +  -  +  - ]:         464 :         sigdata.taproot_script_sigs[lookup_key] = sig_out;
     396   [ +  -  +  - ]:      105102 :     } else if (!SignMuSig2(creator, sigdata, provider, sig_out, pubkey, /*merkle_root=*/nullptr, &leaf_hash, sigversion)) {
     397                 :             :         return false;
     398                 :             :     }
     399                 :             : 
     400                 :      105566 :     return sigdata.taproot_script_sigs.contains(lookup_key);
     401                 :      105997 : }
     402                 :             : 
     403                 :             : template<typename M, typename K, typename V>
     404                 :          65 : miniscript::Availability MsLookupHelper(const M& map, const K& key, V& value)
     405                 :             : {
     406         [ +  + ]:          65 :     auto it = map.find(key);
     407         [ +  + ]:          65 :     if (it != map.end()) {
     408                 :          32 :         value = it->second;
     409                 :          32 :         return miniscript::Availability::YES;
     410                 :             :     }
     411                 :             :     return miniscript::Availability::NO;
     412                 :             : }
     413                 :             : 
     414                 :             : /**
     415                 :             :  * Context for solving a Miniscript.
     416                 :             :  * If enough material (access to keys, hash preimages, ..) is given, produces a valid satisfaction.
     417                 :             :  */
     418                 :             : template<typename Pk>
     419                 :             : struct Satisfier {
     420                 :             :     using Key = Pk;
     421                 :             : 
     422                 :             :     const SigningProvider& m_provider;
     423                 :             :     SignatureData& m_sig_data;
     424                 :             :     const BaseSignatureCreator& m_creator;
     425                 :             :     const CScript& m_witness_script;
     426                 :             :     //! The context of the script we are satisfying (either P2WSH or Tapscript).
     427                 :             :     const miniscript::MiniscriptContext m_script_ctx;
     428                 :             : 
     429                 :        4390 :     explicit Satisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
     430                 :             :                        const BaseSignatureCreator& creator LIFETIMEBOUND,
     431                 :             :                        const CScript& witscript LIFETIMEBOUND,
     432                 :        4390 :                        miniscript::MiniscriptContext script_ctx) : m_provider(provider),
     433                 :        4390 :                                                                    m_sig_data(sig_data),
     434                 :        4390 :                                                                    m_creator(creator),
     435                 :        4390 :                                                                    m_witness_script(witscript),
     436                 :        4390 :                                                                    m_script_ctx(script_ctx) {}
     437                 :             : 
     438   [ +  +  +  +  :      377017 :     static bool KeyCompare(const Key& a, const Key& b) {
          -  -  -  -  -  
          -  -  -  +  +  
             +  +  +  + ]
     439   [ -  +  +  -  :      378129 :         return a < b;
          -  -  -  -  -  
          -  -  -  +  +  
          +  +  -  -  -  
          -  -  -  -  -  
          +  +  +  +  +  
          -  +  +  +  +  
                   +  + ]
     440                 :             :     }
     441                 :             : 
     442                 :             :     //! Get a CPubKey from a key hash. Note the key hash may be of an xonly pubkey.
     443                 :             :     template<typename I>
     444         [ -  + ]:         381 :     std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
     445         [ -  + ]:         381 :         assert(last - first == 20);
     446                 :         381 :         CPubKey pubkey;
     447                 :         381 :         CKeyID key_id;
     448                 :         381 :         std::copy(first, last, key_id.begin());
     449         [ +  + ]:         381 :         if (GetPubKey(m_provider, m_sig_data, key_id, pubkey)) return pubkey;
     450                 :           1 :         m_sig_data.missing_pubkeys.push_back(key_id);
     451                 :           1 :         return {};
     452                 :             :     }
     453                 :             : 
     454                 :             :     //! Conversion to raw public key.
     455                 :         380 :     std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
     456                 :             : 
     457                 :             :     //! Time lock satisfactions.
     458                 :         989 :     bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
     459                 :         100 :     bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
     460                 :             : 
     461                 :             :     //! Hash preimage satisfactions.
     462                 :          17 :     miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
     463   [ +  -  -  - ]:          17 :         return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage);
     464                 :             :     }
     465                 :          12 :     miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
     466   [ +  -  -  - ]:          12 :         return MsLookupHelper(m_sig_data.ripemd160_preimages, hash, preimage);
     467                 :             :     }
     468                 :          24 :     miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
     469   [ +  -  +  - ]:          24 :         return MsLookupHelper(m_sig_data.hash256_preimages, hash, preimage);
     470                 :             :     }
     471                 :          12 :     miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
     472   [ +  -  -  - ]:          12 :         return MsLookupHelper(m_sig_data.hash160_preimages, hash, preimage);
     473                 :             :     }
     474                 :             : 
     475                 :      677593 :     miniscript::MiniscriptContext MsContext() const {
     476   [ -  -  +  -  :      677593 :         return m_script_ctx;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
          +  -  +  -  +  
          -  +  -  +  -  
          -  -  +  -  +  
          -  +  -  -  -  
          -  -  +  -  +  
          -  +  -  +  -  
          -  -  -  -  +  
          -  +  -  +  -  
          +  -  -  -  -  
          -  +  -  -  -  
          -  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          -  +  -  +  -  
          +  -  +  -  -  
          -  -  -  -  -  
             +  -  -  - ]
     477                 :             :     }
     478                 :             : };
     479                 :             : 
     480                 :             : /** Miniscript satisfier specific to P2WSH context. */
     481                 :             : struct WshSatisfier: Satisfier<CPubKey> {
     482                 :         222 :     explicit WshSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
     483                 :             :                           const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& witscript LIFETIMEBOUND)
     484                 :         222 :                           : Satisfier(provider, sig_data, creator, witscript, miniscript::MiniscriptContext::P2WSH) {}
     485                 :             : 
     486                 :             :     //! Conversion from a raw compressed public key.
     487                 :             :     template <typename I>
     488                 :         495 :     std::optional<CPubKey> FromPKBytes(I first, I last) const {
     489         [ +  + ]:         495 :         CPubKey pubkey{first, last};
     490         [ +  + ]:         495 :         if (pubkey.IsValid()) return pubkey;
     491                 :           1 :         return {};
     492                 :             :     }
     493                 :             : 
     494                 :             :     //! Conversion from a raw compressed public key hash.
     495                 :             :     template<typename I>
     496                 :          77 :     std::optional<CPubKey> FromPKHBytes(I first, I last) const {
     497         [ +  - ]:          77 :         return Satisfier::CPubFromPKHBytes(first, last);
     498                 :             :     }
     499                 :             : 
     500                 :             :     //! Satisfy an ECDSA signature check.
     501                 :         570 :     miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
     502         [ +  + ]:         570 :         if (CreateSig(m_creator, m_sig_data, m_provider, sig, key, m_witness_script, SigVersion::WITNESS_V0)) {
     503                 :         256 :             return miniscript::Availability::YES;
     504                 :             :         }
     505                 :             :         return miniscript::Availability::NO;
     506                 :             :     }
     507                 :             : };
     508                 :             : 
     509                 :             : /** Miniscript satisfier specific to Tapscript context. */
     510                 :             : struct TapSatisfier: Satisfier<XOnlyPubKey> {
     511                 :             :     const uint256& m_leaf_hash;
     512                 :             : 
     513                 :        4168 :     explicit TapSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
     514                 :             :                           const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& script LIFETIMEBOUND,
     515                 :             :                           const uint256& leaf_hash LIFETIMEBOUND)
     516                 :        4168 :                           : Satisfier(provider, sig_data, creator, script, miniscript::MiniscriptContext::TAPSCRIPT),
     517                 :        4168 :                             m_leaf_hash(leaf_hash) {}
     518                 :             : 
     519                 :             :     //! Conversion from a raw xonly public key.
     520                 :             :     template <typename I>
     521         [ +  + ]:      105694 :     std::optional<XOnlyPubKey> FromPKBytes(I first, I last) const {
     522         [ +  + ]:      105694 :         if (last - first != 32) return {};
     523                 :      105693 :         XOnlyPubKey pubkey;
     524                 :      105693 :         std::copy(first, last, pubkey.begin());
     525                 :      105693 :         return pubkey;
     526                 :             :     }
     527                 :             : 
     528                 :             :     //! Conversion from a raw xonly public key hash.
     529                 :             :     template<typename I>
     530                 :         304 :     std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const {
     531         [ +  - ]:         304 :         if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey};
     532                 :           0 :         return {};
     533                 :             :     }
     534                 :             : 
     535                 :             :     //! Satisfy a BIP340 signature check.
     536                 :      105997 :     miniscript::Availability Sign(const XOnlyPubKey& key, std::vector<unsigned char>& sig) const {
     537         [ +  + ]:      105997 :         if (CreateTaprootScriptSig(m_creator, m_sig_data, m_provider, sig, key, m_leaf_hash, SigVersion::TAPSCRIPT)) {
     538                 :         934 :             return miniscript::Availability::YES;
     539                 :             :         }
     540                 :             :         return miniscript::Availability::NO;
     541                 :             :     }
     542                 :             : };
     543                 :             : 
     544                 :        4168 : static bool SignTaprootScript(const SigningProvider& provider, const BaseSignatureCreator& creator, SignatureData& sigdata, int leaf_version, std::span<const unsigned char> script_bytes, std::vector<valtype>& result)
     545                 :             : {
     546                 :             :     // Only BIP342 tapscript signing is supported for now.
     547         [ +  - ]:        4168 :     if (leaf_version != TAPROOT_LEAF_TAPSCRIPT) return false;
     548                 :             : 
     549                 :        4168 :     uint256 leaf_hash = ComputeTapleafHash(leaf_version, script_bytes);
     550                 :        4168 :     CScript script = CScript(script_bytes.begin(), script_bytes.end());
     551                 :             : 
     552                 :        4168 :     TapSatisfier ms_satisfier{provider, sigdata, creator, script, leaf_hash};
     553         [ +  - ]:        4168 :     const auto ms = miniscript::FromScript(script, ms_satisfier);
     554   [ +  +  +  -  :        7692 :     return ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
                   +  + ]
     555                 :        4168 : }
     556                 :             : 
     557                 :        8422 : static bool SignTaproot(const SigningProvider& provider, const BaseSignatureCreator& creator, const WitnessV1Taproot& output, SignatureData& sigdata, std::vector<valtype>& result)
     558                 :             : {
     559         [ +  - ]:        8422 :     TaprootSpendData spenddata;
     560         [ +  - ]:        8422 :     TaprootBuilder builder;
     561                 :             : 
     562                 :             :     // Gather information about this output.
     563   [ +  -  +  + ]:        8422 :     if (provider.GetTaprootSpendData(output, spenddata)) {
     564   [ +  -  +  - ]:        3032 :         sigdata.tr_spenddata.Merge(spenddata);
     565                 :             :     }
     566   [ +  -  +  + ]:        8422 :     if (provider.GetTaprootBuilder(output, builder)) {
     567         [ +  - ]:        1516 :         sigdata.tr_builder = builder;
     568                 :             :     }
     569   [ +  -  +  + ]:        8422 :     if (auto agg_keys = provider.GetAllMuSig2ParticipantPubkeys(); !agg_keys.empty()) {
     570         [ +  - ]:        8422 :         sigdata.musig2_pubkeys.insert(agg_keys.begin(), agg_keys.end());
     571                 :           0 :     }
     572                 :             : 
     573                 :             : 
     574                 :             :     // Try key path spending.
     575                 :        8422 :     {
     576         [ +  - ]:        8422 :         KeyOriginInfo internal_key_info;
     577   [ +  -  +  + ]:        8422 :         if (provider.GetKeyOriginByXOnly(sigdata.tr_spenddata.internal_key, internal_key_info)) {
     578                 :        1562 :             auto it = sigdata.taproot_misc_pubkeys.find(sigdata.tr_spenddata.internal_key);
     579         [ +  + ]:        1562 :             if (it == sigdata.taproot_misc_pubkeys.end()) {
     580   [ +  -  +  - ]:         844 :                 sigdata.taproot_misc_pubkeys.emplace(sigdata.tr_spenddata.internal_key, std::make_pair(std::set<uint256>(), internal_key_info));
     581                 :             :             }
     582                 :             :         }
     583                 :             : 
     584         [ +  - ]:        8422 :         KeyOriginInfo output_key_info;
     585   [ +  -  +  + ]:        8422 :         if (provider.GetKeyOriginByXOnly(output, output_key_info)) {
     586                 :         141 :             auto it = sigdata.taproot_misc_pubkeys.find(output);
     587         [ +  + ]:         141 :             if (it == sigdata.taproot_misc_pubkeys.end()) {
     588   [ +  -  +  - ]:          45 :                 sigdata.taproot_misc_pubkeys.emplace(output, std::make_pair(std::set<uint256>(), output_key_info));
     589                 :             :             }
     590                 :             :         }
     591                 :             : 
     592                 :       24240 :         auto make_keypath_sig = [&](const XOnlyPubKey& pk, const uint256* merkle_root) {
     593                 :       15818 :             std::vector<unsigned char> sig;
     594   [ +  -  +  + ]:       15818 :             if (creator.CreateSchnorrSig(provider, sig, pk, nullptr, merkle_root, SigVersion::TAPROOT)) {
     595         [ +  - ]:         612 :                 sigdata.taproot_key_path_sig = sig;
     596                 :             :             } else {
     597         [ +  - ]:       15206 :                 SignMuSig2(creator, sigdata, provider, sig, pk, merkle_root, /*leaf_hash=*/nullptr, SigVersion::TAPROOT);
     598                 :             :             }
     599                 :       15818 :         };
     600                 :             : 
     601                 :             :         // First try signing with internal key
     602   [ -  +  +  + ]:        8422 :         if (sigdata.taproot_key_path_sig.size() == 0) {
     603         [ +  - ]:        8205 :             make_keypath_sig(sigdata.tr_spenddata.internal_key, &sigdata.tr_spenddata.merkle_root);
     604                 :             :         }
     605                 :             :         // Try signing with output key if still no signature
     606   [ -  +  +  + ]:        8422 :         if (sigdata.taproot_key_path_sig.size() == 0) {
     607         [ +  - ]:        7613 :             make_keypath_sig(output, nullptr);
     608                 :             :         }
     609   [ -  +  +  + ]:        8422 :         if (sigdata.taproot_key_path_sig.size()) {
     610         [ +  - ]:        1718 :             result = Vector(sigdata.taproot_key_path_sig);
     611                 :         859 :             return true;
     612                 :             :         }
     613                 :        8422 :     }
     614                 :             : 
     615                 :             :     // Try script path spending.
     616                 :        7563 :     std::vector<std::vector<unsigned char>> smallest_result_stack;
     617   [ -  +  +  + ]:       11731 :     for (const auto& [key, control_blocks] : sigdata.tr_spenddata.scripts) {
     618                 :        4168 :         const auto& [script, leaf_ver] = key;
     619                 :        4168 :         std::vector<std::vector<unsigned char>> result_stack;
     620   [ -  +  +  -  :        4168 :         if (SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
                   +  + ]
     621         [ +  - ]:         643 :             result_stack.emplace_back(std::begin(script), std::end(script)); // Push the script
     622         [ +  - ]:         643 :             result_stack.push_back(*control_blocks.begin()); // Push the smallest control block
     623   [ -  +  +  +  :         663 :             if (smallest_result_stack.size() == 0 ||
                   +  + ]
     624                 :          20 :                 GetSerializeSize(result_stack) < GetSerializeSize(smallest_result_stack)) {
     625                 :         634 :                 smallest_result_stack = std::move(result_stack);
     626                 :             :             }
     627                 :             :         }
     628                 :        4168 :     }
     629   [ -  +  +  + ]:        7563 :     if (smallest_result_stack.size() != 0) {
     630                 :         623 :         result = std::move(smallest_result_stack);
     631                 :         623 :         return true;
     632                 :             :     }
     633                 :             : 
     634                 :             :     return false;
     635                 :       15985 : }
     636                 :             : 
     637                 :             : /**
     638                 :             :  * Sign scriptPubKey using signature made with creator.
     639                 :             :  * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
     640                 :             :  * unless whichTypeRet is TxoutType::SCRIPTHASH, in which case scriptSigRet is the redemption script.
     641                 :             :  * Returns false if scriptPubKey could not be completely satisfied.
     642                 :             :  */
     643                 :      117154 : static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey,
     644                 :             :                      std::vector<valtype>& ret, TxoutType& whichTypeRet, SigVersion sigversion, SignatureData& sigdata)
     645                 :             : {
     646                 :      117154 :     CScript scriptRet;
     647                 :      117154 :     ret.clear();
     648                 :      117154 :     std::vector<unsigned char> sig;
     649                 :             : 
     650                 :      117154 :     std::vector<valtype> vSolutions;
     651         [ +  - ]:      117154 :     whichTypeRet = Solver(scriptPubKey, vSolutions);
     652                 :             : 
     653   [ +  +  +  +  :      117154 :     switch (whichTypeRet) {
          +  +  +  +  -  
                      + ]
     654                 :             :     case TxoutType::NONSTANDARD:
     655                 :             :     case TxoutType::NULL_DATA:
     656                 :             :     case TxoutType::WITNESS_UNKNOWN:
     657                 :             :         return false;
     658                 :         244 :     case TxoutType::PUBKEY:
     659   [ -  +  +  -  :         244 :         if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false;
                   +  + ]
     660         [ +  - ]:         177 :         ret.push_back(std::move(sig));
     661                 :             :         return true;
     662                 :       59866 :     case TxoutType::PUBKEYHASH: {
     663   [ -  +  +  - ]:       59866 :         CKeyID keyID = CKeyID(uint160(vSolutions[0]));
     664         [ +  - ]:       59866 :         CPubKey pubkey;
     665   [ +  -  +  + ]:       59866 :         if (!GetPubKey(provider, sigdata, keyID, pubkey)) {
     666                 :             :             // Pubkey could not be found, add to missing
     667         [ +  - ]:       30486 :             sigdata.missing_pubkeys.push_back(keyID);
     668                 :             :             return false;
     669                 :             :         }
     670   [ +  -  +  + ]:       29380 :         if (!CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) return false;
     671         [ +  - ]:       15250 :         ret.push_back(std::move(sig));
     672         [ +  - ]:       30500 :         ret.push_back(ToByteVector(pubkey));
     673                 :       15250 :         return true;
     674                 :             :     }
     675                 :        6763 :     case TxoutType::SCRIPTHASH: {
     676         [ -  + ]:        6763 :         uint160 h160{vSolutions[0]};
     677   [ +  -  +  + ]:        6763 :         if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {
     678   [ +  +  +  - ]:        5574 :             ret.emplace_back(scriptRet.begin(), scriptRet.end());
     679                 :             :             return true;
     680                 :             :         }
     681                 :             :         // Could not find redeemScript, add to missing
     682                 :        1298 :         sigdata.missing_redeem_script = h160;
     683                 :        1298 :         return false;
     684                 :             :     }
     685                 :         505 :     case TxoutType::MULTISIG: {
     686         [ +  - ]:         505 :         size_t required = vSolutions.front()[0];
     687         [ +  - ]:         505 :         ret.emplace_back(); // workaround CHECKMULTISIG bug
     688   [ -  +  +  + ]:        2669 :         for (size_t i = 1; i < vSolutions.size() - 1; ++i) {
     689         [ -  + ]:        2164 :             CPubKey pubkey = CPubKey(vSolutions[i]);
     690                 :             :             // We need to always call CreateSig in order to fill sigdata with all
     691                 :             :             // possible signatures that we can create. This will allow further PSBT
     692                 :             :             // processing to work as it needs all possible signature and pubkey pairs
     693   [ +  -  +  + ]:        2164 :             if (CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {
     694   [ -  +  +  + ]:        1277 :                 if (ret.size() < required + 1) {
     695         [ +  - ]:        2164 :                     ret.push_back(std::move(sig));
     696                 :             :                 }
     697                 :             :             }
     698                 :             :         }
     699         [ -  + ]:         505 :         bool ok = ret.size() == required + 1;
     700   [ -  +  +  + ]:         874 :         for (size_t i = 0; i + ret.size() < required + 1; ++i) {
     701         [ +  - ]:         369 :             ret.emplace_back();
     702                 :             :         }
     703                 :             :         return ok;
     704                 :             :     }
     705                 :       40078 :     case TxoutType::WITNESS_V0_KEYHASH:
     706         [ +  - ]:       40078 :         ret.push_back(vSolutions[0]);
     707                 :             :         return true;
     708                 :             : 
     709                 :        1083 :     case TxoutType::WITNESS_V0_SCRIPTHASH:
     710   [ -  +  +  -  :        1083 :         if (GetCScript(provider, sigdata, CScriptID{RIPEMD160(vSolutions[0])}, scriptRet)) {
             +  -  +  + ]
     711   [ +  +  +  - ]:        1415 :             ret.emplace_back(scriptRet.begin(), scriptRet.end());
     712                 :             :             return true;
     713                 :             :         }
     714                 :             :         // Could not find witnessScript, add to missing
     715         [ -  + ]:         226 :         sigdata.missing_witness_script = uint256(vSolutions[0]);
     716                 :         226 :         return false;
     717                 :             : 
     718                 :        8422 :     case TxoutType::WITNESS_V1_TAPROOT:
     719   [ -  +  +  - ]:        8422 :         return SignTaproot(provider, creator, WitnessV1Taproot(XOnlyPubKey{vSolutions[0]}), sigdata, ret);
     720                 :             : 
     721                 :           1 :     case TxoutType::ANCHOR:
     722                 :           1 :         return true;
     723                 :             :     } // no default case, so the compiler can warn about missing cases
     724                 :           0 :     assert(false);
     725                 :      117154 : }
     726                 :             : 
     727                 :       70979 : static CScript PushAll(const std::vector<valtype>& values)
     728                 :             : {
     729                 :       70979 :     CScript result;
     730         [ +  + ]:       88316 :     for (const valtype& v : values) {
     731   [ -  +  +  + ]:       17337 :         if (v.size() == 0) {
     732         [ +  - ]:         245 :             result << OP_0;
     733   [ -  +  -  -  :       17092 :         } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
                   -  - ]
     734         [ #  # ]:           0 :             result << CScript::EncodeOP_N(v[0]);
     735   [ -  +  -  - ]:       17092 :         } else if (v.size() == 1 && v[0] == 0x81) {
     736         [ #  # ]:           0 :             result << OP_1NEGATE;
     737                 :             :         } else {
     738                 :       17092 :             result << v;
     739                 :             :         }
     740                 :             :     }
     741                 :       70979 :     return result;
     742                 :           0 : }
     743                 :             : 
     744                 :       73135 : bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
     745                 :             : {
     746         [ +  + ]:       73135 :     if (sigdata.complete) return true;
     747                 :             : 
     748                 :       70979 :     std::vector<valtype> result;
     749                 :       70979 :     TxoutType whichType;
     750         [ +  - ]:       70979 :     bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);
     751                 :       70979 :     bool P2SH = false;
     752                 :       70979 :     CScript subscript;
     753                 :             : 
     754   [ +  +  +  + ]:       70979 :     if (solved && whichType == TxoutType::SCRIPTHASH)
     755                 :             :     {
     756                 :             :         // Solver returns the subscript that needs to be evaluated;
     757                 :             :         // the final scriptSig is the signatures from that
     758                 :             :         // and then the serialized subscript:
     759                 :        5465 :         subscript = CScript(result[0].begin(), result[0].end());
     760                 :        5465 :         sigdata.redeem_script = subscript;
     761   [ +  -  +  +  :        5465 :         solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;
                   +  - ]
     762                 :             :         P2SH = true;
     763                 :             :     }
     764                 :             : 
     765         [ +  + ]:       47999 :     if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)
     766                 :             :     {
     767                 :       39864 :         CScript witnessscript;
     768   [ +  -  +  -  :       79728 :         witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
          +  -  +  -  +  
                      - ]
     769                 :       39864 :         TxoutType subType;
     770   [ +  -  +  -  :       39864 :         solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
                   +  + ]
     771         [ +  - ]:       39864 :         sigdata.scriptWitness.stack = result;
     772                 :       39864 :         sigdata.witness = true;
     773                 :       39864 :         result.clear();
     774                 :       39864 :     }
     775   [ +  +  +  + ]:       31019 :     else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)
     776                 :             :     {
     777                 :         846 :         CScript witnessscript(result[0].begin(), result[0].end());
     778                 :         846 :         sigdata.witness_script = witnessscript;
     779                 :             : 
     780                 :         846 :         TxoutType subType{TxoutType::NONSTANDARD};
     781   [ +  -  +  +  :         846 :         solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata) && subType != TxoutType::SCRIPTHASH && subType != TxoutType::WITNESS_V0_SCRIPTHASH && subType != TxoutType::WITNESS_V0_KEYHASH;
          +  -  +  +  +  
                      + ]
     782                 :             : 
     783                 :             :         // If we couldn't find a solution with the legacy satisfier, try satisfying the script using Miniscript.
     784                 :             :         // Note we need to check if the result stack is empty before, because it might be used even if the Script
     785                 :             :         // isn't fully solved. For instance the CHECKMULTISIG satisfaction in SignStep() pushes partial signatures
     786                 :             :         // and the extractor relies on this behaviour to combine witnesses.
     787         [ +  + ]:         682 :         if (!solved && result.empty()) {
     788                 :         222 :             WshSatisfier ms_satisfier{provider, sigdata, creator, witnessscript};
     789         [ +  - ]:         222 :             const auto ms = miniscript::FromScript(witnessscript, ms_satisfier);
     790   [ +  +  +  -  :         357 :             solved = ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
                   +  + ]
     791                 :         222 :         }
     792   [ +  +  +  - ]:        1397 :         result.emplace_back(witnessscript.begin(), witnessscript.end());
     793                 :             : 
     794         [ +  - ]:         846 :         sigdata.scriptWitness.stack = result;
     795                 :         846 :         sigdata.witness = true;
     796                 :         846 :         result.clear();
     797   [ +  +  +  - ]:       31115 :     } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
     798                 :        8419 :         sigdata.witness = true;
     799         [ +  + ]:        8419 :         if (solved) {
     800                 :        1479 :             sigdata.scriptWitness.stack = std::move(result);
     801                 :             :         }
     802                 :        8419 :         result.clear();
     803   [ +  +  -  + ]:       21850 :     } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
     804                 :           0 :         sigdata.witness = true;
     805                 :             :     }
     806                 :             : 
     807         [ +  + ]:       70979 :     if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
     808         [ +  + ]:       70979 :     if (P2SH) {
     809   [ +  +  +  - ]:        5574 :         result.emplace_back(subscript.begin(), subscript.end());
     810                 :             :     }
     811         [ +  - ]:       70979 :     sigdata.scriptSig = PushAll(result);
     812                 :             : 
     813                 :             :     // Test solution
     814   [ +  +  +  -  :       70979 :     sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
             +  -  +  + ]
     815                 :       70979 :     return sigdata.complete;
     816                 :       70979 : }
     817                 :             : 
     818                 :             : namespace {
     819                 :       41611 : class SignatureExtractorChecker final : public DeferringSignatureChecker
     820                 :             : {
     821                 :             : private:
     822                 :             :     SignatureData& sigdata;
     823                 :             : 
     824                 :             : public:
     825                 :       41611 :     SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : DeferringSignatureChecker(checker), sigdata(sigdata) {}
     826                 :             : 
     827                 :        3088 :     bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
     828                 :             :     {
     829         [ +  + ]:        3088 :         if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
     830         [ -  + ]:        2308 :             CPubKey pubkey(vchPubKey);
     831   [ +  -  +  - ]:        2308 :             sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));
     832                 :        2308 :             return true;
     833                 :             :         }
     834                 :             :         return false;
     835                 :             :     }
     836                 :             : };
     837                 :             : 
     838                 :       41611 : struct Stacks
     839                 :             : {
     840                 :             :     std::vector<valtype> script;
     841                 :             :     std::vector<valtype> witness;
     842                 :             : 
     843                 :             :     Stacks() = delete;
     844                 :             :     Stacks(const Stacks&) = delete;
     845         [ +  - ]:       41611 :     explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
     846         [ +  - ]:       41611 :         EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
     847                 :       41611 :     }
     848                 :             : };
     849                 :             : }
     850                 :             : 
     851                 :             : // Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead
     852                 :       41611 : SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout)
     853                 :             : {
     854                 :       41611 :     SignatureData data;
     855   [ -  +  -  + ]:       41611 :     assert(tx.vin.size() > nIn);
     856                 :       41611 :     data.scriptSig = tx.vin[nIn].scriptSig;
     857         [ +  - ]:       41611 :     data.scriptWitness = tx.vin[nIn].scriptWitness;
     858         [ +  - ]:       41611 :     Stacks stack(data);
     859                 :             : 
     860                 :             :     // Get signatures
     861         [ +  - ]:       41611 :     MutableTransactionSignatureChecker tx_checker(&tx, nIn, txout.nValue, MissingDataBehavior::FAIL);
     862         [ +  - ]:       41611 :     SignatureExtractorChecker extractor_checker(data, tx_checker);
     863   [ +  -  +  + ]:       41611 :     if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {
     864                 :        2153 :         data.complete = true;
     865                 :        2153 :         return data;
     866                 :             :     }
     867                 :             : 
     868                 :             :     // Get scripts
     869                 :       39458 :     std::vector<std::vector<unsigned char>> solutions;
     870         [ +  - ]:       39458 :     TxoutType script_type = Solver(txout.scriptPubKey, solutions);
     871                 :       39458 :     SigVersion sigversion = SigVersion::BASE;
     872                 :       39458 :     CScript next_script = txout.scriptPubKey;
     873                 :             : 
     874   [ +  +  +  +  :       39458 :     if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) {
                   +  - ]
     875                 :             :         // Get the redeemScript
     876                 :          30 :         CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
     877                 :          30 :         data.redeem_script = redeem_script;
     878                 :          30 :         next_script = std::move(redeem_script);
     879                 :             : 
     880                 :             :         // Get redeemScript type
     881         [ +  - ]:          30 :         script_type = Solver(next_script, solutions);
     882                 :          30 :         stack.script.pop_back();
     883                 :          30 :     }
     884   [ +  +  +  +  :       39458 :     if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {
                   +  - ]
     885                 :             :         // Get the witnessScript
     886                 :          45 :         CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
     887                 :          45 :         data.witness_script = witness_script;
     888                 :          45 :         next_script = std::move(witness_script);
     889                 :             : 
     890                 :             :         // Get witnessScript type
     891         [ +  - ]:          45 :         script_type = Solver(next_script, solutions);
     892                 :          45 :         stack.witness.pop_back();
     893                 :          45 :         stack.script = std::move(stack.witness);
     894                 :          45 :         stack.witness.clear();
     895                 :          45 :         sigversion = SigVersion::WITNESS_V0;
     896                 :          45 :     }
     897   [ +  +  +  - ]:       39458 :     if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {
     898                 :             :         // Build a map of pubkey -> signature by matching sigs to pubkeys:
     899   [ -  +  -  + ]:          61 :         assert(solutions.size() > 1);
     900                 :          61 :         unsigned int num_pubkeys = solutions.size()-2;
     901                 :          61 :         unsigned int last_success_key = 0;
     902         [ +  + ]:         385 :         for (const valtype& sig : stack.script) {
     903         [ +  + ]:         988 :             for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {
     904         [ -  + ]:         822 :                 const valtype& pubkey = solutions[i+1];
     905                 :             :                 // We either have a signature for this pubkey, or we have found a signature and it is valid
     906   [ -  +  +  -  :         822 :                 if (data.signatures.contains(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
          +  -  +  -  +  
                      + ]
     907                 :             :                     last_success_key = i + 1;
     908                 :             :                     break;
     909                 :             :                 }
     910                 :             :             }
     911                 :             :         }
     912                 :             :     }
     913                 :             : 
     914                 :       39458 :     return data;
     915                 :       83222 : }
     916                 :             : 
     917                 :       46193 : void UpdateInput(CTxIn& input, const SignatureData& data)
     918                 :             : {
     919                 :       46193 :     input.scriptSig = data.scriptSig;
     920                 :       46193 :     input.scriptWitness = data.scriptWitness;
     921                 :       46193 : }
     922                 :             : 
     923                 :          82 : void SignatureData::MergeSignatureData(SignatureData sigdata)
     924                 :             : {
     925         [ +  + ]:          82 :     if (complete) return;
     926         [ +  + ]:          77 :     if (sigdata.complete) {
     927                 :           8 :         *this = std::move(sigdata);
     928                 :           8 :         return;
     929                 :             :     }
     930   [ +  +  +  +  :          82 :     if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
             +  +  +  + ]
     931                 :          13 :         redeem_script = sigdata.redeem_script;
     932                 :             :     }
     933   [ +  +  +  +  :         103 :     if (witness_script.empty() && !sigdata.witness_script.empty()) {
             +  +  +  + ]
     934                 :          16 :         witness_script = sigdata.witness_script;
     935                 :             :     }
     936                 :          69 :     signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end()));
     937                 :             : }
     938                 :             : 
     939                 :             : namespace {
     940                 :             : /** Dummy signature checker which accepts all signatures. */
     941                 :             : class DummySignatureChecker final : public BaseSignatureChecker
     942                 :             : {
     943                 :             : public:
     944                 :             :     DummySignatureChecker() = default;
     945         [ -  + ]:           8 :     bool CheckECDSASignature(const std::vector<unsigned char>& sig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override { return sig.size() != 0; }
     946                 :           0 :     bool CheckSchnorrSignature(std::span<const unsigned char> sig, std::span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const override { return sig.size() != 0; }
     947                 :           0 :     bool CheckLockTime(const CScriptNum& nLockTime) const override { return true; }
     948                 :           0 :     bool CheckSequence(const CScriptNum& nSequence) const override { return true; }
     949                 :             : };
     950                 :             : }
     951                 :             : 
     952                 :             : const BaseSignatureChecker& DUMMY_CHECKER = DummySignatureChecker();
     953                 :             : 
     954                 :             : namespace {
     955                 :             : class DummySignatureCreator final : public BaseSignatureCreator {
     956                 :             : private:
     957                 :             :     char m_r_len = 32;
     958                 :             :     char m_s_len = 32;
     959                 :             : public:
     960                 :             :     DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {}
     961                 :           7 :     const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; }
     962                 :           4 :     bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override
     963                 :             :     {
     964                 :             :         // Create a dummy signature that is a valid DER-encoding
     965                 :           4 :         vchSig.assign(m_r_len + m_s_len + 7, '\000');
     966                 :           4 :         vchSig[0] = 0x30;
     967                 :           4 :         vchSig[1] = m_r_len + m_s_len + 4;
     968                 :           4 :         vchSig[2] = 0x02;
     969                 :           4 :         vchSig[3] = m_r_len;
     970                 :           4 :         vchSig[4] = 0x01;
     971                 :           4 :         vchSig[4 + m_r_len] = 0x02;
     972                 :           4 :         vchSig[5 + m_r_len] = m_s_len;
     973                 :           4 :         vchSig[6 + m_r_len] = 0x01;
     974                 :           4 :         vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL;
     975                 :           4 :         return true;
     976                 :             :     }
     977                 :           3 :     bool CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* tweak, SigVersion sigversion) const override
     978                 :             :     {
     979                 :           3 :         sig.assign(64, '\000');
     980                 :           3 :         return true;
     981                 :             :     }
     982                 :           0 :     std::vector<uint8_t> CreateMuSig2Nonce(const SigningProvider& provider, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const uint256* merkle_root, SigVersion sigversion, const SignatureData& sigdata) const override
     983                 :             :     {
     984                 :           0 :         std::vector<uint8_t> out;
     985         [ #  # ]:           0 :         out.assign(MUSIG2_PUBNONCE_SIZE, '\000');
     986                 :           0 :         return out;
     987                 :           0 :     }
     988                 :           0 :     bool CreateMuSig2PartialSig(const SigningProvider& provider, uint256& partial_sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const CPubKey& part_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const override
     989                 :             :     {
     990                 :           0 :         partial_sig = uint256::ONE;
     991                 :           0 :         return true;
     992                 :             :     }
     993                 :           0 :     bool CreateMuSig2AggregateSig(const std::vector<CPubKey>& participants, std::vector<uint8_t>& sig, const CPubKey& aggregate_pubkey, const CPubKey& script_pubkey, const uint256* leaf_hash, const std::vector<std::pair<uint256, bool>>& tweaks, SigVersion sigversion, const SignatureData& sigdata) const override
     994                 :             :     {
     995                 :           0 :         sig.assign(64, '\000');
     996                 :           0 :         return true;
     997                 :             :     }
     998                 :             : };
     999                 :             : 
    1000                 :             : }
    1001                 :             : 
    1002                 :             : const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32);
    1003                 :             : const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32);
    1004                 :             : 
    1005                 :           4 : bool IsSegWitOutput(const SigningProvider& provider, const CScript& script)
    1006                 :             : {
    1007                 :           4 :     int version;
    1008                 :           4 :     valtype program;
    1009   [ +  -  -  + ]:           4 :     if (script.IsWitnessProgram(version, program)) return true;
    1010   [ #  #  #  # ]:           0 :     if (script.IsPayToScriptHash()) {
    1011                 :           0 :         std::vector<valtype> solutions;
    1012         [ #  # ]:           0 :         auto whichtype = Solver(script, solutions);
    1013         [ #  # ]:           0 :         if (whichtype == TxoutType::SCRIPTHASH) {
    1014         [ #  # ]:           0 :             auto h160 = uint160(solutions[0]);
    1015                 :           0 :             CScript subscript;
    1016   [ #  #  #  # ]:           0 :             if (provider.GetCScript(CScriptID{h160}, subscript)) {
    1017   [ #  #  #  # ]:           0 :                 if (subscript.IsWitnessProgram(version, program)) return true;
    1018                 :             :             }
    1019                 :           0 :         }
    1020                 :           0 :     }
    1021                 :             :     return false;
    1022                 :           4 : }
    1023                 :             : 
    1024                 :       17187 : bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, const SignOptions& options, std::map<int, bilingual_str>& input_errors)
    1025                 :             : {
    1026                 :       17187 :     bool fHashSingle = ((options.sighash_type & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
    1027                 :             : 
    1028                 :             :     // Use CTransaction for the constant parts of the
    1029                 :             :     // transaction to avoid rehashing.
    1030                 :       17187 :     const CTransaction txConst(mtx);
    1031                 :             : 
    1032                 :       17187 :     PrecomputedTransactionData txdata;
    1033                 :       17187 :     std::vector<CTxOut> spent_outputs;
    1034   [ -  +  +  + ]:       58736 :     for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
    1035                 :       41559 :         CTxIn& txin = mtx.vin[i];
    1036                 :       41559 :         auto coin = coins.find(txin.prevout);
    1037   [ +  -  +  + ]:       41559 :         if (coin == coins.end() || coin->second.IsSpent()) {
    1038         [ +  - ]:          10 :             txdata.Init(txConst, /*spent_outputs=*/{}, /*force=*/true);
    1039                 :          10 :             break;
    1040                 :             :         } else {
    1041         [ +  - ]:       41549 :             spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
    1042                 :             :         }
    1043                 :             :     }
    1044   [ -  +  -  +  :       17187 :     if (spent_outputs.size() == mtx.vin.size()) {
                   +  + ]
    1045         [ +  - ]:       17177 :         txdata.Init(txConst, std::move(spent_outputs), true);
    1046                 :             :     }
    1047                 :             : 
    1048                 :             :     // Sign what we can:
    1049   [ -  +  +  + ]:       58755 :     for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
    1050                 :       41568 :         CTxIn& txin = mtx.vin[i];
    1051                 :       41568 :         auto coin = coins.find(txin.prevout);
    1052   [ +  -  +  + ]:       41568 :         if (coin == coins.end() || coin->second.IsSpent()) {
    1053   [ +  -  +  - ]:          19 :             input_errors[i] = _("Input not found or already spent");
    1054                 :          19 :             continue;
    1055                 :             :         }
    1056         [ +  - ]:       41549 :         const CScript& prevPubKey = coin->second.out.scriptPubKey;
    1057                 :       41549 :         const CAmount& amount = coin->second.out.nValue;
    1058                 :             : 
    1059         [ +  - ]:       83067 :         SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
    1060                 :             :         // Only sign SIGHASH_SINGLE if there's a corresponding output:
    1061   [ -  +  -  -  :       41549 :         if (!fHashSingle || (i < mtx.vout.size())) {
                   -  - ]
    1062   [ +  -  +  - ]:       83098 :             ProduceSignature(*keystore, MutableTransactionSignatureCreator(mtx, i, amount, &txdata, options), prevPubKey, sigdata);
    1063                 :             :         }
    1064                 :             : 
    1065         [ +  - ]:       41549 :         UpdateInput(txin, sigdata);
    1066                 :             : 
    1067                 :             :         // amount must be specified for valid segwit signature
    1068   [ +  +  +  + ]:       41549 :         if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
    1069   [ +  -  +  - ]:          31 :             input_errors[i] = _("Missing amount");
    1070                 :          31 :             continue;
    1071                 :             :         }
    1072                 :             : 
    1073                 :       41518 :         ScriptError serror = SCRIPT_ERR_OK;
    1074   [ +  +  +  -  :       71089 :         if (!sigdata.complete && !VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
             +  +  +  + ]
    1075         [ +  + ]:       29533 :             if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
    1076                 :             :                 // Unable to sign input and verification failed (possible attempt to partially sign).
    1077   [ +  -  +  -  :       21498 :                 input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)");
                   +  - ]
    1078         [ +  + ]:       18784 :             } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {
    1079                 :             :                 // Verification failed (possibly due to insufficient signatures).
    1080   [ +  -  +  -  :         158 :                 input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
                   +  - ]
    1081                 :             :             } else {
    1082   [ +  -  +  -  :       37410 :                 input_errors[i] = Untranslated(ScriptErrorString(serror));
                   +  - ]
    1083                 :             :             }
    1084                 :             :         } else {
    1085                 :             :             // If this input succeeds, make sure there is no error set for it
    1086                 :       11985 :             input_errors.erase(i);
    1087                 :             :         }
    1088                 :       41549 :     }
    1089                 :       17187 :     return input_errors.empty();
    1090                 :       34374 : }
        

Generated by: LCOV version 2.0-1