LCOV - code coverage report
Current view: top level - src/script - sign.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 89.3 % 460 411
Test Date: 2024-08-28 04:44:32 Functions: 85.7 % 42 36
Branches: 53.7 % 784 421

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2010 Satoshi Nakamoto
       2                 :             : // Copyright (c) 2009-2022 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 <consensus/amount.h>
       9                 :             : #include <key.h>
      10                 :             : #include <policy/policy.h>
      11                 :             : #include <primitives/transaction.h>
      12                 :             : #include <script/keyorigin.h>
      13                 :             : #include <script/miniscript.h>
      14                 :             : #include <script/script.h>
      15                 :             : #include <script/signingprovider.h>
      16                 :             : #include <script/solver.h>
      17                 :             : #include <uint256.h>
      18                 :             : #include <util/translation.h>
      19                 :             : #include <util/vector.h>
      20                 :             : 
      21                 :             : typedef std::vector<unsigned char> valtype;
      22                 :             : 
      23                 :        4640 : MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, int hash_type)
      24                 :        4640 :     : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount}, checker{&m_txto, nIn, amount, MissingDataBehavior::FAIL},
      25                 :        4640 :       m_txdata(nullptr)
      26                 :             : {
      27                 :        4640 : }
      28                 :             : 
      29                 :         500 : MutableTransactionSignatureCreator::MutableTransactionSignatureCreator(const CMutableTransaction& tx, unsigned int input_idx, const CAmount& amount, const PrecomputedTransactionData* txdata, int hash_type)
      30                 :         500 :     : m_txto{tx}, nIn{input_idx}, nHashType{hash_type}, amount{amount},
      31         [ +  - ]:         500 :       checker{txdata ? MutableTransactionSignatureChecker{&m_txto, nIn, amount, *txdata, MissingDataBehavior::FAIL} :
      32                 :             :                        MutableTransactionSignatureChecker{&m_txto, nIn, amount, MissingDataBehavior::FAIL}},
      33         [ +  - ]:         500 :       m_txdata(txdata)
      34                 :             : {
      35                 :         500 : }
      36                 :             : 
      37                 :        5464 : bool MutableTransactionSignatureCreator::CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& address, const CScript& scriptCode, SigVersion sigversion) const
      38                 :             : {
      39         [ -  + ]:        5464 :     assert(sigversion == SigVersion::BASE || sigversion == SigVersion::WITNESS_V0);
      40                 :             : 
      41                 :        5464 :     CKey key;
      42   [ +  -  +  + ]:        5464 :     if (!provider.GetKey(address, key))
      43                 :             :         return false;
      44                 :             : 
      45                 :             :     // Signing with uncompressed keys is disabled in witness scripts
      46   [ +  +  +  + ]:        5302 :     if (sigversion == SigVersion::WITNESS_V0 && !key.IsCompressed())
      47                 :             :         return false;
      48                 :             : 
      49                 :             :     // Signing without known amount does not work in witness scripts.
      50   [ +  +  +  - ]:        5298 :     if (sigversion == SigVersion::WITNESS_V0 && !MoneyRange(amount)) return false;
      51                 :             : 
      52                 :             :     // BASE/WITNESS_V0 signatures don't support explicit SIGHASH_DEFAULT, use SIGHASH_ALL instead.
      53         [ +  + ]:        5298 :     const int hashtype = nHashType == SIGHASH_DEFAULT ? SIGHASH_ALL : nHashType;
      54                 :             : 
      55         [ +  - ]:        5298 :     uint256 hash = SignatureHash(scriptCode, m_txto, nIn, hashtype, amount, sigversion, m_txdata);
      56   [ +  -  +  - ]:        5298 :     if (!key.Sign(hash, vchSig))
      57                 :             :         return false;
      58         [ +  - ]:        5464 :     vchSig.push_back((unsigned char)hashtype);
      59                 :             :     return true;
      60                 :        5464 : }
      61                 :             : 
      62                 :         165 : 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
      63                 :             : {
      64         [ -  + ]:         165 :     assert(sigversion == SigVersion::TAPROOT || sigversion == SigVersion::TAPSCRIPT);
      65                 :             : 
      66                 :         165 :     CKey key;
      67   [ +  -  +  + ]:         165 :     if (!provider.GetKeyByXOnly(pubkey, key)) return false;
      68                 :             : 
      69                 :             :     // BIP341/BIP342 signing needs lots of precomputed transaction data. While some
      70                 :             :     // (non-SIGHASH_DEFAULT) sighash modes exist that can work with just some subset
      71                 :             :     // of data present, for now, only support signing when everything is provided.
      72   [ +  -  +  -  :          79 :     if (!m_txdata || !m_txdata->m_bip341_taproot_ready || !m_txdata->m_spent_outputs_ready) return false;
                   +  - ]
      73                 :             : 
      74         [ +  + ]:          79 :     ScriptExecutionData execdata;
      75                 :          79 :     execdata.m_annex_init = true;
      76                 :          79 :     execdata.m_annex_present = false; // Only support annex-less signing for now.
      77         [ +  + ]:          79 :     if (sigversion == SigVersion::TAPSCRIPT) {
      78                 :          48 :         execdata.m_codeseparator_pos_init = true;
      79                 :          48 :         execdata.m_codeseparator_pos = 0xFFFFFFFF; // Only support non-OP_CODESEPARATOR BIP342 signing for now.
      80         [ +  - ]:          48 :         if (!leaf_hash) return false; // BIP342 signing needs leaf hash.
      81                 :          48 :         execdata.m_tapleaf_hash_init = true;
      82                 :          48 :         execdata.m_tapleaf_hash = *leaf_hash;
      83                 :             :     }
      84                 :          79 :     uint256 hash;
      85   [ +  -  +  - ]:          79 :     if (!SignatureHashSchnorr(hash, execdata, m_txto, nIn, nHashType, sigversion, *m_txdata, MissingDataBehavior::FAIL)) return false;
      86         [ +  - ]:          79 :     sig.resize(64);
      87                 :             :     // Use uint256{} as aux_rnd for now.
      88   [ +  -  +  - ]:          79 :     if (!key.SignSchnorr(hash, sig, merkle_root, {})) return false;
      89   [ +  +  +  - ]:         165 :     if (nHashType) sig.push_back(nHashType);
      90                 :             :     return true;
      91                 :         165 : }
      92                 :             : 
      93                 :         243 : static bool GetCScript(const SigningProvider& provider, const SignatureData& sigdata, const CScriptID& scriptid, CScript& script)
      94                 :             : {
      95         [ +  + ]:         243 :     if (provider.GetCScript(scriptid, script)) {
      96                 :             :         return true;
      97                 :             :     }
      98                 :             :     // Look for scripts in SignatureData
      99         [ +  + ]:          10 :     if (CScriptID(sigdata.redeem_script) == scriptid) {
     100                 :           5 :         script = sigdata.redeem_script;
     101                 :           5 :         return true;
     102         [ +  + ]:           5 :     } else if (CScriptID(sigdata.witness_script) == scriptid) {
     103                 :           3 :         script = sigdata.witness_script;
     104                 :           3 :         return true;
     105                 :             :     }
     106                 :             :     return false;
     107                 :             : }
     108                 :             : 
     109                 :        4710 : static bool GetPubKey(const SigningProvider& provider, const SignatureData& sigdata, const CKeyID& address, CPubKey& pubkey)
     110                 :             : {
     111                 :             :     // Look for pubkey in all partial sigs
     112                 :        4710 :     const auto it = sigdata.signatures.find(address);
     113         [ -  + ]:        4710 :     if (it != sigdata.signatures.end()) {
     114                 :           0 :         pubkey = it->second.first;
     115                 :           0 :         return true;
     116                 :             :     }
     117                 :             :     // Look for pubkey in pubkey lists
     118                 :        4710 :     const auto& pk_it = sigdata.misc_pubkeys.find(address);
     119         [ -  + ]:        4710 :     if (pk_it != sigdata.misc_pubkeys.end()) {
     120                 :           0 :         pubkey = pk_it->second.first;
     121                 :           0 :         return true;
     122                 :             :     }
     123                 :        4710 :     const auto& tap_pk_it = sigdata.tap_pubkeys.find(address);
     124         [ -  + ]:        4710 :     if (tap_pk_it != sigdata.tap_pubkeys.end()) {
     125                 :           0 :         pubkey = tap_pk_it->second.GetEvenCorrespondingCPubKey();
     126                 :           0 :         return true;
     127                 :             :     }
     128                 :             :     // Query the underlying provider
     129                 :        4710 :     return provider.GetPubKey(address, pubkey);
     130                 :             : }
     131                 :             : 
     132                 :        5488 : 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)
     133                 :             : {
     134                 :        5488 :     CKeyID keyid = pubkey.GetID();
     135                 :        5488 :     const auto it = sigdata.signatures.find(keyid);
     136         [ +  + ]:        5488 :     if (it != sigdata.signatures.end()) {
     137                 :          22 :         sig_out = it->second.second;
     138                 :          22 :         return true;
     139                 :             :     }
     140         [ +  - ]:        5466 :     KeyOriginInfo info;
     141   [ +  -  +  + ]:        5466 :     if (provider.GetKeyOrigin(keyid, info)) {
     142         [ +  - ]:        1294 :         sigdata.misc_pubkeys.emplace(keyid, std::make_pair(pubkey, std::move(info)));
     143                 :             :     }
     144   [ +  -  +  + ]:        5466 :     if (creator.CreateSig(provider, sig_out, keyid, scriptcode, sigversion)) {
     145   [ +  -  +  - ]:       10600 :         auto i = sigdata.signatures.emplace(keyid, SigPair(pubkey, sig_out));
     146         [ -  + ]:        5300 :         assert(i.second);
     147                 :             :         return true;
     148                 :             :     }
     149                 :             :     // Could not make signature or signature not found, add keyid to missing
     150         [ +  - ]:         166 :     sigdata.missing_sigs.push_back(keyid);
     151                 :             :     return false;
     152                 :        5466 : }
     153                 :             : 
     154                 :          66 : 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)
     155                 :             : {
     156         [ +  - ]:          66 :     KeyOriginInfo info;
     157   [ +  -  +  - ]:          66 :     if (provider.GetKeyOriginByXOnly(pubkey, info)) {
     158                 :          66 :         auto it = sigdata.taproot_misc_pubkeys.find(pubkey);
     159         [ +  + ]:          66 :         if (it == sigdata.taproot_misc_pubkeys.end()) {
     160   [ +  -  +  - ]:         120 :             sigdata.taproot_misc_pubkeys.emplace(pubkey, std::make_pair(std::set<uint256>({leaf_hash}), info));
     161                 :             :         } else {
     162         [ +  - ]:           6 :             it->second.first.insert(leaf_hash);
     163                 :             :         }
     164                 :             :     }
     165                 :             : 
     166                 :          66 :     auto lookup_key = std::make_pair(pubkey, leaf_hash);
     167                 :          66 :     auto it = sigdata.taproot_script_sigs.find(lookup_key);
     168         [ -  + ]:          66 :     if (it != sigdata.taproot_script_sigs.end()) {
     169         [ #  # ]:           0 :         sig_out = it->second;
     170                 :             :         return true;
     171                 :             :     }
     172   [ +  -  +  + ]:          66 :     if (creator.CreateSchnorrSig(provider, sig_out, pubkey, &leaf_hash, nullptr, sigversion)) {
     173   [ +  -  +  - ]:          48 :         sigdata.taproot_script_sigs[lookup_key] = sig_out;
     174                 :             :         return true;
     175                 :             :     }
     176                 :             :     return false;
     177                 :          66 : }
     178                 :             : 
     179                 :             : template<typename M, typename K, typename V>
     180                 :          60 : miniscript::Availability MsLookupHelper(const M& map, const K& key, V& value)
     181                 :             : {
     182         [ +  + ]:          60 :     auto it = map.find(key);
     183         [ +  + ]:          60 :     if (it != map.end()) {
     184                 :          30 :         value = it->second;
     185                 :          30 :         return miniscript::Availability::YES;
     186                 :             :     }
     187                 :             :     return miniscript::Availability::NO;
     188                 :             : }
     189                 :             : 
     190                 :             : /**
     191                 :             :  * Context for solving a Miniscript.
     192                 :             :  * If enough material (access to keys, hash preimages, ..) is given, produces a valid satisfaction.
     193                 :             :  */
     194                 :             : template<typename Pk>
     195                 :             : struct Satisfier {
     196                 :             :     using Key = Pk;
     197                 :             : 
     198                 :             :     const SigningProvider& m_provider;
     199                 :             :     SignatureData& m_sig_data;
     200                 :             :     const BaseSignatureCreator& m_creator;
     201                 :             :     const CScript& m_witness_script;
     202                 :             :     //! The context of the script we are satisfying (either P2WSH or Tapscript).
     203                 :             :     const miniscript::MiniscriptContext m_script_ctx;
     204                 :             : 
     205                 :         127 :     explicit Satisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
     206                 :             :                        const BaseSignatureCreator& creator LIFETIMEBOUND,
     207                 :             :                        const CScript& witscript LIFETIMEBOUND,
     208                 :         127 :                        miniscript::MiniscriptContext script_ctx) : m_provider(provider),
     209                 :         127 :                                                                    m_sig_data(sig_data),
     210                 :         127 :                                                                    m_creator(creator),
     211                 :         127 :                                                                    m_witness_script(witscript),
     212                 :         127 :                                                                    m_script_ctx(script_ctx) {}
     213                 :             : 
     214   [ +  -  -  +  :          54 :     static bool KeyCompare(const Key& a, const Key& b) {
          -  -  -  -  -  
          -  -  -  -  +  
             +  +  +  - ]
     215   [ -  +  +  -  :         144 :         return a < b;
          -  -  -  -  -  
          -  -  -  +  -  
          -  +  -  -  -  
          -  -  -  -  -  
          -  +  -  +  +  
          -  -  +  +  +  
                   +  - ]
     216                 :             :     }
     217                 :             : 
     218                 :             :     //! Get a CPubKey from a key hash. Note the key hash may be of an xonly pubkey.
     219                 :             :     template<typename I>
     220         [ -  + ]:          18 :     std::optional<CPubKey> CPubFromPKHBytes(I first, I last) const {
     221         [ -  + ]:          18 :         assert(last - first == 20);
     222                 :          18 :         CPubKey pubkey;
     223                 :          18 :         CKeyID key_id;
     224                 :          18 :         std::copy(first, last, key_id.begin());
     225         [ +  - ]:          18 :         if (GetPubKey(m_provider, m_sig_data, key_id, pubkey)) return pubkey;
     226                 :           0 :         m_sig_data.missing_pubkeys.push_back(key_id);
     227                 :           0 :         return {};
     228                 :             :     }
     229                 :             : 
     230                 :             :     //! Conversion to raw public key.
     231                 :          18 :     std::vector<unsigned char> ToPKBytes(const Key& key) const { return {key.begin(), key.end()}; }
     232                 :             : 
     233                 :             :     //! Time lock satisfactions.
     234                 :          18 :     bool CheckAfter(uint32_t value) const { return m_creator.Checker().CheckLockTime(CScriptNum(value)); }
     235                 :          42 :     bool CheckOlder(uint32_t value) const { return m_creator.Checker().CheckSequence(CScriptNum(value)); }
     236                 :             : 
     237                 :             :     //! Hash preimage satisfactions.
     238                 :          12 :     miniscript::Availability SatSHA256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
     239   [ +  -  -  - ]:          12 :         return MsLookupHelper(m_sig_data.sha256_preimages, hash, preimage);
     240                 :             :     }
     241                 :          12 :     miniscript::Availability SatRIPEMD160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
     242   [ +  -  -  - ]:          12 :         return MsLookupHelper(m_sig_data.ripemd160_preimages, hash, preimage);
     243                 :             :     }
     244                 :          24 :     miniscript::Availability SatHASH256(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
     245   [ +  -  +  - ]:          24 :         return MsLookupHelper(m_sig_data.hash256_preimages, hash, preimage);
     246                 :             :     }
     247                 :          12 :     miniscript::Availability SatHASH160(const std::vector<unsigned char>& hash, std::vector<unsigned char>& preimage) const {
     248   [ +  -  -  - ]:          12 :         return MsLookupHelper(m_sig_data.hash160_preimages, hash, preimage);
     249                 :             :     }
     250                 :             : 
     251                 :         895 :     miniscript::MiniscriptContext MsContext() const {
     252   [ -  -  +  -  :         895 :         return m_script_ctx;
          +  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  +  
          -  +  -  -  -  
          -  -  +  -  +  
          -  +  -  +  -  
          -  -  +  -  +  
          -  -  -  -  -  
          -  -  -  -  +  
          -  +  -  -  -  
          -  -  -  -  +  
          -  +  -  +  -  
          -  -  -  -  -  
          -  +  -  -  -  
          -  -  +  -  +  
          -  +  -  +  -  
          +  -  +  -  -  
          -  -  -  +  -  
          -  -  -  -  -  
          -  -  -  -  -  
             +  -  -  - ]
     253                 :             :     }
     254                 :             : };
     255                 :             : 
     256                 :             : /** Miniscript satisfier specific to P2WSH context. */
     257                 :             : struct WshSatisfier: Satisfier<CPubKey> {
     258                 :          78 :     explicit WshSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
     259                 :             :                           const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& witscript LIFETIMEBOUND)
     260                 :          78 :                           : Satisfier(provider, sig_data, creator, witscript, miniscript::MiniscriptContext::P2WSH) {}
     261                 :             : 
     262                 :             :     //! Conversion from a raw compressed public key.
     263                 :             :     template <typename I>
     264                 :         102 :     std::optional<CPubKey> FromPKBytes(I first, I last) const {
     265         [ +  - ]:         102 :         CPubKey pubkey{first, last};
     266         [ +  - ]:         102 :         if (pubkey.IsValid()) return pubkey;
     267                 :           0 :         return {};
     268                 :             :     }
     269                 :             : 
     270                 :             :     //! Conversion from a raw compressed public key hash.
     271                 :             :     template<typename I>
     272                 :          12 :     std::optional<CPubKey> FromPKHBytes(I first, I last) const {
     273         [ +  - ]:          12 :         return Satisfier::CPubFromPKHBytes(first, last);
     274                 :             :     }
     275                 :             : 
     276                 :             :     //! Satisfy an ECDSA signature check.
     277                 :         114 :     miniscript::Availability Sign(const CPubKey& key, std::vector<unsigned char>& sig) const {
     278         [ +  + ]:         114 :         if (CreateSig(m_creator, m_sig_data, m_provider, sig, key, m_witness_script, SigVersion::WITNESS_V0)) {
     279                 :          84 :             return miniscript::Availability::YES;
     280                 :             :         }
     281                 :             :         return miniscript::Availability::NO;
     282                 :             :     }
     283                 :             : };
     284                 :             : 
     285                 :             : /** Miniscript satisfier specific to Tapscript context. */
     286                 :             : struct TapSatisfier: Satisfier<XOnlyPubKey> {
     287                 :             :     const uint256& m_leaf_hash;
     288                 :             : 
     289                 :          49 :     explicit TapSatisfier(const SigningProvider& provider LIFETIMEBOUND, SignatureData& sig_data LIFETIMEBOUND,
     290                 :             :                           const BaseSignatureCreator& creator LIFETIMEBOUND, const CScript& script LIFETIMEBOUND,
     291                 :             :                           const uint256& leaf_hash LIFETIMEBOUND)
     292                 :          49 :                           : Satisfier(provider, sig_data, creator, script, miniscript::MiniscriptContext::TAPSCRIPT),
     293                 :          49 :                             m_leaf_hash(leaf_hash) {}
     294                 :             : 
     295                 :             :     //! Conversion from a raw xonly public key.
     296                 :             :     template <typename I>
     297         [ +  + ]:          61 :     std::optional<XOnlyPubKey> FromPKBytes(I first, I last) const {
     298         [ +  + ]:          61 :         if (last - first != 32) return {};
     299                 :          60 :         XOnlyPubKey pubkey;
     300                 :          60 :         std::copy(first, last, pubkey.begin());
     301                 :          60 :         return pubkey;
     302                 :             :     }
     303                 :             : 
     304                 :             :     //! Conversion from a raw xonly public key hash.
     305                 :             :     template<typename I>
     306                 :           6 :     std::optional<XOnlyPubKey> FromPKHBytes(I first, I last) const {
     307         [ +  - ]:           6 :         if (auto pubkey = Satisfier::CPubFromPKHBytes(first, last)) return XOnlyPubKey{*pubkey};
     308                 :           0 :         return {};
     309                 :             :     }
     310                 :             : 
     311                 :             :     //! Satisfy a BIP340 signature check.
     312                 :          66 :     miniscript::Availability Sign(const XOnlyPubKey& key, std::vector<unsigned char>& sig) const {
     313         [ +  + ]:          66 :         if (CreateTaprootScriptSig(m_creator, m_sig_data, m_provider, sig, key, m_leaf_hash, SigVersion::TAPSCRIPT)) {
     314                 :          48 :             return miniscript::Availability::YES;
     315                 :             :         }
     316                 :             :         return miniscript::Availability::NO;
     317                 :             :     }
     318                 :             : };
     319                 :             : 
     320                 :          49 : static bool SignTaprootScript(const SigningProvider& provider, const BaseSignatureCreator& creator, SignatureData& sigdata, int leaf_version, Span<const unsigned char> script_bytes, std::vector<valtype>& result)
     321                 :             : {
     322                 :             :     // Only BIP342 tapscript signing is supported for now.
     323         [ +  - ]:          49 :     if (leaf_version != TAPROOT_LEAF_TAPSCRIPT) return false;
     324                 :             : 
     325                 :          49 :     uint256 leaf_hash = ComputeTapleafHash(leaf_version, script_bytes);
     326                 :          49 :     CScript script = CScript(script_bytes.begin(), script_bytes.end());
     327                 :             : 
     328                 :          49 :     TapSatisfier ms_satisfier{provider, sigdata, creator, script, leaf_hash};
     329         [ +  - ]:          49 :     const auto ms = miniscript::FromScript(script, ms_satisfier);
     330   [ +  +  +  -  :          73 :     return ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
             +  +  +  + ]
     331                 :          49 : }
     332                 :             : 
     333                 :          55 : static bool SignTaproot(const SigningProvider& provider, const BaseSignatureCreator& creator, const WitnessV1Taproot& output, SignatureData& sigdata, std::vector<valtype>& result)
     334                 :             : {
     335         [ +  - ]:          55 :     TaprootSpendData spenddata;
     336         [ +  - ]:          55 :     TaprootBuilder builder;
     337                 :             : 
     338                 :             :     // Gather information about this output.
     339   [ +  -  +  + ]:          55 :     if (provider.GetTaprootSpendData(output, spenddata)) {
     340   [ +  -  +  - ]:          96 :         sigdata.tr_spenddata.Merge(spenddata);
     341                 :             :     }
     342   [ +  -  +  + ]:          55 :     if (provider.GetTaprootBuilder(output, builder)) {
     343         [ +  - ]:          48 :         sigdata.tr_builder = builder;
     344                 :             :     }
     345                 :             : 
     346                 :             :     // Try key path spending.
     347                 :          55 :     {
     348         [ +  - ]:          55 :         KeyOriginInfo info;
     349   [ +  -  +  + ]:          55 :         if (provider.GetKeyOriginByXOnly(sigdata.tr_spenddata.internal_key, info)) {
     350                 :          48 :             auto it = sigdata.taproot_misc_pubkeys.find(sigdata.tr_spenddata.internal_key);
     351         [ +  - ]:          48 :             if (it == sigdata.taproot_misc_pubkeys.end()) {
     352   [ +  -  +  - ]:          48 :                 sigdata.taproot_misc_pubkeys.emplace(sigdata.tr_spenddata.internal_key, std::make_pair(std::set<uint256>(), info));
     353                 :             :             }
     354                 :             :         }
     355                 :             : 
     356                 :          55 :         std::vector<unsigned char> sig;
     357         [ +  - ]:          55 :         if (sigdata.taproot_key_path_sig.size() == 0) {
     358   [ +  -  +  + ]:          55 :             if (creator.CreateSchnorrSig(provider, sig, sigdata.tr_spenddata.internal_key, nullptr, &sigdata.tr_spenddata.merkle_root, SigVersion::TAPROOT)) {
     359         [ +  - ]:          18 :                 sigdata.taproot_key_path_sig = sig;
     360                 :             :             }
     361                 :             :         }
     362         [ +  + ]:          55 :         if (sigdata.taproot_key_path_sig.size() == 0) {
     363   [ +  -  +  + ]:          37 :             if (creator.CreateSchnorrSig(provider, sig, output, nullptr, nullptr, SigVersion::TAPROOT)) {
     364         [ +  - ]:           6 :                 sigdata.taproot_key_path_sig = sig;
     365                 :             :             }
     366                 :             :         }
     367         [ +  + ]:          55 :         if (sigdata.taproot_key_path_sig.size()) {
     368         [ +  - ]:          48 :             result = Vector(sigdata.taproot_key_path_sig);
     369                 :          24 :             return true;
     370                 :             :         }
     371                 :          55 :     }
     372                 :             : 
     373                 :             :     // Try script path spending.
     374                 :          31 :     std::vector<std::vector<unsigned char>> smallest_result_stack;
     375   [ +  -  +  + ]:          80 :     for (const auto& [key, control_blocks] : sigdata.tr_spenddata.scripts) {
     376                 :          49 :         const auto& [script, leaf_ver] = key;
     377                 :          49 :         std::vector<std::vector<unsigned char>> result_stack;
     378   [ +  -  +  + ]:          49 :         if (SignTaprootScript(provider, creator, sigdata, leaf_ver, script, result_stack)) {
     379         [ +  - ]:          24 :             result_stack.emplace_back(std::begin(script), std::end(script)); // Push the script
     380         [ +  - ]:          24 :             result_stack.push_back(*control_blocks.begin()); // Push the smallest control block
     381   [ -  +  -  - ]:          24 :             if (smallest_result_stack.size() == 0 ||
     382                 :           0 :                 GetSerializeSize(result_stack) < GetSerializeSize(smallest_result_stack)) {
     383                 :          24 :                 smallest_result_stack = std::move(result_stack);
     384                 :             :             }
     385                 :             :         }
     386                 :          49 :     }
     387         [ +  + ]:          31 :     if (smallest_result_stack.size() != 0) {
     388                 :          24 :         result = std::move(smallest_result_stack);
     389                 :          24 :         return true;
     390                 :             :     }
     391                 :             : 
     392                 :             :     return false;
     393                 :          86 : }
     394                 :             : 
     395                 :             : /**
     396                 :             :  * Sign scriptPubKey using signature made with creator.
     397                 :             :  * Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
     398                 :             :  * unless whichTypeRet is TxoutType::SCRIPTHASH, in which case scriptSigRet is the redemption script.
     399                 :             :  * Returns false if scriptPubKey could not be completely satisfied.
     400                 :             :  */
     401                 :        9934 : static bool SignStep(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& scriptPubKey,
     402                 :             :                      std::vector<valtype>& ret, TxoutType& whichTypeRet, SigVersion sigversion, SignatureData& sigdata)
     403                 :             : {
     404                 :        9934 :     CScript scriptRet;
     405                 :        9934 :     ret.clear();
     406                 :        9934 :     std::vector<unsigned char> sig;
     407                 :             : 
     408                 :        9934 :     std::vector<valtype> vSolutions;
     409         [ +  - ]:        9934 :     whichTypeRet = Solver(scriptPubKey, vSolutions);
     410                 :             : 
     411   [ +  +  +  +  :        9934 :     switch (whichTypeRet) {
          +  +  +  +  -  
                      + ]
     412                 :             :     case TxoutType::NONSTANDARD:
     413                 :             :     case TxoutType::NULL_DATA:
     414                 :             :     case TxoutType::WITNESS_UNKNOWN:
     415                 :             :         return false;
     416                 :         229 :     case TxoutType::PUBKEY:
     417   [ +  -  +  + ]:         229 :         if (!CreateSig(creator, sigdata, provider, sig, CPubKey(vSolutions[0]), scriptPubKey, sigversion)) return false;
     418         [ +  - ]:         129 :         ret.push_back(std::move(sig));
     419                 :             :         return true;
     420                 :        4692 :     case TxoutType::PUBKEYHASH: {
     421         [ +  - ]:        4692 :         CKeyID keyID = CKeyID(uint160(vSolutions[0]));
     422         [ +  - ]:        4692 :         CPubKey pubkey;
     423   [ +  -  +  + ]:        4692 :         if (!GetPubKey(provider, sigdata, keyID, pubkey)) {
     424                 :             :             // Pubkey could not be found, add to missing
     425         [ +  - ]:           1 :             sigdata.missing_pubkeys.push_back(keyID);
     426                 :             :             return false;
     427                 :             :         }
     428   [ +  -  +  + ]:        4691 :         if (!CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) return false;
     429         [ +  - ]:        4685 :         ret.push_back(std::move(sig));
     430         [ +  - ]:        9370 :         ret.push_back(ToByteVector(pubkey));
     431                 :        4685 :         return true;
     432                 :             :     }
     433                 :         115 :     case TxoutType::SCRIPTHASH: {
     434                 :         115 :         uint160 h160{vSolutions[0]};
     435   [ +  -  +  + ]:         115 :         if (GetCScript(provider, sigdata, CScriptID{h160}, scriptRet)) {
     436   [ +  +  +  - ]:         192 :             ret.emplace_back(scriptRet.begin(), scriptRet.end());
     437                 :             :             return true;
     438                 :             :         }
     439                 :             :         // Could not find redeemScript, add to missing
     440                 :           2 :         sigdata.missing_redeem_script = h160;
     441                 :           2 :         return false;
     442                 :             :     }
     443                 :          71 :     case TxoutType::MULTISIG: {
     444         [ +  - ]:          71 :         size_t required = vSolutions.front()[0];
     445         [ +  - ]:          71 :         ret.emplace_back(); // workaround CHECKMULTISIG bug
     446         [ +  + ]:         525 :         for (size_t i = 1; i < vSolutions.size() - 1; ++i) {
     447                 :         454 :             CPubKey pubkey = CPubKey(vSolutions[i]);
     448                 :             :             // We need to always call CreateSig in order to fill sigdata with all
     449                 :             :             // possible signatures that we can create. This will allow further PSBT
     450                 :             :             // processing to work as it needs all possible signature and pubkey pairs
     451   [ +  -  +  + ]:         454 :             if (CreateSig(creator, sigdata, provider, sig, pubkey, scriptPubKey, sigversion)) {
     452         [ +  + ]:         424 :                 if (ret.size() < required + 1) {
     453         [ +  - ]:         454 :                     ret.push_back(std::move(sig));
     454                 :             :                 }
     455                 :             :             }
     456                 :             :         }
     457                 :          71 :         bool ok = ret.size() == required + 1;
     458         [ +  + ]:          87 :         for (size_t i = 0; i + ret.size() < required + 1; ++i) {
     459         [ +  - ]:          16 :             ret.emplace_back();
     460                 :             :         }
     461                 :             :         return ok;
     462                 :             :     }
     463                 :        4561 :     case TxoutType::WITNESS_V0_KEYHASH:
     464         [ +  - ]:        4561 :         ret.push_back(vSolutions[0]);
     465                 :             :         return true;
     466                 :             : 
     467                 :         128 :     case TxoutType::WITNESS_V0_SCRIPTHASH:
     468   [ +  -  +  -  :         128 :         if (GetCScript(provider, sigdata, CScriptID{RIPEMD160(vSolutions[0])}, scriptRet)) {
                   +  - ]
     469   [ +  +  +  - ]:         244 :             ret.emplace_back(scriptRet.begin(), scriptRet.end());
     470                 :             :             return true;
     471                 :             :         }
     472                 :             :         // Could not find witnessScript, add to missing
     473                 :           0 :         sigdata.missing_witness_script = uint256(vSolutions[0]);
     474                 :           0 :         return false;
     475                 :             : 
     476                 :          55 :     case TxoutType::WITNESS_V1_TAPROOT:
     477   [ +  -  +  - ]:          55 :         return SignTaproot(provider, creator, WitnessV1Taproot(XOnlyPubKey{vSolutions[0]}), sigdata, ret);
     478                 :             : 
     479                 :           1 :     case TxoutType::ANCHOR:
     480                 :           1 :         return true;
     481                 :             :     } // no default case, so the compiler can warn about missing cases
     482                 :           0 :     assert(false);
     483                 :        9934 : }
     484                 :             : 
     485                 :        5132 : static CScript PushAll(const std::vector<valtype>& values)
     486                 :             : {
     487                 :        5132 :     CScript result;
     488         [ +  + ]:        5707 :     for (const valtype& v : values) {
     489         [ +  + ]:         575 :         if (v.size() == 0) {
     490         [ +  - ]:          55 :             result << OP_0;
     491   [ -  +  -  -  :         520 :         } else if (v.size() == 1 && v[0] >= 1 && v[0] <= 16) {
                   -  - ]
     492         [ #  # ]:           0 :             result << CScript::EncodeOP_N(v[0]);
     493   [ -  +  -  - ]:         520 :         } else if (v.size() == 1 && v[0] == 0x81) {
     494         [ #  # ]:           0 :             result << OP_1NEGATE;
     495                 :             :         } else {
     496                 :         520 :             result << v;
     497                 :             :         }
     498                 :             :     }
     499                 :        5132 :     return result;
     500                 :           0 : }
     501                 :             : 
     502                 :        5140 : bool ProduceSignature(const SigningProvider& provider, const BaseSignatureCreator& creator, const CScript& fromPubKey, SignatureData& sigdata)
     503                 :             : {
     504         [ +  + ]:        5140 :     if (sigdata.complete) return true;
     505                 :             : 
     506                 :        5132 :     std::vector<valtype> result;
     507                 :        5132 :     TxoutType whichType;
     508         [ +  - ]:        5132 :     bool solved = SignStep(provider, creator, fromPubKey, result, whichType, SigVersion::BASE, sigdata);
     509                 :        5132 :     bool P2SH = false;
     510                 :        5132 :     CScript subscript;
     511                 :             : 
     512   [ +  +  +  + ]:        5132 :     if (solved && whichType == TxoutType::SCRIPTHASH)
     513                 :             :     {
     514                 :             :         // Solver returns the subscript that needs to be evaluated;
     515                 :             :         // the final scriptSig is the signatures from that
     516                 :             :         // and then the serialized subscript:
     517                 :         113 :         subscript = CScript(result[0].begin(), result[0].end());
     518                 :         113 :         sigdata.redeem_script = subscript;
     519   [ +  -  +  +  :         113 :         solved = solved && SignStep(provider, creator, subscript, result, whichType, SigVersion::BASE, sigdata) && whichType != TxoutType::SCRIPTHASH;
                   +  - ]
     520                 :             :         P2SH = true;
     521                 :             :     }
     522                 :             : 
     523         [ +  + ]:        5008 :     if (solved && whichType == TxoutType::WITNESS_V0_KEYHASH)
     524                 :             :     {
     525                 :        4561 :         CScript witnessscript;
     526   [ +  -  +  -  :        4561 :         witnessscript << OP_DUP << OP_HASH160 << ToByteVector(result[0]) << OP_EQUALVERIFY << OP_CHECKSIG;
          +  -  +  -  +  
                      - ]
     527                 :        4561 :         TxoutType subType;
     528   [ +  -  +  -  :        4561 :         solved = solved && SignStep(provider, creator, witnessscript, result, subType, SigVersion::WITNESS_V0, sigdata);
                   +  + ]
     529         [ +  - ]:        4561 :         sigdata.scriptWitness.stack = result;
     530                 :        4561 :         sigdata.witness = true;
     531                 :        4561 :         result.clear();
     532                 :        4561 :     }
     533   [ +  +  +  + ]:         565 :     else if (solved && whichType == TxoutType::WITNESS_V0_SCRIPTHASH)
     534                 :             :     {
     535                 :         128 :         CScript witnessscript(result[0].begin(), result[0].end());
     536                 :         128 :         sigdata.witness_script = witnessscript;
     537                 :             : 
     538                 :         128 :         TxoutType subType{TxoutType::NONSTANDARD};
     539   [ +  -  +  +  :         128 :         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;
          +  -  +  -  -  
                      + ]
     540                 :             : 
     541                 :             :         // If we couldn't find a solution with the legacy satisfier, try satisfying the script using Miniscript.
     542                 :             :         // Note we need to check if the result stack is empty before, because it might be used even if the Script
     543                 :             :         // isn't fully solved. For instance the CHECKMULTISIG satisfaction in SignStep() pushes partial signatures
     544                 :             :         // and the extractor relies on this behaviour to combine witnesses.
     545         [ +  + ]:          84 :         if (!solved && result.empty()) {
     546                 :          78 :             WshSatisfier ms_satisfier{provider, sigdata, creator, witnessscript};
     547         [ +  - ]:          78 :             const auto ms = miniscript::FromScript(witnessscript, ms_satisfier);
     548   [ +  -  +  -  :         114 :             solved = ms && ms->Satisfy(ms_satisfier, result) == miniscript::Availability::YES;
             +  +  +  - ]
     549                 :          78 :         }
     550   [ +  +  +  - ]:         244 :         result.emplace_back(witnessscript.begin(), witnessscript.end());
     551                 :             : 
     552         [ +  - ]:         128 :         sigdata.scriptWitness.stack = result;
     553                 :         128 :         sigdata.witness = true;
     554                 :         128 :         result.clear();
     555   [ +  +  +  - ]:         571 :     } else if (whichType == TxoutType::WITNESS_V1_TAPROOT && !P2SH) {
     556                 :          55 :         sigdata.witness = true;
     557         [ +  + ]:          55 :         if (solved) {
     558                 :          48 :             sigdata.scriptWitness.stack = std::move(result);
     559                 :             :         }
     560                 :          55 :         result.clear();
     561   [ +  +  -  + ]:         388 :     } else if (solved && whichType == TxoutType::WITNESS_UNKNOWN) {
     562                 :           0 :         sigdata.witness = true;
     563                 :             :     }
     564                 :             : 
     565         [ +  + ]:        5132 :     if (!sigdata.witness) sigdata.scriptWitness.stack.clear();
     566         [ +  + ]:        5132 :     if (P2SH) {
     567   [ +  +  +  - ]:         192 :         result.emplace_back(subscript.begin(), subscript.end());
     568                 :             :     }
     569         [ +  - ]:        5132 :     sigdata.scriptSig = PushAll(result);
     570                 :             : 
     571                 :             :     // Test solution
     572   [ +  +  +  -  :        5132 :     sigdata.complete = solved && VerifyScript(sigdata.scriptSig, fromPubKey, &sigdata.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, creator.Checker());
             +  -  -  + ]
     573                 :        5132 :     return sigdata.complete;
     574                 :        5132 : }
     575                 :             : 
     576                 :             : namespace {
     577                 :         199 : class SignatureExtractorChecker final : public DeferringSignatureChecker
     578                 :             : {
     579                 :             : private:
     580                 :             :     SignatureData& sigdata;
     581                 :             : 
     582                 :             : public:
     583                 :         199 :     SignatureExtractorChecker(SignatureData& sigdata, BaseSignatureChecker& checker) : DeferringSignatureChecker(checker), sigdata(sigdata) {}
     584                 :             : 
     585                 :          47 :     bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
     586                 :             :     {
     587         [ +  + ]:          47 :         if (m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion)) {
     588                 :          14 :             CPubKey pubkey(vchPubKey);
     589   [ +  -  +  - ]:          14 :             sigdata.signatures.emplace(pubkey.GetID(), SigPair(pubkey, scriptSig));
     590                 :          14 :             return true;
     591                 :             :         }
     592                 :             :         return false;
     593                 :             :     }
     594                 :             : };
     595                 :             : 
     596                 :         199 : struct Stacks
     597                 :             : {
     598                 :             :     std::vector<valtype> script;
     599                 :             :     std::vector<valtype> witness;
     600                 :             : 
     601                 :             :     Stacks() = delete;
     602                 :             :     Stacks(const Stacks&) = delete;
     603         [ +  - ]:         199 :     explicit Stacks(const SignatureData& data) : witness(data.scriptWitness.stack) {
     604         [ +  - ]:         199 :         EvalScript(script, data.scriptSig, SCRIPT_VERIFY_STRICTENC, BaseSignatureChecker(), SigVersion::BASE);
     605                 :         199 :     }
     606                 :             : };
     607                 :             : }
     608                 :             : 
     609                 :             : // Extracts signatures and scripts from incomplete scriptSigs. Please do not extend this, use PSBT instead
     610                 :         199 : SignatureData DataFromTransaction(const CMutableTransaction& tx, unsigned int nIn, const CTxOut& txout)
     611                 :             : {
     612                 :         199 :     SignatureData data;
     613         [ -  + ]:         199 :     assert(tx.vin.size() > nIn);
     614                 :         199 :     data.scriptSig = tx.vin[nIn].scriptSig;
     615         [ +  - ]:         199 :     data.scriptWitness = tx.vin[nIn].scriptWitness;
     616         [ +  - ]:         199 :     Stacks stack(data);
     617                 :             : 
     618                 :             :     // Get signatures
     619         [ +  - ]:         199 :     MutableTransactionSignatureChecker tx_checker(&tx, nIn, txout.nValue, MissingDataBehavior::FAIL);
     620         [ +  - ]:         199 :     SignatureExtractorChecker extractor_checker(data, tx_checker);
     621   [ +  -  +  + ]:         199 :     if (VerifyScript(data.scriptSig, txout.scriptPubKey, &data.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, extractor_checker)) {
     622                 :           5 :         data.complete = true;
     623                 :           5 :         return data;
     624                 :             :     }
     625                 :             : 
     626                 :             :     // Get scripts
     627                 :         194 :     std::vector<std::vector<unsigned char>> solutions;
     628         [ +  - ]:         194 :     TxoutType script_type = Solver(txout.scriptPubKey, solutions);
     629                 :         194 :     SigVersion sigversion = SigVersion::BASE;
     630                 :         194 :     CScript next_script = txout.scriptPubKey;
     631                 :             : 
     632   [ +  +  +  +  :         194 :     if (script_type == TxoutType::SCRIPTHASH && !stack.script.empty() && !stack.script.back().empty()) {
                   +  - ]
     633                 :             :         // Get the redeemScript
     634                 :           4 :         CScript redeem_script(stack.script.back().begin(), stack.script.back().end());
     635                 :           4 :         data.redeem_script = redeem_script;
     636                 :           4 :         next_script = std::move(redeem_script);
     637                 :             : 
     638                 :             :         // Get redeemScript type
     639         [ +  - ]:           4 :         script_type = Solver(next_script, solutions);
     640                 :           4 :         stack.script.pop_back();
     641                 :           4 :     }
     642   [ +  +  +  -  :         194 :     if (script_type == TxoutType::WITNESS_V0_SCRIPTHASH && !stack.witness.empty() && !stack.witness.back().empty()) {
                   +  - ]
     643                 :             :         // Get the witnessScript
     644                 :           4 :         CScript witness_script(stack.witness.back().begin(), stack.witness.back().end());
     645                 :           4 :         data.witness_script = witness_script;
     646                 :           4 :         next_script = std::move(witness_script);
     647                 :             : 
     648                 :             :         // Get witnessScript type
     649         [ +  - ]:           4 :         script_type = Solver(next_script, solutions);
     650                 :           4 :         stack.witness.pop_back();
     651                 :           4 :         stack.script = std::move(stack.witness);
     652                 :           4 :         stack.witness.clear();
     653                 :           4 :         sigversion = SigVersion::WITNESS_V0;
     654                 :           4 :     }
     655   [ +  +  +  - ]:         194 :     if (script_type == TxoutType::MULTISIG && !stack.script.empty()) {
     656                 :             :         // Build a map of pubkey -> signature by matching sigs to pubkeys:
     657         [ -  + ]:           8 :         assert(solutions.size() > 1);
     658                 :           8 :         unsigned int num_pubkeys = solutions.size()-2;
     659                 :           8 :         unsigned int last_success_key = 0;
     660         [ +  + ]:          32 :         for (const valtype& sig : stack.script) {
     661         [ +  + ]:          48 :             for (unsigned int i = last_success_key; i < num_pubkeys; ++i) {
     662                 :          32 :                 const valtype& pubkey = solutions[i+1];
     663                 :             :                 // We either have a signature for this pubkey, or we have found a signature and it is valid
     664   [ +  -  +  -  :          32 :                 if (data.signatures.count(CPubKey(pubkey).GetID()) || extractor_checker.CheckECDSASignature(sig, pubkey, next_script, sigversion)) {
             +  -  +  + ]
     665                 :             :                     last_success_key = i + 1;
     666                 :             :                     break;
     667                 :             :                 }
     668                 :             :             }
     669                 :             :         }
     670                 :             :     }
     671                 :             : 
     672                 :         194 :     return data;
     673                 :         398 : }
     674                 :             : 
     675                 :        4803 : void UpdateInput(CTxIn& input, const SignatureData& data)
     676                 :             : {
     677                 :        4803 :     input.scriptSig = data.scriptSig;
     678                 :        4803 :     input.scriptWitness = data.scriptWitness;
     679                 :        4803 : }
     680                 :             : 
     681                 :          38 : void SignatureData::MergeSignatureData(SignatureData sigdata)
     682                 :             : {
     683         [ +  + ]:          38 :     if (complete) return;
     684         [ +  + ]:          33 :     if (sigdata.complete) {
     685                 :           8 :         *this = std::move(sigdata);
     686                 :           8 :         return;
     687                 :             :     }
     688   [ +  +  +  +  :          27 :     if (redeem_script.empty() && !sigdata.redeem_script.empty()) {
             -  +  -  + ]
     689                 :           0 :         redeem_script = sigdata.redeem_script;
     690                 :             :     }
     691   [ +  +  +  +  :          27 :     if (witness_script.empty() && !sigdata.witness_script.empty()) {
             -  +  -  + ]
     692                 :           0 :         witness_script = sigdata.witness_script;
     693                 :             :     }
     694                 :          25 :     signatures.insert(std::make_move_iterator(sigdata.signatures.begin()), std::make_move_iterator(sigdata.signatures.end()));
     695                 :             : }
     696                 :             : 
     697                 :        4609 : bool SignSignature(const SigningProvider &provider, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, const CAmount& amount, int nHashType, SignatureData& sig_data)
     698                 :             : {
     699         [ -  + ]:        4609 :     assert(nIn < txTo.vin.size());
     700                 :             : 
     701                 :        4609 :     MutableTransactionSignatureCreator creator(txTo, nIn, amount, nHashType);
     702                 :             : 
     703         [ +  - ]:        4609 :     bool ret = ProduceSignature(provider, creator, fromPubKey, sig_data);
     704   [ +  -  +  - ]:        4609 :     UpdateInput(txTo.vin.at(nIn), sig_data);
     705                 :        4609 :     return ret;
     706                 :        4609 : }
     707                 :             : 
     708                 :         109 : bool SignSignature(const SigningProvider &provider, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType, SignatureData& sig_data)
     709                 :             : {
     710         [ -  + ]:         109 :     assert(nIn < txTo.vin.size());
     711         [ -  + ]:         109 :     const CTxIn& txin = txTo.vin[nIn];
     712         [ -  + ]:         109 :     assert(txin.prevout.n < txFrom.vout.size());
     713                 :         109 :     const CTxOut& txout = txFrom.vout[txin.prevout.n];
     714                 :             : 
     715                 :         109 :     return SignSignature(provider, txout.scriptPubKey, txTo, nIn, txout.nValue, nHashType, sig_data);
     716                 :             : }
     717                 :             : 
     718                 :             : namespace {
     719                 :             : /** Dummy signature checker which accepts all signatures. */
     720                 :             : class DummySignatureChecker final : public BaseSignatureChecker
     721                 :             : {
     722                 :             : public:
     723                 :             :     DummySignatureChecker() = default;
     724                 :           6 :     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; }
     725                 :           0 :     bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror) const override { return sig.size() != 0; }
     726                 :           0 :     bool CheckLockTime(const CScriptNum& nLockTime) const override { return true; }
     727                 :           0 :     bool CheckSequence(const CScriptNum& nSequence) const override { return true; }
     728                 :             : };
     729                 :             : }
     730                 :             : 
     731                 :             : const BaseSignatureChecker& DUMMY_CHECKER = DummySignatureChecker();
     732                 :             : 
     733                 :             : namespace {
     734                 :             : class DummySignatureCreator final : public BaseSignatureCreator {
     735                 :             : private:
     736                 :             :     char m_r_len = 32;
     737                 :             :     char m_s_len = 32;
     738                 :             : public:
     739                 :             :     DummySignatureCreator(char r_len, char s_len) : m_r_len(r_len), m_s_len(s_len) {}
     740                 :           2 :     const BaseSignatureChecker& Checker() const override { return DUMMY_CHECKER; }
     741                 :           2 :     bool CreateSig(const SigningProvider& provider, std::vector<unsigned char>& vchSig, const CKeyID& keyid, const CScript& scriptCode, SigVersion sigversion) const override
     742                 :             :     {
     743                 :             :         // Create a dummy signature that is a valid DER-encoding
     744                 :           2 :         vchSig.assign(m_r_len + m_s_len + 7, '\000');
     745                 :           2 :         vchSig[0] = 0x30;
     746                 :           2 :         vchSig[1] = m_r_len + m_s_len + 4;
     747                 :           2 :         vchSig[2] = 0x02;
     748                 :           2 :         vchSig[3] = m_r_len;
     749                 :           2 :         vchSig[4] = 0x01;
     750                 :           2 :         vchSig[4 + m_r_len] = 0x02;
     751                 :           2 :         vchSig[5 + m_r_len] = m_s_len;
     752                 :           2 :         vchSig[6 + m_r_len] = 0x01;
     753                 :           2 :         vchSig[6 + m_r_len + m_s_len] = SIGHASH_ALL;
     754                 :           2 :         return true;
     755                 :             :     }
     756                 :           0 :     bool CreateSchnorrSig(const SigningProvider& provider, std::vector<unsigned char>& sig, const XOnlyPubKey& pubkey, const uint256* leaf_hash, const uint256* tweak, SigVersion sigversion) const override
     757                 :             :     {
     758                 :           0 :         sig.assign(64, '\000');
     759                 :           0 :         return true;
     760                 :             :     }
     761                 :             : };
     762                 :             : 
     763                 :             : }
     764                 :             : 
     765                 :             : const BaseSignatureCreator& DUMMY_SIGNATURE_CREATOR = DummySignatureCreator(32, 32);
     766                 :             : const BaseSignatureCreator& DUMMY_MAXIMUM_SIGNATURE_CREATOR = DummySignatureCreator(33, 32);
     767                 :             : 
     768                 :           0 : bool IsSegWitOutput(const SigningProvider& provider, const CScript& script)
     769                 :             : {
     770                 :           0 :     int version;
     771                 :           0 :     valtype program;
     772   [ #  #  #  # ]:           0 :     if (script.IsWitnessProgram(version, program)) return true;
     773   [ #  #  #  # ]:           0 :     if (script.IsPayToScriptHash()) {
     774                 :           0 :         std::vector<valtype> solutions;
     775         [ #  # ]:           0 :         auto whichtype = Solver(script, solutions);
     776         [ #  # ]:           0 :         if (whichtype == TxoutType::SCRIPTHASH) {
     777                 :           0 :             auto h160 = uint160(solutions[0]);
     778                 :           0 :             CScript subscript;
     779   [ #  #  #  # ]:           0 :             if (provider.GetCScript(CScriptID{h160}, subscript)) {
     780   [ #  #  #  # ]:           0 :                 if (subscript.IsWitnessProgram(version, program)) return true;
     781                 :             :             }
     782                 :           0 :         }
     783                 :           0 :     }
     784                 :             :     return false;
     785                 :           0 : }
     786                 :             : 
     787                 :         181 : bool SignTransaction(CMutableTransaction& mtx, const SigningProvider* keystore, const std::map<COutPoint, Coin>& coins, int nHashType, std::map<int, bilingual_str>& input_errors)
     788                 :             : {
     789                 :         181 :     bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
     790                 :             : 
     791                 :             :     // Use CTransaction for the constant parts of the
     792                 :             :     // transaction to avoid rehashing.
     793                 :         181 :     const CTransaction txConst(mtx);
     794                 :             : 
     795                 :         181 :     PrecomputedTransactionData txdata;
     796                 :         181 :     std::vector<CTxOut> spent_outputs;
     797         [ +  + ]:         362 :     for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
     798                 :         181 :         CTxIn& txin = mtx.vin[i];
     799                 :         181 :         auto coin = coins.find(txin.prevout);
     800   [ +  -  -  + ]:         181 :         if (coin == coins.end() || coin->second.IsSpent()) {
     801         [ #  # ]:           0 :             txdata.Init(txConst, /*spent_outputs=*/{}, /*force=*/true);
     802                 :           0 :             break;
     803                 :             :         } else {
     804         [ +  - ]:         181 :             spent_outputs.emplace_back(coin->second.out.nValue, coin->second.out.scriptPubKey);
     805                 :             :         }
     806                 :             :     }
     807         [ +  - ]:         181 :     if (spent_outputs.size() == mtx.vin.size()) {
     808         [ +  - ]:         181 :         txdata.Init(txConst, std::move(spent_outputs), true);
     809                 :             :     }
     810                 :             : 
     811                 :             :     // Sign what we can:
     812         [ +  + ]:         362 :     for (unsigned int i = 0; i < mtx.vin.size(); ++i) {
     813                 :         181 :         CTxIn& txin = mtx.vin[i];
     814                 :         181 :         auto coin = coins.find(txin.prevout);
     815   [ +  -  +  - ]:         181 :         if (coin == coins.end() || coin->second.IsSpent()) {
     816   [ #  #  #  # ]:           0 :             input_errors[i] = _("Input not found or already spent");
     817                 :           0 :             continue;
     818                 :             :         }
     819         [ +  - ]:         181 :         const CScript& prevPubKey = coin->second.out.scriptPubKey;
     820                 :         181 :         const CAmount& amount = coin->second.out.nValue;
     821                 :             : 
     822         [ +  - ]:         362 :         SignatureData sigdata = DataFromTransaction(mtx, i, coin->second.out);
     823                 :             :         // Only sign SIGHASH_SINGLE if there's a corresponding output:
     824   [ -  +  -  - ]:         181 :         if (!fHashSingle || (i < mtx.vout.size())) {
     825         [ +  - ]:         181 :             ProduceSignature(*keystore, MutableTransactionSignatureCreator(mtx, i, amount, &txdata, nHashType), prevPubKey, sigdata);
     826                 :             :         }
     827                 :             : 
     828         [ +  - ]:         181 :         UpdateInput(txin, sigdata);
     829                 :             : 
     830                 :             :         // amount must be specified for valid segwit signature
     831   [ +  +  +  - ]:         181 :         if (amount == MAX_MONEY && !txin.scriptWitness.IsNull()) {
     832   [ #  #  #  # ]:           0 :             input_errors[i] = _("Missing amount");
     833                 :           0 :             continue;
     834                 :             :         }
     835                 :             : 
     836                 :         181 :         ScriptError serror = SCRIPT_ERR_OK;
     837   [ +  +  +  -  :         282 :         if (!sigdata.complete && !VerifyScript(txin.scriptSig, prevPubKey, &txin.scriptWitness, STANDARD_SCRIPT_VERIFY_FLAGS, TransactionSignatureChecker(&txConst, i, amount, txdata, MissingDataBehavior::FAIL), &serror)) {
             +  -  +  + ]
     838         [ +  + ]:         101 :             if (serror == SCRIPT_ERR_INVALID_STACK_OPERATION) {
     839                 :             :                 // Unable to sign input and verification failed (possible attempt to partially sign).
     840   [ +  -  +  -  :         200 :                 input_errors[i] = Untranslated("Unable to sign input, invalid stack size (possibly missing key)");
                   +  - ]
     841         [ -  + ]:           1 :             } else if (serror == SCRIPT_ERR_SIG_NULLFAIL) {
     842                 :             :                 // Verification failed (possibly due to insufficient signatures).
     843   [ #  #  #  #  :           0 :                 input_errors[i] = Untranslated("CHECK(MULTI)SIG failing with non-zero signature (possibly need more signatures)");
                   #  # ]
     844                 :             :             } else {
     845   [ +  -  +  -  :           2 :                 input_errors[i] = Untranslated(ScriptErrorString(serror));
                   +  - ]
     846                 :             :             }
     847                 :             :         } else {
     848                 :             :             // If this input succeeds, make sure there is no error set for it
     849                 :          80 :             input_errors.erase(i);
     850                 :             :         }
     851                 :         181 :     }
     852                 :         181 :     return input_errors.empty();
     853                 :         362 : }
        

Generated by: LCOV version 2.0-1