Line data Source code
1 : // Copyright (c) 2011-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/validation.h>
6 : #include <key.h>
7 : #include <script/sign.h>
8 : #include <script/signingprovider.h>
9 : #include <script/standard.h>
10 : #include <test/util/setup_common.h>
11 : #include <txmempool.h>
12 : #include <validation.h>
13 :
14 : #include <boost/test/unit_test.hpp>
15 :
16 : bool CheckInputScripts(const CTransaction& tx, TxValidationState &state, const CCoinsViewCache &inputs, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks);
17 :
18 89 : BOOST_AUTO_TEST_SUITE(txvalidationcache_tests)
19 :
20 95 : BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup)
21 : {
22 : // Make sure skipping validation of transactions that were
23 : // validated going into the memory pool does not allow
24 : // double-spends in blocks to pass validation when they should not.
25 :
26 1 : CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
27 :
28 4 : const auto ToMemPool = [this](const CMutableTransaction& tx) {
29 3 : LOCK(cs_main);
30 :
31 3 : TxValidationState state;
32 3 : return AcceptToMemoryPool(*m_node.mempool, state, MakeTransactionRef(tx),
33 : nullptr /* plTxnReplaced */, true /* bypass_limits */, 0 /* nAbsurdFee */);
34 3 : };
35 :
36 : // Create a double-spend of mature coinbase txn:
37 1 : std::vector<CMutableTransaction> spends;
38 1 : spends.resize(2);
39 3 : for (int i = 0; i < 2; i++)
40 : {
41 2 : spends[i].nVersion = 1;
42 2 : spends[i].vin.resize(1);
43 2 : spends[i].vin[0].prevout.hash = m_coinbase_txns[0]->GetHash();
44 2 : spends[i].vin[0].prevout.n = 0;
45 2 : spends[i].vout.resize(1);
46 2 : spends[i].vout[0].nValue = 11*CENT;
47 2 : spends[i].vout[0].scriptPubKey = scriptPubKey;
48 :
49 : // Sign:
50 2 : std::vector<unsigned char> vchSig;
51 2 : uint256 hash = SignatureHash(scriptPubKey, spends[i], 0, SIGHASH_ALL, 0, SigVersion::BASE);
52 2 : BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));
53 2 : vchSig.push_back((unsigned char)SIGHASH_ALL);
54 2 : spends[i].vin[0].scriptSig << vchSig;
55 2 : }
56 :
57 1 : CBlock block;
58 :
59 : // Test 1: block with both of those transactions should be rejected.
60 1 : block = CreateAndProcessBlock(spends, scriptPubKey);
61 : {
62 1 : LOCK(cs_main);
63 1 : BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash());
64 1 : }
65 :
66 : // Test 2: ... and should be rejected if spend1 is in the memory pool
67 1 : BOOST_CHECK(ToMemPool(spends[0]));
68 1 : block = CreateAndProcessBlock(spends, scriptPubKey);
69 : {
70 1 : LOCK(cs_main);
71 1 : BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash());
72 1 : }
73 1 : m_node.mempool->clear();
74 :
75 : // Test 3: ... and should be rejected if spend2 is in the memory pool
76 1 : BOOST_CHECK(ToMemPool(spends[1]));
77 1 : block = CreateAndProcessBlock(spends, scriptPubKey);
78 : {
79 1 : LOCK(cs_main);
80 1 : BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash());
81 1 : }
82 1 : m_node.mempool->clear();
83 :
84 : // Final sanity test: first spend in *m_node.mempool, second in block, that's OK:
85 1 : std::vector<CMutableTransaction> oneSpend;
86 1 : oneSpend.push_back(spends[0]);
87 1 : BOOST_CHECK(ToMemPool(spends[1]));
88 1 : block = CreateAndProcessBlock(oneSpend, scriptPubKey);
89 : {
90 1 : LOCK(cs_main);
91 1 : BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() == block.GetHash());
92 1 : }
93 : // spends[1] should have been removed from the mempool when the
94 : // block with spends[0] is accepted:
95 1 : BOOST_CHECK_EQUAL(m_node.mempool->size(), 0U);
96 1 : }
97 :
98 : // Run CheckInputScripts (using CoinsTip()) on the given transaction, for all script
99 : // flags. Test that CheckInputScripts passes for all flags that don't overlap with
100 : // the failing_flags argument, but otherwise fails.
101 : // CHECKLOCKTIMEVERIFY and CHECKSEQUENCEVERIFY (and future NOP codes that may
102 : // get reassigned) have an interaction with DISCOURAGE_UPGRADABLE_NOPS: if
103 : // the script flags used contain DISCOURAGE_UPGRADABLE_NOPS but don't contain
104 : // CHECKLOCKTIMEVERIFY (or CHECKSEQUENCEVERIFY), but the script does contain
105 : // OP_CHECKLOCKTIMEVERIFY (or OP_CHECKSEQUENCEVERIFY), then script execution
106 : // should fail.
107 : // Capture this interaction with the upgraded_nop argument: set it when evaluating
108 : // any script flag that is implemented as an upgraded NOP code.
109 7 : static void ValidateCheckInputsForAllFlags(const CTransaction &tx, uint32_t failing_flags, bool add_to_cache) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
110 : {
111 7 : PrecomputedTransactionData txdata;
112 : // If we add many more flags, this loop can get too expensive, but we can
113 : // rewrite in the future to randomly pick a set of flags to evaluate.
114 129031 : for (uint32_t test_flags=0; test_flags < (1U << 16); test_flags += 1) {
115 129024 : TxValidationState state;
116 : // Filter out incompatible flag choices
117 129024 : if ((test_flags & SCRIPT_VERIFY_CLEANSTACK)) {
118 : // CLEANSTACK requires P2SH and WITNESS, see VerifyScript() in
119 : // script/interpreter.cpp
120 57344 : test_flags |= SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS;
121 57344 : }
122 129024 : if ((test_flags & SCRIPT_VERIFY_WITNESS)) {
123 : // WITNESS requires P2SH
124 100352 : test_flags |= SCRIPT_VERIFY_P2SH;
125 100352 : }
126 129024 : bool ret = CheckInputScripts(tx, state, &::ChainstateActive().CoinsTip(), test_flags, true, add_to_cache, txdata, nullptr);
127 : // CheckInputScripts should succeed iff test_flags doesn't intersect with
128 : // failing_flags
129 129024 : bool expected_return_value = !(test_flags & failing_flags);
130 129024 : BOOST_CHECK_EQUAL(ret, expected_return_value);
131 :
132 : // Test the caching
133 129024 : if (ret && add_to_cache) {
134 : // Check that we get a cache hit if the tx was valid
135 63488 : std::vector<CScriptCheck> scriptchecks;
136 63488 : BOOST_CHECK(CheckInputScripts(tx, state, &::ChainstateActive().CoinsTip(), test_flags, true, add_to_cache, txdata, &scriptchecks));
137 63488 : BOOST_CHECK(scriptchecks.empty());
138 63488 : } else {
139 : // Check that we get script executions to check, if the transaction
140 : // was invalid, or we didn't add to cache.
141 65536 : std::vector<CScriptCheck> scriptchecks;
142 65536 : BOOST_CHECK(CheckInputScripts(tx, state, &::ChainstateActive().CoinsTip(), test_flags, true, add_to_cache, txdata, &scriptchecks));
143 65536 : BOOST_CHECK_EQUAL(scriptchecks.size(), tx.vin.size());
144 65536 : }
145 129024 : }
146 7 : }
147 :
148 95 : BOOST_FIXTURE_TEST_CASE(checkinputs_test, TestChain100Setup)
149 : {
150 : // Test that passing CheckInputScripts with one set of script flags doesn't imply
151 : // that we would pass again with a different set of flags.
152 : {
153 1 : LOCK(cs_main);
154 1 : InitScriptExecutionCache();
155 1 : }
156 :
157 1 : CScript p2pk_scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
158 1 : CScript p2sh_scriptPubKey = GetScriptForDestination(ScriptHash(p2pk_scriptPubKey));
159 1 : CScript p2pkh_scriptPubKey = GetScriptForDestination(PKHash(coinbaseKey.GetPubKey()));
160 1 : CScript p2wpkh_scriptPubKey = GetScriptForDestination(WitnessV0KeyHash(coinbaseKey.GetPubKey()));
161 :
162 1 : FillableSigningProvider keystore;
163 1 : BOOST_CHECK(keystore.AddKey(coinbaseKey));
164 1 : BOOST_CHECK(keystore.AddCScript(p2pk_scriptPubKey));
165 :
166 : // flags to test: SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, SCRIPT_VERIFY_CHECKSEQUENCE_VERIFY, SCRIPT_VERIFY_NULLDUMMY, uncompressed pubkey thing
167 :
168 : // Create 2 outputs that match the three scripts above, spending the first
169 : // coinbase tx.
170 1 : CMutableTransaction spend_tx;
171 :
172 1 : spend_tx.nVersion = 1;
173 1 : spend_tx.vin.resize(1);
174 1 : spend_tx.vin[0].prevout.hash = m_coinbase_txns[0]->GetHash();
175 1 : spend_tx.vin[0].prevout.n = 0;
176 1 : spend_tx.vout.resize(4);
177 1 : spend_tx.vout[0].nValue = 11*CENT;
178 1 : spend_tx.vout[0].scriptPubKey = p2sh_scriptPubKey;
179 1 : spend_tx.vout[1].nValue = 11*CENT;
180 1 : spend_tx.vout[1].scriptPubKey = p2wpkh_scriptPubKey;
181 1 : spend_tx.vout[2].nValue = 11*CENT;
182 1 : spend_tx.vout[2].scriptPubKey = CScript() << OP_CHECKLOCKTIMEVERIFY << OP_DROP << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
183 1 : spend_tx.vout[3].nValue = 11*CENT;
184 1 : spend_tx.vout[3].scriptPubKey = CScript() << OP_CHECKSEQUENCEVERIFY << OP_DROP << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
185 :
186 : // Sign, with a non-DER signature
187 : {
188 1 : std::vector<unsigned char> vchSig;
189 1 : uint256 hash = SignatureHash(p2pk_scriptPubKey, spend_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE);
190 1 : BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));
191 1 : vchSig.push_back((unsigned char) 0); // padding byte makes this non-DER
192 1 : vchSig.push_back((unsigned char)SIGHASH_ALL);
193 1 : spend_tx.vin[0].scriptSig << vchSig;
194 1 : }
195 :
196 : // Test that invalidity under a set of flags doesn't preclude validity
197 : // under other (eg consensus) flags.
198 : // spend_tx is invalid according to DERSIG
199 : {
200 1 : LOCK(cs_main);
201 :
202 1 : TxValidationState state;
203 1 : PrecomputedTransactionData ptd_spend_tx;
204 :
205 1 : BOOST_CHECK(!CheckInputScripts(CTransaction(spend_tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG, true, true, ptd_spend_tx, nullptr));
206 :
207 : // If we call again asking for scriptchecks (as happens in
208 : // ConnectBlock), we should add a script check object for this -- we're
209 : // not caching invalidity (if that changes, delete this test case).
210 1 : std::vector<CScriptCheck> scriptchecks;
211 1 : BOOST_CHECK(CheckInputScripts(CTransaction(spend_tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_DERSIG, true, true, ptd_spend_tx, &scriptchecks));
212 1 : BOOST_CHECK_EQUAL(scriptchecks.size(), 1U);
213 :
214 : // Test that CheckInputScripts returns true iff DERSIG-enforcing flags are
215 : // not present. Don't add these checks to the cache, so that we can
216 : // test later that block validation works fine in the absence of cached
217 : // successes.
218 1 : ValidateCheckInputsForAllFlags(CTransaction(spend_tx), SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC, false);
219 1 : }
220 :
221 : // And if we produce a block with this tx, it should be valid (DERSIG not
222 : // enabled yet), even though there's no cache entry.
223 1 : CBlock block;
224 :
225 1 : block = CreateAndProcessBlock({spend_tx}, p2pk_scriptPubKey);
226 1 : LOCK(cs_main);
227 1 : BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() == block.GetHash());
228 1 : BOOST_CHECK(::ChainstateActive().CoinsTip().GetBestBlock() == block.GetHash());
229 :
230 : // Test P2SH: construct a transaction that is valid without P2SH, and
231 : // then test validity with P2SH.
232 : {
233 1 : CMutableTransaction invalid_under_p2sh_tx;
234 1 : invalid_under_p2sh_tx.nVersion = 1;
235 1 : invalid_under_p2sh_tx.vin.resize(1);
236 1 : invalid_under_p2sh_tx.vin[0].prevout.hash = spend_tx.GetHash();
237 1 : invalid_under_p2sh_tx.vin[0].prevout.n = 0;
238 1 : invalid_under_p2sh_tx.vout.resize(1);
239 1 : invalid_under_p2sh_tx.vout[0].nValue = 11*CENT;
240 1 : invalid_under_p2sh_tx.vout[0].scriptPubKey = p2pk_scriptPubKey;
241 1 : std::vector<unsigned char> vchSig2(p2pk_scriptPubKey.begin(), p2pk_scriptPubKey.end());
242 1 : invalid_under_p2sh_tx.vin[0].scriptSig << vchSig2;
243 :
244 1 : ValidateCheckInputsForAllFlags(CTransaction(invalid_under_p2sh_tx), SCRIPT_VERIFY_P2SH, true);
245 1 : }
246 :
247 : // Test CHECKLOCKTIMEVERIFY
248 : {
249 1 : CMutableTransaction invalid_with_cltv_tx;
250 1 : invalid_with_cltv_tx.nVersion = 1;
251 1 : invalid_with_cltv_tx.nLockTime = 100;
252 1 : invalid_with_cltv_tx.vin.resize(1);
253 1 : invalid_with_cltv_tx.vin[0].prevout.hash = spend_tx.GetHash();
254 1 : invalid_with_cltv_tx.vin[0].prevout.n = 2;
255 1 : invalid_with_cltv_tx.vin[0].nSequence = 0;
256 1 : invalid_with_cltv_tx.vout.resize(1);
257 1 : invalid_with_cltv_tx.vout[0].nValue = 11*CENT;
258 1 : invalid_with_cltv_tx.vout[0].scriptPubKey = p2pk_scriptPubKey;
259 :
260 : // Sign
261 1 : std::vector<unsigned char> vchSig;
262 1 : uint256 hash = SignatureHash(spend_tx.vout[2].scriptPubKey, invalid_with_cltv_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE);
263 1 : BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));
264 1 : vchSig.push_back((unsigned char)SIGHASH_ALL);
265 1 : invalid_with_cltv_tx.vin[0].scriptSig = CScript() << vchSig << 101;
266 :
267 1 : ValidateCheckInputsForAllFlags(CTransaction(invalid_with_cltv_tx), SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, true);
268 :
269 : // Make it valid, and check again
270 1 : invalid_with_cltv_tx.vin[0].scriptSig = CScript() << vchSig << 100;
271 1 : TxValidationState state;
272 1 : PrecomputedTransactionData txdata;
273 1 : BOOST_CHECK(CheckInputScripts(CTransaction(invalid_with_cltv_tx), state, ::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY, true, true, txdata, nullptr));
274 1 : }
275 :
276 : // TEST CHECKSEQUENCEVERIFY
277 : {
278 1 : CMutableTransaction invalid_with_csv_tx;
279 1 : invalid_with_csv_tx.nVersion = 2;
280 1 : invalid_with_csv_tx.vin.resize(1);
281 1 : invalid_with_csv_tx.vin[0].prevout.hash = spend_tx.GetHash();
282 1 : invalid_with_csv_tx.vin[0].prevout.n = 3;
283 1 : invalid_with_csv_tx.vin[0].nSequence = 100;
284 1 : invalid_with_csv_tx.vout.resize(1);
285 1 : invalid_with_csv_tx.vout[0].nValue = 11*CENT;
286 1 : invalid_with_csv_tx.vout[0].scriptPubKey = p2pk_scriptPubKey;
287 :
288 : // Sign
289 1 : std::vector<unsigned char> vchSig;
290 1 : uint256 hash = SignatureHash(spend_tx.vout[3].scriptPubKey, invalid_with_csv_tx, 0, SIGHASH_ALL, 0, SigVersion::BASE);
291 1 : BOOST_CHECK(coinbaseKey.Sign(hash, vchSig));
292 1 : vchSig.push_back((unsigned char)SIGHASH_ALL);
293 1 : invalid_with_csv_tx.vin[0].scriptSig = CScript() << vchSig << 101;
294 :
295 1 : ValidateCheckInputsForAllFlags(CTransaction(invalid_with_csv_tx), SCRIPT_VERIFY_CHECKSEQUENCEVERIFY, true);
296 :
297 : // Make it valid, and check again
298 1 : invalid_with_csv_tx.vin[0].scriptSig = CScript() << vchSig << 100;
299 1 : TxValidationState state;
300 1 : PrecomputedTransactionData txdata;
301 1 : BOOST_CHECK(CheckInputScripts(CTransaction(invalid_with_csv_tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_CHECKSEQUENCEVERIFY, true, true, txdata, nullptr));
302 1 : }
303 :
304 : // TODO: add tests for remaining script flags
305 :
306 : // Test that passing CheckInputScripts with a valid witness doesn't imply success
307 : // for the same tx with a different witness.
308 : {
309 1 : CMutableTransaction valid_with_witness_tx;
310 1 : valid_with_witness_tx.nVersion = 1;
311 1 : valid_with_witness_tx.vin.resize(1);
312 1 : valid_with_witness_tx.vin[0].prevout.hash = spend_tx.GetHash();
313 1 : valid_with_witness_tx.vin[0].prevout.n = 1;
314 1 : valid_with_witness_tx.vout.resize(1);
315 1 : valid_with_witness_tx.vout[0].nValue = 11*CENT;
316 1 : valid_with_witness_tx.vout[0].scriptPubKey = p2pk_scriptPubKey;
317 :
318 : // Sign
319 1 : SignatureData sigdata;
320 1 : BOOST_CHECK(ProduceSignature(keystore, MutableTransactionSignatureCreator(&valid_with_witness_tx, 0, 11*CENT, SIGHASH_ALL), spend_tx.vout[1].scriptPubKey, sigdata));
321 1 : UpdateInput(valid_with_witness_tx.vin[0], sigdata);
322 :
323 : // This should be valid under all script flags.
324 1 : ValidateCheckInputsForAllFlags(CTransaction(valid_with_witness_tx), 0, true);
325 :
326 : // Remove the witness, and check that it is now invalid.
327 1 : valid_with_witness_tx.vin[0].scriptWitness.SetNull();
328 1 : ValidateCheckInputsForAllFlags(CTransaction(valid_with_witness_tx), SCRIPT_VERIFY_WITNESS, true);
329 1 : }
330 :
331 : {
332 : // Test a transaction with multiple inputs.
333 1 : CMutableTransaction tx;
334 :
335 1 : tx.nVersion = 1;
336 1 : tx.vin.resize(2);
337 1 : tx.vin[0].prevout.hash = spend_tx.GetHash();
338 1 : tx.vin[0].prevout.n = 0;
339 1 : tx.vin[1].prevout.hash = spend_tx.GetHash();
340 1 : tx.vin[1].prevout.n = 1;
341 1 : tx.vout.resize(1);
342 1 : tx.vout[0].nValue = 22*CENT;
343 1 : tx.vout[0].scriptPubKey = p2pk_scriptPubKey;
344 :
345 : // Sign
346 3 : for (int i=0; i<2; ++i) {
347 2 : SignatureData sigdata;
348 2 : BOOST_CHECK(ProduceSignature(keystore, MutableTransactionSignatureCreator(&tx, i, 11*CENT, SIGHASH_ALL), spend_tx.vout[i].scriptPubKey, sigdata));
349 2 : UpdateInput(tx.vin[i], sigdata);
350 2 : }
351 :
352 : // This should be valid under all script flags
353 1 : ValidateCheckInputsForAllFlags(CTransaction(tx), 0, true);
354 :
355 : // Check that if the second input is invalid, but the first input is
356 : // valid, the transaction is not cached.
357 : // Invalidate vin[1]
358 1 : tx.vin[1].scriptWitness.SetNull();
359 :
360 1 : TxValidationState state;
361 1 : PrecomputedTransactionData txdata;
362 : // This transaction is now invalid under segwit, because of the second input.
363 1 : BOOST_CHECK(!CheckInputScripts(CTransaction(tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true, true, txdata, nullptr));
364 :
365 1 : std::vector<CScriptCheck> scriptchecks;
366 : // Make sure this transaction was not cached (ie because the first
367 : // input was valid)
368 1 : BOOST_CHECK(CheckInputScripts(CTransaction(tx), state, &::ChainstateActive().CoinsTip(), SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS, true, true, txdata, &scriptchecks));
369 : // Should get 2 script checks back -- caching is on a whole-transaction basis.
370 1 : BOOST_CHECK_EQUAL(scriptchecks.size(), 2U);
371 1 : }
372 1 : }
373 :
374 89 : BOOST_AUTO_TEST_SUITE_END()
|