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