Bitcoin Core  22.99.0
P2P Digital Currency
sighash_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2013-2020 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 <consensus/tx_check.h>
6 #include <consensus/validation.h>
7 #include <hash.h>
8 #include <script/interpreter.h>
9 #include <script/script.h>
10 #include <serialize.h>
11 #include <streams.h>
12 #include <test/data/sighash.json.h>
13 #include <test/util/setup_common.h>
14 #include <util/strencodings.h>
15 #include <util/system.h>
16 #include <version.h>
17 
18 #include <iostream>
19 
20 #include <boost/test/unit_test.hpp>
21 
22 #include <univalue.h>
23 
24 UniValue read_json(const std::string& jsondata);
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  tx.nVersion = InsecureRand32();
96  tx.vin.clear();
97  tx.vout.clear();
98  tx.nLockTime = (InsecureRandBool()) ? InsecureRand32() : 0;
99  int ins = (InsecureRandBits(2)) + 1;
100  int outs = fSingle ? ins : (InsecureRandBits(2)) + 1;
101  for (int in = 0; in < ins; in++) {
102  tx.vin.push_back(CTxIn());
103  CTxIn &txin = tx.vin.back();
104  txin.prevout.hash = InsecureRand256();
105  txin.prevout.n = InsecureRandBits(2);
106  RandomScript(txin.scriptSig);
107  txin.nSequence = (InsecureRandBool()) ? InsecureRand32() : std::numeric_limits<uint32_t>::max();
108  }
109  for (int out = 0; out < outs; out++) {
110  tx.vout.push_back(CTxOut());
111  CTxOut &txout = tx.vout.back();
112  txout.nValue = InsecureRandRange(100000000);
113  RandomScript(txout.scriptPubKey);
114  }
115 }
116 
118 
119 BOOST_AUTO_TEST_CASE(sighash_test)
120 {
121  #if defined(PRINT_SIGHASH_JSON)
122  std::cout << "[\n";
123  std::cout << "\t[\"raw_transaction, script, input_index, hashType, signature_hash (result)\"],\n";
124  int nRandomTests = 500;
125  #else
126  int nRandomTests = 50000;
127  #endif
128  for (int i=0; i<nRandomTests; i++) {
129  int nHashType = InsecureRand32();
130  CMutableTransaction txTo;
131  RandomTransaction(txTo, (nHashType & 0x1f) == SIGHASH_SINGLE);
132  CScript scriptCode;
133  RandomScript(scriptCode);
134  int nIn = InsecureRandRange(txTo.vin.size());
135 
136  uint256 sh, sho;
137  sho = SignatureHashOld(scriptCode, CTransaction(txTo), nIn, nHashType);
138  sh = SignatureHash(scriptCode, txTo, nIn, nHashType, 0, SigVersion::BASE);
139  #if defined(PRINT_SIGHASH_JSON)
141  ss << txTo;
142 
143  std::cout << "\t[\"" ;
144  std::cout << HexStr(ss) << "\", \"";
145  std::cout << HexStr(scriptCode) << "\", ";
146  std::cout << nIn << ", ";
147  std::cout << nHashType << ", \"";
148  std::cout << sho.GetHex() << "\"]";
149  if (i+1 != nRandomTests) {
150  std::cout << ",";
151  }
152  std::cout << "\n";
153  #endif
154  BOOST_CHECK(sh == sho);
155  }
156  #if defined(PRINT_SIGHASH_JSON)
157  std::cout << "]\n";
158  #endif
159 }
160 
161 // Goal: check that SignatureHash generates correct hash
162 BOOST_AUTO_TEST_CASE(sighash_from_data)
163 {
164  UniValue tests = read_json(std::string(json_tests::sighash, json_tests::sighash + sizeof(json_tests::sighash)));
165 
166  for (unsigned int idx = 0; idx < tests.size(); idx++) {
167  UniValue test = tests[idx];
168  std::string strTest = test.write();
169  if (test.size() < 1) // Allow for extra stuff (useful for comments)
170  {
171  BOOST_ERROR("Bad test: " << strTest);
172  continue;
173  }
174  if (test.size() == 1) continue; // comment
175 
176  std::string raw_tx, raw_script, sigHashHex;
177  int nIn, nHashType;
178  uint256 sh;
179  CTransactionRef tx;
180  CScript scriptCode = CScript();
181 
182  try {
183  // deserialize test data
184  raw_tx = test[0].get_str();
185  raw_script = test[1].get_str();
186  nIn = test[2].get_int();
187  nHashType = test[3].get_int();
188  sigHashHex = test[4].get_str();
189 
191  stream >> tx;
192 
193  TxValidationState state;
194  BOOST_CHECK_MESSAGE(CheckTransaction(*tx, state), strTest);
195  BOOST_CHECK(state.IsValid());
196 
197  std::vector<unsigned char> raw = ParseHex(raw_script);
198  scriptCode.insert(scriptCode.end(), raw.begin(), raw.end());
199  } catch (...) {
200  BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest);
201  continue;
202  }
203 
204  sh = SignatureHash(scriptCode, *tx, nIn, nHashType, 0, SigVersion::BASE);
205  BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest);
206  }
207 }
CTxIn
An input of a transaction.
Definition: transaction.h:65
CMutableTransaction::vin
std::vector< CTxIn > vin
Definition: transaction.h:346
CTransaction::vin
const std::vector< CTxIn > vin
Definition: transaction.h:270
prevector::insert
iterator insert(iterator pos, const T &value)
Definition: prevector.h:347
FindAndDelete
int FindAndDelete(CScript &script, const CScript &b)
Definition: interpreter.cpp:253
ParseHex
std::vector< unsigned char > ParseHex(const char *psz)
Definition: strencodings.cpp:84
InsecureRandBool
static bool InsecureRandBool()
Definition: setup_common.h:69
SigVersion::BASE
@ BASE
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
streams.h
setup_common.h
RandomScript
static void RandomScript(CScript &script)
Definition: sighash_tests.cpp:86
COutPoint::hash
uint256 hash
Definition: transaction.h:29
CMutableTransaction::nVersion
int32_t nVersion
Definition: transaction.h:348
InsecureRand256
static uint256 InsecureRand256()
Definition: setup_common.h:66
InsecureRandRange
static uint64_t InsecureRandRange(uint64_t range)
Definition: setup_common.h:68
validation.h
SIGHASH_SINGLE
@ SIGHASH_SINGLE
Definition: interpreter.h:29
interpreter.h
opcodetype
opcodetype
Script opcodes.
Definition: script.h:66
OP_3
@ OP_3
Definition: script.h:79
InsecureRand32
static uint32_t InsecureRand32()
Definition: setup_common.h:65
SIGHASH_NONE
@ SIGHASH_NONE
Definition: interpreter.h:28
CheckTransaction
bool CheckTransaction(const CTransaction &tx, TxValidationState &state)
Definition: tx_check.cpp:10
UniValue::write
std::string write(unsigned int prettyIndent=0, unsigned int indentLevel=0) const
Definition: univalue_write.cpp:29
CTransactionRef
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:386
BOOST_FIXTURE_TEST_SUITE
#define BOOST_FIXTURE_TEST_SUITE(a, b)
Definition: object.cpp:14
version.h
BOOST_AUTO_TEST_SUITE_END
BOOST_AUTO_TEST_SUITE_END()
UniValue
Definition: univalue.h:19
CTransaction
The basic transaction that is broadcasted on the network and contained in blocks.
Definition: transaction.h:259
OP_FALSE
@ OP_FALSE
Definition: script.h:70
CTxIn::nSequence
uint32_t nSequence
Definition: transaction.h:70
ValidationState::IsValid
bool IsValid() const
Definition: validation.h:119
TxValidationState
Definition: validation.h:139
CTxOut::nValue
CAmount nValue
Definition: transaction.h:131
OP_1
@ OP_1
Definition: script.h:76
UniValue::get_str
const std::string & get_str() const
Definition: univalue_get.cpp:97
prevector::end
iterator end()
Definition: prevector.h:292
strencodings.h
OP_RETURN
@ OP_RETURN
Definition: script.h:104
CMutableTransaction::nLockTime
uint32_t nLockTime
Definition: transaction.h:349
OP_IF
@ OP_IF
Definition: script.h:97
SIGHASH_ANYONECANPAY
@ SIGHASH_ANYONECANPAY
Definition: interpreter.h:30
CTxOut
An output of a transaction.
Definition: transaction.h:128
CTxOut::scriptPubKey
CScript scriptPubKey
Definition: transaction.h:132
univalue.h
base_blob::GetHex
std::string GetHex() const
Definition: uint256.cpp:20
SERIALIZE_TRANSACTION_NO_WITNESS
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:23
BasicTestingSetup
Basic testing setup.
Definition: setup_common.h:76
OP_2
@ OP_2
Definition: script.h:78
OP_CODESEPARATOR
@ OP_CODESEPARATOR
Definition: script.h:182
uint256
256-bit opaque blob.
Definition: uint256.h:124
CScript
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
script.h
read_json
UniValue read_json(const std::string &jsondata)
Definition: script_tests.cpp:42
system.h
CMutableTransaction::vout
std::vector< CTxOut > vout
Definition: transaction.h:347
UniValue::get_int
int get_int() const
Definition: univalue_get.cpp:104
SignatureHash
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache)
Definition: interpreter.cpp:1590
COutPoint::n
uint32_t n
Definition: transaction.h:30
SignatureHashOld
static uint256 SignatureHashOld(CScript scriptCode, const CTransaction &txTo, unsigned int nIn, int nHashType)
Definition: sighash_tests.cpp:27
CTxIn::prevout
COutPoint prevout
Definition: transaction.h:68
CHashWriter
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:100
CTxIn::scriptSig
CScript scriptSig
Definition: transaction.h:69
serialize.h
CDataStream
Double ended buffer combining vector and stream-like interfaces.
Definition: streams.h:204
InsecureRandBits
static uint64_t InsecureRandBits(int bits)
Definition: setup_common.h:67
SER_NETWORK
@ SER_NETWORK
Definition: serialize.h:138
UniValue::size
size_t size() const
Definition: univalue.h:68
RandomTransaction
static void RandomTransaction(CMutableTransaction &tx, bool fSingle)
Definition: sighash_tests.cpp:94
OP_VERIF
@ OP_VERIF
Definition: script.h:99
CMutableTransaction
A mutable version of CTransaction.
Definition: transaction.h:344
CHashWriter::GetHash
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition: hash.h:122
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:594
OP_CHECKSIG
@ OP_CHECKSIG
Definition: script.h:183
tx_check.h
SER_GETHASH
@ SER_GETHASH
Definition: serialize.h:140
BOOST_CHECK
#define BOOST_CHECK(expr)
Definition: object.cpp:17
PROTOCOL_VERSION
static const int PROTOCOL_VERSION
network protocol versioning
Definition: version.h:12
uint256::ONE
static const uint256 ONE
Definition: uint256.h:130
BOOST_AUTO_TEST_CASE
BOOST_AUTO_TEST_CASE(sighash_test)
Definition: sighash_tests.cpp:119