Bitcoin Core  25.99.0
P2P Digital Currency
sighash_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2013-2022 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 
5 #include <common/system.h>
6 #include <consensus/tx_check.h>
7 #include <consensus/validation.h>
8 #include <hash.h>
9 #include <script/interpreter.h>
10 #include <script/script.h>
11 #include <serialize.h>
12 #include <streams.h>
13 #include <test/data/sighash.json.h>
14 #include <test/util/json.h>
15 #include <test/util/random.h>
16 #include <test/util/setup_common.h>
17 #include <util/strencodings.h>
18 #include <version.h>
19 
20 #include <iostream>
21 
22 #include <boost/test/unit_test.hpp>
23 
24 #include <univalue.h>
25 
26 // Old script.cpp SignatureHash function
27 uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
28 {
29  if (nIn >= txTo.vin.size())
30  {
31  return uint256::ONE;
32  }
33  CMutableTransaction txTmp(txTo);
34 
35  // In case concatenating two scripts ends up with two codeseparators,
36  // or an extra one at the end, this prevents all those possible incompatibilities.
38 
39  // Blank out other inputs' signatures
40  for (unsigned int i = 0; i < txTmp.vin.size(); i++)
41  txTmp.vin[i].scriptSig = CScript();
42  txTmp.vin[nIn].scriptSig = scriptCode;
43 
44  // Blank out some of the outputs
45  if ((nHashType & 0x1f) == SIGHASH_NONE)
46  {
47  // Wildcard payee
48  txTmp.vout.clear();
49 
50  // Let the others update at will
51  for (unsigned int i = 0; i < txTmp.vin.size(); i++)
52  if (i != nIn)
53  txTmp.vin[i].nSequence = 0;
54  }
55  else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
56  {
57  // Only lock-in the txout payee at same index as txin
58  unsigned int nOut = nIn;
59  if (nOut >= txTmp.vout.size())
60  {
61  return uint256::ONE;
62  }
63  txTmp.vout.resize(nOut+1);
64  for (unsigned int i = 0; i < nOut; i++)
65  txTmp.vout[i].SetNull();
66 
67  // Let the others update at will
68  for (unsigned int i = 0; i < txTmp.vin.size(); i++)
69  if (i != nIn)
70  txTmp.vin[i].nSequence = 0;
71  }
72 
73  // Blank out other inputs completely, not recommended for open transactions
74  if (nHashType & SIGHASH_ANYONECANPAY)
75  {
76  txTmp.vin[0] = txTmp.vin[nIn];
77  txTmp.vin.resize(1);
78  }
79 
80  // Serialize and hash
82  ss << txTmp << nHashType;
83  return ss.GetHash();
84 }
85 
86 void static RandomScript(CScript &script) {
88  script = CScript();
89  int ops = (InsecureRandRange(10));
90  for (int i=0; i<ops; i++)
91  script << oplist[InsecureRandRange(std::size(oplist))];
92 }
93 
94 void static RandomTransaction(CMutableTransaction& tx, bool fSingle)
95 {
96  tx.nVersion = int(InsecureRand32());
97  tx.vin.clear();
98  tx.vout.clear();
99  tx.nLockTime = (InsecureRandBool()) ? InsecureRand32() : 0;
100  int ins = (InsecureRandBits(2)) + 1;
101  int outs = fSingle ? ins : (InsecureRandBits(2)) + 1;
102  for (int in = 0; in < ins; in++) {
103  tx.vin.push_back(CTxIn());
104  CTxIn &txin = tx.vin.back();
105  txin.prevout.hash = InsecureRand256();
106  txin.prevout.n = InsecureRandBits(2);
107  RandomScript(txin.scriptSig);
108  txin.nSequence = (InsecureRandBool()) ? InsecureRand32() : std::numeric_limits<uint32_t>::max();
109  }
110  for (int out = 0; out < outs; out++) {
111  tx.vout.push_back(CTxOut());
112  CTxOut &txout = tx.vout.back();
114  RandomScript(txout.scriptPubKey);
115  }
116 }
117 
118 BOOST_FIXTURE_TEST_SUITE(sighash_tests, BasicTestingSetup)
119 
120 BOOST_AUTO_TEST_CASE(sighash_test)
121 {
122  #if defined(PRINT_SIGHASH_JSON)
123  std::cout << "[\n";
124  std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
125  int nRandomTests = 500;
126  #else
127  int nRandomTests = 50000;
128  #endif
129  for (int i=0; i<nRandomTests; i++) {
130  int nHashType{int(InsecureRand32())};
131  CMutableTransaction txTo;
132  RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
133  CScript scriptCode;
134  RandomScript(scriptCode);
135  int nIn = InsecureRandRange(txTo.vin.size());
136 
137  uint256 sh, sho;
138  sho = SignatureHashOld(scriptCode, CTransaction(txTo), nIn, nHashType);
139  sh = SignatureHash(scriptCode, txTo, nIn, nHashType, 0, SigVersion::BASE);
140  #if defined(PRINT_SIGHASH_JSON)
142  ss << txTo;
143 
144  std::cout << "\t[\"" ;
145  std::cout << HexStr(ss) << "\", \"";
146  std::cout << HexStr(scriptCode) << "\", ";
147  std::cout << nIn << ", ";
148  std::cout << nHashType << ", \"";
149  std::cout << sho.GetHex() << "\"]";
150  if (i+1 != nRandomTests) {
151  std::cout << ",";
152  }
153  std::cout << "\n";
154  #endif
155  BOOST_CHECK(sh == sho);
156  }
157  #if defined(PRINT_SIGHASH_JSON)
158  std::cout << "]\n";
159  #endif
160 }
161 
162 // Goal: check that SignatureHash generates correct hash
163 BOOST_AUTO_TEST_CASE(sighash_from_data)
164 {
165  UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));
166 
167  for (unsigned int idx = 0; idx < tests.size(); idx++) {
168  const UniValue& test = tests[idx];
169  std::string strTest = test.write();
170  if (test.size() < 1) // Allow for extra stuff (useful for comments)
171  {
172  BOOST_ERROR("Bad test: " << strTest);
173  continue;
174  }
175  if (test.size() == 1) continue; // comment
176 
177  std::string raw_tx, raw_script, sigHashHex;
178  int nIn, nHashType;
179  uint256 sh;
180  CTransactionRef tx;
181  CScript scriptCode = CScript();
182 
183  try {
184  // deserialize test data
185  raw_tx = test[0].get_str();
186  raw_script = test[1].get_str();
187  nIn = test[2].getInt<int>();
188  nHashType = test[3].getInt<int>();
189  sigHashHex = test[4].get_str();
190 
192  stream >> tx;
193 
194  TxValidationState state;
195  BOOST_CHECK_MESSAGE(CheckTransaction(*tx, state), strTest);
196  BOOST_CHECK(state.IsValid());
197 
198  std::vector<unsigned char> raw = ParseHex(raw_script);
199  scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
200  } catch (...) {
201  BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest);
202  continue;
203  }
204 
205  sh = SignatureHash(scriptCode, *tx, nIn, nHashType, 0, SigVersion::BASE);
206  BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
207  }
208 }
uint32_t n
Definition: transaction.h:39
uint256 hash
Definition: transaction.h:38
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:411
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:295
const std::vector< CTxIn > vin
Definition: transaction.h:305
An input of a transaction.
Definition: transaction.h:75
uint32_t nSequence
Definition: transaction.h:79
CScript scriptSig
Definition: transaction.h:78
COutPoint prevout
Definition: transaction.h:77
An output of a transaction.
Definition: transaction.h:158
CScript scriptPubKey
Definition: transaction.h:161
CAmount nValue
Definition: transaction.h:160
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition: hash.h:116
const std::string & get_str() const
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
size_t size() const
Definition: univalue.h:68
Int getInt() const
Definition: univalue.h:137
bool IsValid() const
Definition: validation.h:121
std::string GetHex() const
Definition: uint256.cpp:11
iterator end()
Definition: prevector.h:294
iterator insert(iterator pos, const T &value)
Definition: prevector.h:349
256-bit opaque blob.
Definition: uint256.h:105
static const uint256 ONE
Definition: uint256.h:111
BOOST_AUTO_TEST_SUITE_END()
int FindAndDelete(CScript &script, const CScript &b)
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache)
@ BASE
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
@ SIGHASH_ANYONECANPAY
Definition: interpreter.h:31
@ SIGHASH_NONE
Definition: interpreter.h:29
@ SIGHASH_SINGLE
Definition: interpreter.h:30
UniValue read_json(const std::string &jsondata)
Definition: json.cpp:12
#define BOOST_CHECK(expr)
Definition: object.cpp:17
static const int SERIALIZE_TRANSACTION_NO_WITNESS
A flag that is ORed into the protocol version to designate that a transaction should be (un)serialize...
Definition: transaction.h:32
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:421
opcodetype
Script opcodes.
Definition: script.h:70
@ OP_2
Definition: script.h:81
@ OP_IF
Definition: script.h:100
@ OP_CHECKSIG
Definition: script.h:186
@ OP_VERIF
Definition: script.h:102
@ OP_CODESEPARATOR
Definition: script.h:185
@ OP_FALSE
Definition: script.h:73
@ OP_1
Definition: script.h:79
@ OP_3
Definition: script.h:82
@ OP_RETURN
Definition: script.h:107
@ SER_NETWORK
Definition: serialize.h:131
@ SER_GETHASH
Definition: serialize.h:133
static uint256 SignatureHashOld(CScript scriptCode, const CTransaction &txTo, unsigned int nIn, int nHashType)
static void RandomTransaction(CMutableTransaction &tx, bool fSingle)
BOOST_AUTO_TEST_CASE(sighash_test)
static void RandomScript(CScript &script)
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:65
Basic testing setup.
Definition: setup_common.h:80
A mutable version of CTransaction.
Definition: transaction.h:380
std::vector< CTxOut > vout
Definition: transaction.h:382
std::vector< CTxIn > vin
Definition: transaction.h:381
static CAmount InsecureRandMoneyAmount()
Definition: random.h:40
static uint64_t InsecureRandRange(uint64_t range)
Definition: random.h:30
static uint256 InsecureRand256()
Definition: random.h:20
static uint64_t InsecureRandBits(int bits)
Definition: random.h:25
static uint32_t InsecureRand32()
Definition: random.h:15
static bool InsecureRandBool()
Definition: random.h:35
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:11
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12