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