Branch data Line data Source code
1 : : // Copyright (c) 2018-present 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 <boost/test/unit_test.hpp>
6 : :
7 : : #include <chainparams.h>
8 : : #include <consensus/merkle.h>
9 : : #include <consensus/validation.h>
10 : : #include <node/miner.h>
11 : : #include <pow.h>
12 : : #include <random.h>
13 : : #include <test/util/random.h>
14 : : #include <test/util/script.h>
15 : : #include <test/util/setup_common.h>
16 : : #include <util/time.h>
17 : : #include <validation.h>
18 : : #include <validationinterface.h>
19 : :
20 : : #include <thread>
21 : :
22 : : using kernel::ChainstateRole;
23 : : using node::BlockAssembler;
24 : :
25 : : namespace validation_block_tests {
26 : 9 : struct MinerTestingSetup : public RegTestingSetup {
27 : : std::shared_ptr<CBlock> Block(const uint256& prev_hash);
28 : : std::shared_ptr<const CBlock> GoodBlock(const uint256& prev_hash);
29 : : std::shared_ptr<const CBlock> BadBlock(const uint256& prev_hash);
30 : : std::shared_ptr<CBlock> FinalizeBlock(std::shared_ptr<CBlock> pblock);
31 : : void BuildChain(const uint256& root, int height, unsigned int invalid_rate, unsigned int branch_rate, unsigned int max_size, std::vector<std::shared_ptr<const CBlock>>& blocks);
32 : : };
33 : : } // namespace validation_block_tests
34 : :
35 : : BOOST_FIXTURE_TEST_SUITE(validation_block_tests, MinerTestingSetup)
36 : :
37 : : struct TestSubscriber final : public CValidationInterface {
38 : : uint256 m_expected_tip;
39 : :
40 : 1 : explicit TestSubscriber(uint256 tip) : m_expected_tip(tip) {}
41 : :
42 : 30 : void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override
43 : : {
44 [ + - ]: 30 : BOOST_CHECK_EQUAL(m_expected_tip, pindexNew->GetBlockHash());
45 : 30 : }
46 : :
47 : 42 : void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
48 : : {
49 [ + - ]: 42 : BOOST_CHECK_EQUAL(m_expected_tip, block->hashPrevBlock);
50 [ + - ]: 42 : BOOST_CHECK_EQUAL(m_expected_tip, pindex->pprev->GetBlockHash());
51 : :
52 : 42 : m_expected_tip = block->GetHash();
53 : 42 : }
54 : :
55 : 12 : void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
56 : : {
57 [ + - ]: 12 : BOOST_CHECK_EQUAL(m_expected_tip, block->GetHash());
58 [ + - ]: 12 : BOOST_CHECK_EQUAL(m_expected_tip, pindex->GetBlockHash());
59 : :
60 : 12 : m_expected_tip = block->hashPrevBlock;
61 : 12 : }
62 : : };
63 : :
64 : 840 : std::shared_ptr<CBlock> MinerTestingSetup::Block(const uint256& prev_hash)
65 : : {
66 : 840 : static int i = 0;
67 [ + + + - : 840 : static uint64_t time = Params().GenesisBlock().nTime;
+ - ]
68 : :
69 : 840 : BlockAssembler::Options options;
70 [ + - + - ]: 840 : options.coinbase_output_script = CScript{} << i++ << OP_TRUE;
71 : 840 : options.include_dummy_extranonce = true;
72 [ + - + - : 840 : auto ptemplate = BlockAssembler{m_node.chainman->ActiveChainstate(), m_node.mempool.get(), options}.CreateNewBlock();
+ - ]
73 [ + - ]: 840 : auto pblock = std::make_shared<CBlock>(ptemplate->block);
74 [ + - ]: 840 : pblock->hashPrevBlock = prev_hash;
75 : 840 : pblock->nTime = ++time;
76 : :
77 : : // Make the coinbase transaction with two outputs:
78 : : // One zero-value one that has a unique pubkey to make sure that blocks at the same height can have a different hash
79 : : // Another one that has the coinbase reward in a P2WSH with OP_TRUE as witness program to make it easy to spend
80 [ + - ]: 840 : CMutableTransaction txCoinbase(*pblock->vtx[0]);
81 [ + - ]: 840 : txCoinbase.vout.resize(2);
82 : 840 : txCoinbase.vout[1].scriptPubKey = P2WSH_OP_TRUE;
83 : 840 : txCoinbase.vout[1].nValue = txCoinbase.vout[0].nValue;
84 : 840 : txCoinbase.vout[0].nValue = 0;
85 : 840 : txCoinbase.vin[0].scriptWitness.SetNull();
86 : : // Always pad with OP_0 as dummy extraNonce (also avoids bad-cb-length error for block <=16)
87 [ + - + - : 2520 : const int prev_height{WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(prev_hash)->nHeight)};
+ - ]
88 [ + - + - ]: 840 : txCoinbase.vin[0].scriptSig = CScript{} << prev_height + 1 << OP_0;
89 : 840 : txCoinbase.nLockTime = static_cast<uint32_t>(prev_height);
90 [ + - - + ]: 1680 : pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
91 : :
92 : 840 : return pblock;
93 : 840 : }
94 : :
95 : 840 : std::shared_ptr<CBlock> MinerTestingSetup::FinalizeBlock(std::shared_ptr<CBlock> pblock)
96 : : {
97 [ + - + - ]: 2520 : const CBlockIndex* prev_block{WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};
98 : 840 : m_node.chainman->GenerateCoinbaseCommitment(*pblock, prev_block);
99 : :
100 : 840 : pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
101 : :
102 [ + + ]: 1650 : while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
103 : 810 : ++(pblock->nNonce);
104 : : }
105 : :
106 : : // submit block header, so that miner can get the block height from the
107 : : // global state and the node has the topology of the chain
108 [ + - ]: 840 : BlockValidationState ignored;
109 [ + - - + : 1680 : BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlockHeaders({{*pblock}}, true, ignored));
+ - + - ]
110 : :
111 : 840 : return pblock;
112 : 840 : }
113 : :
114 : : // construct a valid block
115 : 825 : std::shared_ptr<const CBlock> MinerTestingSetup::GoodBlock(const uint256& prev_hash)
116 : : {
117 [ + - - + : 825 : return FinalizeBlock(Block(prev_hash));
- + ]
118 : : }
119 : :
120 : : // construct an invalid block (but with a valid header)
121 : 15 : std::shared_ptr<const CBlock> MinerTestingSetup::BadBlock(const uint256& prev_hash)
122 : : {
123 : 15 : auto pblock = Block(prev_hash);
124 : :
125 [ + - ]: 15 : CMutableTransaction coinbase_spend;
126 [ + - ]: 15 : coinbase_spend.vin.emplace_back(COutPoint(pblock->vtx[0]->GetHash(), 0), CScript(), 0);
127 [ + - ]: 15 : coinbase_spend.vout.push_back(pblock->vtx[0]->vout[0]);
128 : :
129 [ + - ]: 15 : CTransactionRef tx = MakeTransactionRef(coinbase_spend);
130 [ + - ]: 15 : pblock->vtx.push_back(tx);
131 : :
132 [ + - + - ]: 30 : auto ret = FinalizeBlock(pblock);
133 [ - + ]: 15 : return ret;
134 [ + - + - ]: 60 : }
135 : :
136 : : // NOLINTNEXTLINE(misc-no-recursion)
137 : 87 : void MinerTestingSetup::BuildChain(const uint256& root, int height, const unsigned int invalid_rate, const unsigned int branch_rate, const unsigned int max_size, std::vector<std::shared_ptr<const CBlock>>& blocks)
138 : : {
139 [ + - + - ]: 174 : if (height <= 0 || blocks.size() >= max_size) return;
140 : :
141 : 87 : bool gen_invalid = m_rng.randrange(100U) < invalid_rate;
142 : 87 : bool gen_fork = m_rng.randrange(100U) < branch_rate;
143 : :
144 [ + + ]: 87 : const std::shared_ptr<const CBlock> pblock = gen_invalid ? BadBlock(root) : GoodBlock(root);
145 [ + - ]: 87 : blocks.push_back(pblock);
146 [ + + ]: 87 : if (!gen_invalid) {
147 [ + - + - ]: 72 : BuildChain(pblock->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
148 : : }
149 : :
150 [ + + ]: 87 : if (gen_fork) {
151 [ + - - + ]: 28 : blocks.push_back(GoodBlock(root));
152 [ + - + - ]: 14 : BuildChain(blocks.back()->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
153 : : }
154 : 87 : }
155 : :
156 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
157 : : {
158 : : // build a large-ish chain that's likely to have some forks
159 : 1 : std::vector<std::shared_ptr<const CBlock>> blocks;
160 [ - + + + ]: 2 : while (blocks.size() < 50) {
161 : 1 : blocks.clear();
162 [ + - + - : 1 : BuildChain(Params().GenesisBlock().GetHash(), 100, 15, 10, 500, blocks);
+ - ]
163 : : }
164 : :
165 : 1 : bool ignored;
166 : : // Connect the genesis block and drain any outstanding events
167 [ + - - + : 3 : BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlock(std::make_shared<CBlock>(Params().GenesisBlock()), true, true, &ignored));
+ - + - +
- + - + -
- + + - ]
168 [ + - ]: 1 : m_node.validation_signals->SyncWithValidationInterfaceQueue();
169 : :
170 : : // subscribe to events (this subscriber will validate event ordering)
171 : 1 : const CBlockIndex* initial_tip = nullptr;
172 : 1 : {
173 [ + - ]: 1 : LOCK(cs_main);
174 [ + - - + : 2 : initial_tip = m_node.chainman->ActiveChain().Tip();
+ - ]
175 : 0 : }
176 [ + - ]: 1 : auto sub = std::make_shared<TestSubscriber>(initial_tip->GetBlockHash());
177 [ + - + - ]: 2 : m_node.validation_signals->RegisterSharedValidationInterface(sub);
178 : :
179 : : // create a bunch of threads that repeatedly process a block generated above at random
180 : : // this will create parallelism and randomness inside validation - the ValidationInterface
181 : : // will subscribe to events generated during block validation and assert on ordering invariance
182 : 1 : std::vector<std::thread> threads;
183 [ + - ]: 1 : threads.reserve(10);
184 [ + + ]: 11 : for (int i = 0; i < 10; i++) {
185 [ + - ]: 20 : threads.emplace_back([&]() {
186 : 10 : bool ignored;
187 : 10 : FastRandomContext insecure;
188 [ + + ]: 10010 : for (int i = 0; i < 1000; i++) {
189 [ - + - + ]: 10000 : const auto& block = blocks[insecure.randrange(blocks.size() - 1)];
190 [ - + + - ]: 10000 : Assert(m_node.chainman)->ProcessNewBlock(block, true, true, &ignored);
191 : : }
192 : :
193 : : // to make sure that eventually we process the full chain - do it here
194 [ + + ]: 1020 : for (const auto& block : blocks) {
195 [ - + + + ]: 1010 : if (block->vtx.size() == 1) {
196 [ - + + - ]: 860 : bool processed = Assert(m_node.chainman)->ProcessNewBlock(block, true, true, &ignored);
197 [ - + ]: 860 : assert(processed);
198 : : }
199 : : }
200 : 10 : });
201 : : }
202 : :
203 [ + + ]: 11 : for (auto& t : threads) {
204 [ + - ]: 10 : t.join();
205 : : }
206 [ + - ]: 1 : m_node.validation_signals->SyncWithValidationInterfaceQueue();
207 : :
208 [ + - + - ]: 2 : m_node.validation_signals->UnregisterSharedValidationInterface(sub);
209 : :
210 [ + - ]: 1 : LOCK(cs_main);
211 [ + - + - : 2 : BOOST_CHECK_EQUAL(sub->m_expected_tip, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
- + + - +
- ]
212 [ + - ]: 2 : }
213 : :
214 : : /**
215 : : * Test that mempool updates happen atomically with reorgs.
216 : : *
217 : : * This prevents RPC clients, among others, from retrieving immediately-out-of-date mempool data
218 : : * during large reorgs.
219 : : *
220 : : * The test verifies this by creating a chain of `num_txs` blocks, matures their coinbases, and then
221 : : * submits txns spending from their coinbase to the mempool. A fork chain is then processed,
222 : : * invalidating the txns and evicting them from the mempool.
223 : : *
224 : : * We verify that the mempool updates atomically by polling it continuously
225 : : * from another thread during the reorg and checking that its size only changes
226 : : * once. The size changing exactly once indicates that the polling thread's
227 : : * view of the mempool is either consistent with the chain state before reorg,
228 : : * or consistent with the chain state after the reorg, and not just consistent
229 : : * with some intermediate state during the reorg.
230 : : */
231 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(mempool_locks_reorg)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
232 : : {
233 : 1 : bool ignored;
234 : 741 : auto ProcessBlock = [&](std::shared_ptr<const CBlock> block) -> bool {
235 [ - + ]: 740 : return Assert(m_node.chainman)->ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&ignored);
236 : 1 : };
237 : :
238 : : // Process all mined blocks
239 [ + - + - : 3 : BOOST_REQUIRE(ProcessBlock(std::make_shared<CBlock>(Params().GenesisBlock())));
+ - + - +
- - + ]
240 : 1 : auto last_mined = GoodBlock(Params().GenesisBlock().GetHash());
241 [ + - + - : 4 : BOOST_REQUIRE(ProcessBlock(last_mined));
+ - + - +
- ]
242 : :
243 : : // Run the test multiple times
244 [ + + ]: 4 : for (int test_runs = 3; test_runs > 0; --test_runs) {
245 [ + + + + : 12 : BOOST_CHECK_EQUAL(last_mined->GetHash(), WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()->GetBlockHash()));
+ + + - +
- ]
246 : :
247 : : // Later on split from here
248 : 3 : const uint256 split_hash{last_mined->hashPrevBlock};
249 : :
250 : : // Create a bunch of transactions to spend the miner rewards of the
251 : : // most recent blocks
252 : 3 : std::vector<CTransactionRef> txs;
253 [ + + ]: 69 : for (int num_txs = 22; num_txs > 0; --num_txs) {
254 [ + - ]: 66 : CMutableTransaction mtx;
255 [ + - ]: 66 : mtx.vin.emplace_back(COutPoint{last_mined->vtx[0]->GetHash(), 1}, CScript{});
256 [ + - ]: 66 : mtx.vin[0].scriptWitness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE);
257 [ + - ]: 66 : mtx.vout.push_back(last_mined->vtx[0]->vout[1]);
258 [ + - ]: 66 : mtx.vout[0].nValue -= 1000;
259 [ + - + - : 132 : txs.push_back(MakeTransactionRef(mtx));
- + ]
260 : :
261 [ + - + - : 132 : last_mined = GoodBlock(last_mined->GetHash());
- + ]
262 [ + - + - : 264 : BOOST_REQUIRE(ProcessBlock(last_mined));
+ - + - +
- ]
263 : 66 : }
264 : :
265 : : // Mature the inputs of the txs
266 [ + + ]: 303 : for (int j = COINBASE_MATURITY; j > 0; --j) {
267 [ + - + - : 600 : last_mined = GoodBlock(last_mined->GetHash());
- + ]
268 [ + - + - : 1200 : BOOST_REQUIRE(ProcessBlock(last_mined));
+ - + - +
- ]
269 : : }
270 : :
271 : : // Mine a reorg (and hold it back) before adding the txs to the mempool
272 [ + - ]: 3 : const uint256 tip_init{last_mined->GetHash()};
273 : :
274 : 3 : std::vector<std::shared_ptr<const CBlock>> reorg;
275 [ + - - + ]: 6 : last_mined = GoodBlock(split_hash);
276 [ + - ]: 3 : reorg.push_back(last_mined);
277 [ - + + + ]: 372 : for (size_t j = COINBASE_MATURITY + txs.size() + 1; j > 0; --j) {
278 [ + - + - : 738 : last_mined = GoodBlock(last_mined->GetHash());
- + ]
279 [ + - ]: 369 : reorg.push_back(last_mined);
280 : : }
281 : :
282 : : // Add the txs to the tx pool
283 : 3 : {
284 [ + - ]: 3 : LOCK(cs_main);
285 [ + + ]: 69 : for (const auto& tx : txs) {
286 [ + - ]: 66 : const MempoolAcceptResult result = m_node.chainman->ProcessTransaction(tx);
287 [ + - + - ]: 132 : BOOST_REQUIRE(result.m_result_type == MempoolAcceptResult::ResultType::VALID);
288 : 66 : }
289 : 0 : }
290 : :
291 : : // Check that all txs are in the pool
292 : 3 : {
293 [ + - - + : 3 : BOOST_CHECK_EQUAL(m_node.mempool->size(), txs.size());
+ - + - ]
294 : : }
295 : :
296 : : // Run a thread that simulates an RPC caller that is polling while
297 : : // validation is doing a reorg
298 : 6 : std::thread rpc_thread{[&]() {
299 : : // This thread is checking that the mempool either contains all of
300 : : // the transactions invalidated by the reorg, or none of them, and
301 : : // not some intermediate amount.
302 : 3854357 : while (true) {
303 : 1927180 : LOCK(m_node.mempool->cs);
304 [ + - + + ]: 1927180 : if (m_node.mempool->size() == 0) {
305 : : // We are done with the reorg
306 : : break;
307 : : }
308 : : // Internally, we might be in the middle of the reorg, but
309 : : // externally the reorg to the most-proof-of-work chain should
310 : : // be atomic. So the caller assumes that the returned mempool
311 : : // is consistent. That is, it has all txs that were there
312 : : // before the reorg.
313 [ + - - + : 1927177 : assert(m_node.mempool->size() == txs.size());
- + ]
314 [ + - ]: 1927177 : continue;
315 : 1927177 : }
316 : 3 : LOCK(cs_main);
317 : : // We are done with the reorg, so the tip must have changed
318 [ + - - + : 6 : assert(tip_init != m_node.chainman->ActiveChain().Tip()->GetBlockHash());
- + ]
319 [ + - ]: 6 : }};
320 : :
321 : : // Submit the reorg in this thread to invalidate and remove the txs from the tx pool
322 [ + + ]: 375 : for (const auto& b : reorg) {
323 [ + - + - ]: 1116 : ProcessBlock(b);
324 : : }
325 : : // Check that the reorg was eventually successful
326 [ + + + + : 12 : BOOST_CHECK_EQUAL(last_mined->GetHash(), WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()->GetBlockHash()));
+ + + - +
- ]
327 : :
328 : : // We can join the other thread, which returns when the reorg was successful
329 [ + - ]: 3 : rpc_thread.join();
330 : 3 : }
331 : 1 : }
332 : :
333 [ + - + - : 7 : BOOST_AUTO_TEST_CASE(witness_commitment_index)
+ - + - -
+ + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- + - + -
+ - + - +
- + - - +
+ - + - +
- + - + -
+ - - + +
- ]
334 : : {
335 [ - + ]: 1 : LOCK(Assert(m_node.chainman)->GetMutex());
336 : 1 : CScript pubKey;
337 [ + - + - ]: 1 : pubKey << 1 << OP_TRUE;
338 [ + - ]: 1 : BlockAssembler::Options options;
339 : 1 : options.coinbase_output_script = pubKey;
340 : 1 : options.include_dummy_extranonce = true;
341 [ + - + - : 1 : auto ptemplate = BlockAssembler{m_node.chainman->ActiveChainstate(), m_node.mempool.get(), options}.CreateNewBlock();
+ - ]
342 [ + - ]: 1 : CBlock pblock = ptemplate->block;
343 : :
344 : 1 : CTxOut witness;
345 : 1 : witness.scriptPubKey.resize(MINIMUM_WITNESS_COMMITMENT);
346 [ + - ]: 1 : witness.scriptPubKey[0] = OP_RETURN;
347 [ + - ]: 1 : witness.scriptPubKey[1] = 0x24;
348 [ + - ]: 1 : witness.scriptPubKey[2] = 0xaa;
349 [ + - ]: 1 : witness.scriptPubKey[3] = 0x21;
350 [ + - ]: 1 : witness.scriptPubKey[4] = 0xa9;
351 [ + - ]: 1 : witness.scriptPubKey[5] = 0xed;
352 : :
353 : : // A witness larger than the minimum size is still valid
354 : 1 : CTxOut min_plus_one = witness;
355 : 1 : min_plus_one.scriptPubKey.resize(MINIMUM_WITNESS_COMMITMENT + 1);
356 : :
357 : 1 : CTxOut invalid = witness;
358 [ + - ]: 1 : invalid.scriptPubKey[0] = OP_VERIFY;
359 : :
360 [ + - ]: 1 : CMutableTransaction txCoinbase(*pblock.vtx[0]);
361 [ + - ]: 1 : txCoinbase.vout.resize(4);
362 : 1 : txCoinbase.vout[0] = witness;
363 : 1 : txCoinbase.vout[1] = witness;
364 : 1 : txCoinbase.vout[2] = min_plus_one;
365 : 1 : txCoinbase.vout[3] = invalid;
366 [ + - - + ]: 2 : pblock.vtx[0] = MakeTransactionRef(std::move(txCoinbase));
367 : :
368 [ + - + - ]: 1 : BOOST_CHECK_EQUAL(GetWitnessCommitmentIndex(pblock), 2);
369 [ + - ]: 2 : }
370 : : BOOST_AUTO_TEST_SUITE_END()
|