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

Generated by: LCOV version 2.0-1