sighash_tests.cpp raw

   1  // Copyright (c) 2013-2022 The Limenka developers
   2  // Distributed under the MIT software license, see the accompanying
   3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   4  
   5  #include <common/system.h>
   6  #include <consensus/tx_check.h>
   7  #include <consensus/validation.h>
   8  #include <hash.h>
   9  #include <key.h>
  10  #include <random.h>
  11  #include <primitives/transaction.h>
  12  #include <pubkey.h>
  13  #include <script/interpreter.h>
  14  #include <script/signingprovider.h>
  15  #include <script/sign.h>
  16  #include <script/script.h>
  17  #include <serialize.h>
  18  #include <streams.h>
  19  #include <test/data/sighash.json.h>
  20  #include <test/util/json.h>
  21  #include <test/util/random.h>
  22  #include <test/util/setup_common.h>
  23  #include <util/strencodings.h>
  24  
  25  #include <iostream>
  26  
  27  #include <boost/test/unit_test.hpp>
  28  
  29  #include <univalue.h>
  30  
  31  // Old script.cpp SignatureHash function
  32  uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
  33  {
  34      if (nIn >= txTo.vin.size())
  35      {
  36          return uint256::ONE;
  37      }
  38      CMutableTransaction txTmp(txTo);
  39  
  40      // In case concatenating two scripts ends up with two codeseparators,
  41      // or an extra one at the end, this prevents all those possible incompatibilities.
  42      FindAndDelete(scriptCode, CScript(OP_CODESEPARATOR));
  43  
  44      // Blank out other inputs' signatures
  45      for (unsigned int i = 0; i < txTmp.vin.size(); i++)
  46          txTmp.vin[i].scriptSig = CScript();
  47      txTmp.vin[nIn].scriptSig = scriptCode;
  48  
  49      // Blank out some of the outputs
  50      if ((nHashType & 0x1f) == SIGHASH_NONE)
  51      {
  52          // Wildcard payee
  53          txTmp.vout.clear();
  54  
  55          // Let the others update at will
  56          for (unsigned int i = 0; i < txTmp.vin.size(); i++)
  57              if (i != nIn)
  58                  txTmp.vin[i].nSequence = 0;
  59      }
  60      else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
  61      {
  62          // Only lock-in the txout payee at same index as txin
  63          unsigned int nOut = nIn;
  64          if (nOut >= txTmp.vout.size())
  65          {
  66              return uint256::ONE;
  67          }
  68          txTmp.vout.resize(nOut+1);
  69          for (unsigned int i = 0; i < nOut; i++)
  70              txTmp.vout[i].SetNull();
  71  
  72          // Let the others update at will
  73          for (unsigned int i = 0; i < txTmp.vin.size(); i++)
  74              if (i != nIn)
  75                  txTmp.vin[i].nSequence = 0;
  76      }
  77  
  78      // Blank out other inputs completely, not recommended for open transactions
  79      if (nHashType & SIGHASH_ANYONECANPAY)
  80      {
  81          txTmp.vin[0] = txTmp.vin[nIn];
  82          txTmp.vin.resize(1);
  83      }
  84  
  85      // Serialize and hash
  86      HashWriter ss{};
  87      ss << TX_NO_WITNESS(txTmp) << nHashType;
  88      return ss.GetHash();
  89  }
  90  
  91  struct SigHashTest : BasicTestingSetup {
  92  void RandomScript(CScript &script) {
  93      static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR};
  94      script = CScript();
  95      int ops = (m_rng.randrange(10));
  96      for (int i=0; i<ops; i++)
  97          script << oplist[m_rng.randrange(std::size(oplist))];
  98  }
  99  
 100  void RandomTransaction(CMutableTransaction& tx, bool fSingle)
 101  {
 102      tx.version = m_rng.rand32();
 103      tx.vin.clear();
 104      tx.vout.clear();
 105      tx.nLockTime = (m_rng.randbool()) ? m_rng.rand32() : 0;
 106      int ins = (m_rng.randbits(2)) + 1;
 107      int outs = fSingle ? ins : (m_rng.randbits(2)) + 1;
 108      for (int in = 0; in < ins; in++) {
 109          tx.vin.emplace_back();
 110          CTxIn &txin = tx.vin.back();
 111          txin.prevout.hash = Txid::FromUint256(m_rng.rand256());
 112          txin.prevout.n = m_rng.randbits(2);
 113          RandomScript(txin.scriptSig);
 114          txin.nSequence = (m_rng.randbool()) ? m_rng.rand32() : std::numeric_limits<uint32_t>::max();
 115      }
 116      for (int out = 0; out < outs; out++) {
 117          tx.vout.emplace_back();
 118          CTxOut &txout = tx.vout.back();
 119          txout.nValue = RandMoney(m_rng);
 120          RandomScript(txout.scriptPubKey);
 121      }
 122  }
 123  }; // struct SigHashTest
 124  
 125  BOOST_FIXTURE_TEST_SUITE(sighash_tests, SigHashTest)
 126  
 127  BOOST_AUTO_TEST_CASE(sighash_test)
 128  {
 129      #if defined(PRINT_SIGHASH_JSON)
 130      std::cout << "[\n";
 131      std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
 132      int nRandomTests = 500;
 133      #else
 134      int nRandomTests = 50000;
 135      #endif
 136      for (int i=0; i<nRandomTests; i++) {
 137          int nHashType{int(m_rng.rand32())};
 138          CMutableTransaction txTo;
 139          RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
 140          CScript scriptCode;
 141          RandomScript(scriptCode);
 142          int nIn = m_rng.randrange(txTo.vin.size());
 143  
 144          uint256 sh, sho;
 145          sho = SignatureHashOld(scriptCode, CTransaction(txTo), nIn, nHashType);
 146          sh = SignatureHash(scriptCode, txTo, nIn, nHashType, 0, SigVersion::BASE);
 147          #if defined(PRINT_SIGHASH_JSON)
 148          DataStream ss;
 149          ss << TX_WITH_WITNESS(txTo);
 150  
 151          std::cout << "\t[\"" ;
 152          std::cout << HexStr(ss) << "\", \"";
 153          std::cout << HexStr(scriptCode) << "\", ";
 154          std::cout << nIn << ", ";
 155          std::cout << nHashType << ", \"";
 156          std::cout << sho.GetHex() << "\"]";
 157          if (i+1 != nRandomTests) {
 158            std::cout << ",";
 159          }
 160          std::cout << "\n";
 161          #endif
 162          BOOST_CHECK(sh == sho);
 163      }
 164      #if defined(PRINT_SIGHASH_JSON)
 165      std::cout << "]\n";
 166      #endif
 167  }
 168  
 169  // Goal: check that SignatureHash generates correct hash
 170  BOOST_AUTO_TEST_CASE(sighash_from_data)
 171  {
 172      UniValue tests = read_json(json_tests::sighash);
 173  
 174      for (unsigned int idx = 0; idx < tests.size(); idx++) {
 175          const UniValue& test = tests[idx];
 176          std::string strTest = test.write();
 177          if (test.size() < 1) // Allow for extra stuff (useful for comments)
 178          {
 179              BOOST_ERROR("Bad test: " << strTest);
 180              continue;
 181          }
 182          if (test.size() == 1) continue; // comment
 183  
 184          std::string raw_tx, raw_script, sigHashHex;
 185          int nIn, nHashType;
 186          uint256 sh;
 187          CTransactionRef tx;
 188          CScript scriptCode = CScript();
 189  
 190          try {
 191            // deserialize test data
 192            raw_tx = test[0].get_str();
 193            raw_script = test[1].get_str();
 194            nIn = test[2].getInt<int>();
 195            nHashType = test[3].getInt<int>();
 196            sigHashHex = test[4].get_str();
 197  
 198            DataStream stream(ParseHex(raw_tx));
 199            stream >> TX_WITH_WITNESS(tx);
 200  
 201            TxValidationState state;
 202            BOOST_CHECK_MESSAGE(CheckTransaction(*tx, state), strTest);
 203            BOOST_CHECK(state.IsValid());
 204  
 205            std::vector<unsigned char> raw = ParseHex(raw_script);
 206            scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
 207          } catch (...) {
 208            BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest);
 209            continue;
 210          }
 211  
 212          sh = SignatureHash(scriptCode, *tx, nIn, nHashType, 0, SigVersion::BASE);
 213          BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
 214      }
 215  }
 216  
 217  BOOST_AUTO_TEST_CASE(sighash_caching)
 218  {
 219      // Get a script, transaction and parameters as inputs to the sighash function.
 220      CScript scriptcode;
 221      RandomScript(scriptcode);
 222      CScript diff_scriptcode{scriptcode};
 223      diff_scriptcode << OP_1;
 224      CMutableTransaction tx;
 225      RandomTransaction(tx, /*fSingle=*/false);
 226      const auto in_index{static_cast<uint32_t>(m_rng.randrange(tx.vin.size()))};
 227      const CAmount amount{m_rng.rand<int64_t>()};
 228  
 229      // Exercise the sighash function under both legacy and segwit v0.
 230      for (const auto sigversion: {SigVersion::BASE, SigVersion::WITNESS_V0}) {
 231          // For each, run it against all the 6 standard hash types and a few additional random ones.
 232          std::vector<int32_t> hash_types{{SIGHASH_ALL, SIGHASH_SINGLE, SIGHASH_NONE, SIGHASH_ALL | SIGHASH_ANYONECANPAY,
 233                                            SIGHASH_SINGLE | SIGHASH_ANYONECANPAY, SIGHASH_NONE | SIGHASH_ANYONECANPAY,
 234                                            SIGHASH_ANYONECANPAY, 0, std::numeric_limits<int32_t>::max()}};
 235          for (int i{0}; i < 10; ++i) {
 236              hash_types.push_back(i % 2 == 0 ? m_rng.rand<int8_t>() : m_rng.rand<int32_t>());
 237          }
 238  
 239          // Reuse the same cache across script types. This must not cause any issue as the cached value for one hash type must never
 240          // be confused for another (instantiating the cache within the loop instead would prevent testing this).
 241          SigHashCache cache;
 242          for (const auto hash_type: hash_types) {
 243              const bool expect_one{sigversion == SigVersion::BASE && ((hash_type & 0x1f) == SIGHASH_SINGLE) && in_index >= tx.vout.size()};
 244  
 245              // The result of computing the sighash should be the same with or without cache.
 246              const auto sighash_with_cache{SignatureHash(scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, &cache)};
 247              const auto sighash_no_cache{SignatureHash(scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, nullptr)};
 248              BOOST_CHECK_EQUAL(sighash_with_cache, sighash_no_cache);
 249  
 250              // Calling the cached version again should return the same value again.
 251              BOOST_CHECK_EQUAL(sighash_with_cache, SignatureHash(scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, &cache));
 252  
 253              // While here we might as well also check that the result for legacy is the same as for the old SignatureHash() function.
 254              if (sigversion == SigVersion::BASE) {
 255                  BOOST_CHECK_EQUAL(sighash_with_cache, SignatureHashOld(scriptcode, CTransaction(tx), in_index, hash_type));
 256              }
 257  
 258              // Calling with a different scriptcode (for instance in case a CODESEP is encountered) will not return the cache value but
 259              // overwrite it. The sighash will always be different except in case of legacy SIGHASH_SINGLE bug.
 260              const auto sighash_with_cache2{SignatureHash(diff_scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, &cache)};
 261              const auto sighash_no_cache2{SignatureHash(diff_scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, nullptr)};
 262              BOOST_CHECK_EQUAL(sighash_with_cache2, sighash_no_cache2);
 263              if (!expect_one) {
 264                  BOOST_CHECK_NE(sighash_with_cache, sighash_with_cache2);
 265              } else {
 266                  BOOST_CHECK_EQUAL(sighash_with_cache, sighash_with_cache2);
 267                  BOOST_CHECK_EQUAL(sighash_with_cache, uint256::ONE);
 268              }
 269  
 270              // Calling the cached version again should return the same value again.
 271              BOOST_CHECK_EQUAL(sighash_with_cache2, SignatureHash(diff_scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, &cache));
 272  
 273              // And if we store a different value for this scriptcode and hash type it will return that instead.
 274              {
 275                  HashWriter h{};
 276                  h << 42;
 277                  cache.Store(hash_type, scriptcode, h);
 278                  const auto stored_hash{h.GetHash()};
 279                  BOOST_CHECK(cache.Load(hash_type, scriptcode, h));
 280                  const auto loaded_hash{h.GetHash()};
 281                  BOOST_CHECK_EQUAL(stored_hash, loaded_hash);
 282              }
 283  
 284              // And using this mutated cache with the sighash function will return the new value (except in the legacy SIGHASH_SINGLE bug
 285              // case in which it'll return 1).
 286              if (!expect_one) {
 287                  BOOST_CHECK_NE(SignatureHash(scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, &cache), sighash_with_cache);
 288                  HashWriter h{};
 289                  BOOST_CHECK(cache.Load(hash_type, scriptcode, h));
 290                  h << hash_type;
 291                  const auto new_hash{h.GetHash()};
 292                  BOOST_CHECK_EQUAL(SignatureHash(scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, &cache), new_hash);
 293              } else {
 294                  BOOST_CHECK_EQUAL(SignatureHash(scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, &cache), uint256::ONE);
 295              }
 296  
 297              // Wipe the cache and restore the correct cached value for this scriptcode and hash_type before starting the next iteration.
 298              HashWriter dummy{};
 299              cache.Store(hash_type, diff_scriptcode, dummy);
 300              (void)SignatureHash(scriptcode, tx, in_index, hash_type, amount, sigversion, nullptr, &cache);
 301              BOOST_CHECK(cache.Load(hash_type, scriptcode, dummy) || expect_one);
 302          }
 303      }
 304  }
 305  
 306  BOOST_AUTO_TEST_SUITE_END()
 307