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