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