Bitcoin Core 30.99.0
P2P Digital Currency
validation_block_tests.cpp
Go to the documentation of this file.
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>
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>
16#include <util/time.h>
17#include <validation.h>
18#include <validationinterface.h>
19
20#include <thread>
21
24
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
36
37struct TestSubscriber final : public CValidationInterface {
39
40 explicit TestSubscriber(uint256 tip) : m_expected_tip(tip) {}
41
42 void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override
43 {
44 BOOST_CHECK_EQUAL(m_expected_tip, pindexNew->GetBlockHash());
45 }
46
47 void BlockConnected(const ChainstateRole& role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
48 {
49 BOOST_CHECK_EQUAL(m_expected_tip, block->hashPrevBlock);
50 BOOST_CHECK_EQUAL(m_expected_tip, pindex->pprev->GetBlockHash());
51
52 m_expected_tip = block->GetHash();
53 }
54
55 void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
56 {
57 BOOST_CHECK_EQUAL(m_expected_tip, block->GetHash());
58 BOOST_CHECK_EQUAL(m_expected_tip, pindex->GetBlockHash());
59
60 m_expected_tip = block->hashPrevBlock;
61 }
62};
63
64std::shared_ptr<CBlock> MinerTestingSetup::Block(const uint256& prev_hash)
65{
66 static int i = 0;
67 static uint64_t time = Params().GenesisBlock().nTime;
68
69 BlockAssembler::Options options;
70 options.coinbase_output_script = CScript{} << i++ << OP_TRUE;
71 auto ptemplate = BlockAssembler{m_node.chainman->ActiveChainstate(), m_node.mempool.get(), options}.CreateNewBlock();
72 auto pblock = std::make_shared<CBlock>(ptemplate->block);
73 pblock->hashPrevBlock = prev_hash;
74 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 CMutableTransaction txCoinbase(*pblock->vtx[0]);
80 txCoinbase.vout.resize(2);
81 txCoinbase.vout[1].scriptPubKey = P2WSH_OP_TRUE;
82 txCoinbase.vout[1].nValue = txCoinbase.vout[0].nValue;
83 txCoinbase.vout[0].nValue = 0;
84 txCoinbase.vin[0].scriptWitness.SetNull();
85 // Always pad with OP_0 at the end to avoid bad-cb-length error
86 const int prev_height{WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(prev_hash)->nHeight)};
87 txCoinbase.vin[0].scriptSig = CScript{} << prev_height + 1 << OP_0;
88 txCoinbase.nLockTime = static_cast<uint32_t>(prev_height);
89 pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
90
91 return pblock;
92}
93
94std::shared_ptr<CBlock> MinerTestingSetup::FinalizeBlock(std::shared_ptr<CBlock> pblock)
95{
96 const CBlockIndex* prev_block{WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};
97 m_node.chainman->GenerateCoinbaseCommitment(*pblock, prev_block);
98
99 pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
100
101 while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
102 ++(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 BlockValidationState ignored;
108 BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlockHeaders({{pblock->GetBlockHeader()}}, true, ignored));
109
110 return pblock;
111}
112
113// construct a valid block
114std::shared_ptr<const CBlock> MinerTestingSetup::GoodBlock(const uint256& prev_hash)
115{
116 return FinalizeBlock(Block(prev_hash));
117}
118
119// construct an invalid block (but with a valid header)
120std::shared_ptr<const CBlock> MinerTestingSetup::BadBlock(const uint256& prev_hash)
121{
122 auto pblock = Block(prev_hash);
123
124 CMutableTransaction coinbase_spend;
125 coinbase_spend.vin.emplace_back(COutPoint(pblock->vtx[0]->GetHash(), 0), CScript(), 0);
126 coinbase_spend.vout.push_back(pblock->vtx[0]->vout[0]);
127
128 CTransactionRef tx = MakeTransactionRef(coinbase_spend);
129 pblock->vtx.push_back(tx);
130
131 auto ret = FinalizeBlock(pblock);
132 return ret;
133}
134
135// NOLINTNEXTLINE(misc-no-recursion)
136void 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 if (height <= 0 || blocks.size() >= max_size) return;
139
140 bool gen_invalid = m_rng.randrange(100U) < invalid_rate;
141 bool gen_fork = m_rng.randrange(100U) < branch_rate;
142
143 const std::shared_ptr<const CBlock> pblock = gen_invalid ? BadBlock(root) : GoodBlock(root);
144 blocks.push_back(pblock);
145 if (!gen_invalid) {
146 BuildChain(pblock->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
147 }
148
149 if (gen_fork) {
150 blocks.push_back(GoodBlock(root));
151 BuildChain(blocks.back()->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
152 }
153}
154
155BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering)
156{
157 // build a large-ish chain that's likely to have some forks
158 std::vector<std::shared_ptr<const CBlock>> blocks;
159 while (blocks.size() < 50) {
160 blocks.clear();
161 BuildChain(Params().GenesisBlock().GetHash(), 100, 15, 10, 500, blocks);
162 }
163
164 bool ignored;
165 // Connect the genesis block and drain any outstanding events
166 BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlock(std::make_shared<CBlock>(Params().GenesisBlock()), true, true, &ignored));
167 m_node.validation_signals->SyncWithValidationInterfaceQueue();
168
169 // subscribe to events (this subscriber will validate event ordering)
170 const CBlockIndex* initial_tip = nullptr;
171 {
172 LOCK(cs_main);
173 initial_tip = m_node.chainman->ActiveChain().Tip();
174 }
175 auto sub = std::make_shared<TestSubscriber>(initial_tip->GetBlockHash());
176 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 std::vector<std::thread> threads;
182 threads.reserve(10);
183 for (int i = 0; i < 10; i++) {
184 threads.emplace_back([&]() {
185 bool ignored;
186 FastRandomContext insecure;
187 for (int i = 0; i < 1000; i++) {
188 const auto& block = blocks[insecure.randrange(blocks.size() - 1)];
189 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 for (const auto& block : blocks) {
194 if (block->vtx.size() == 1) {
195 bool processed = Assert(m_node.chainman)->ProcessNewBlock(block, true, true, &ignored);
196 assert(processed);
197 }
198 }
199 });
200 }
201
202 for (auto& t : threads) {
203 t.join();
204 }
205 m_node.validation_signals->SyncWithValidationInterfaceQueue();
206
207 m_node.validation_signals->UnregisterSharedValidationInterface(sub);
208
209 LOCK(cs_main);
210 BOOST_CHECK_EQUAL(sub->m_expected_tip, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
211}
212
230BOOST_AUTO_TEST_CASE(mempool_locks_reorg)
231{
232 bool ignored;
233 auto ProcessBlock = [&](std::shared_ptr<const CBlock> block) -> bool {
234 return Assert(m_node.chainman)->ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&ignored);
235 };
236
237 // Process all mined blocks
238 BOOST_REQUIRE(ProcessBlock(std::make_shared<CBlock>(Params().GenesisBlock())));
239 auto last_mined = GoodBlock(Params().GenesisBlock().GetHash());
240 BOOST_REQUIRE(ProcessBlock(last_mined));
241
242 // Run the test multiple times
243 for (int test_runs = 3; test_runs > 0; --test_runs) {
244 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 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 std::vector<CTransactionRef> txs;
252 for (int num_txs = 22; num_txs > 0; --num_txs) {
254 mtx.vin.emplace_back(COutPoint{last_mined->vtx[0]->GetHash(), 1}, CScript{});
255 mtx.vin[0].scriptWitness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE);
256 mtx.vout.push_back(last_mined->vtx[0]->vout[1]);
257 mtx.vout[0].nValue -= 1000;
258 txs.push_back(MakeTransactionRef(mtx));
259
260 last_mined = GoodBlock(last_mined->GetHash());
261 BOOST_REQUIRE(ProcessBlock(last_mined));
262 }
263
264 // Mature the inputs of the txs
265 for (int j = COINBASE_MATURITY; j > 0; --j) {
266 last_mined = GoodBlock(last_mined->GetHash());
267 BOOST_REQUIRE(ProcessBlock(last_mined));
268 }
269
270 // Mine a reorg (and hold it back) before adding the txs to the mempool
271 const uint256 tip_init{last_mined->GetHash()};
272
273 std::vector<std::shared_ptr<const CBlock>> reorg;
274 last_mined = GoodBlock(split_hash);
275 reorg.push_back(last_mined);
276 for (size_t j = COINBASE_MATURITY + txs.size() + 1; j > 0; --j) {
277 last_mined = GoodBlock(last_mined->GetHash());
278 reorg.push_back(last_mined);
279 }
280
281 // Add the txs to the tx pool
282 {
283 LOCK(cs_main);
284 for (const auto& tx : txs) {
285 const MempoolAcceptResult result = m_node.chainman->ProcessTransaction(tx);
287 }
288 }
289
290 // Check that all txs are in the pool
291 {
292 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 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 while (true) {
302 LOCK(m_node.mempool->cs);
303 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 assert(m_node.mempool->size() == txs.size());
313 continue;
314 }
315 LOCK(cs_main);
316 // We are done with the reorg, so the tip must have changed
317 assert(tip_init != m_node.chainman->ActiveChain().Tip()->GetBlockHash());
318 }};
319
320 // Submit the reorg in this thread to invalidate and remove the txs from the tx pool
321 for (const auto& b : reorg) {
322 ProcessBlock(b);
323 }
324 // Check that the reorg was eventually successful
325 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 rpc_thread.join();
329 }
330}
331
332BOOST_AUTO_TEST_CASE(witness_commitment_index)
333{
334 LOCK(Assert(m_node.chainman)->GetMutex());
335 CScript pubKey;
336 pubKey << 1 << OP_TRUE;
337 BlockAssembler::Options options;
338 options.coinbase_output_script = pubKey;
339 auto ptemplate = BlockAssembler{m_node.chainman->ActiveChainstate(), m_node.mempool.get(), options}.CreateNewBlock();
340 CBlock pblock = ptemplate->block;
341
342 CTxOut witness;
344 witness.scriptPubKey[0] = OP_RETURN;
345 witness.scriptPubKey[1] = 0x24;
346 witness.scriptPubKey[2] = 0xaa;
347 witness.scriptPubKey[3] = 0x21;
348 witness.scriptPubKey[4] = 0xa9;
349 witness.scriptPubKey[5] = 0xed;
350
351 // A witness larger than the minimum size is still valid
352 CTxOut min_plus_one = witness;
354
355 CTxOut invalid = witness;
356 invalid.scriptPubKey[0] = OP_VERIFY;
357
358 CMutableTransaction txCoinbase(*pblock.vtx[0]);
359 txCoinbase.vout.resize(4);
360 txCoinbase.vout[0] = witness;
361 txCoinbase.vout[1] = witness;
362 txCoinbase.vout[2] = min_plus_one;
363 txCoinbase.vout[3] = invalid;
364 pblock.vtx[0] = MakeTransactionRef(std::move(txCoinbase));
365
367}
int ret
node::NodeContext m_node
Definition: bitcoin-gui.cpp:43
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:113
uint32_t nTime
Definition: block.h:28
Definition: block.h:69
std::vector< CTransactionRef > vtx
Definition: block.h:72
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: chain.h:95
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:101
uint256 GetBlockHash() const
Definition: chain.h:199
const CBlock & GenesisBlock() const
Definition: chainparams.h:95
An outpoint - a combination of a transaction hash and an index n into its vout.
Definition: transaction.h:29
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:405
An output of a transaction.
Definition: transaction.h:140
CScript scriptPubKey
Definition: transaction.h:143
Implement this to subscribe to events generated in validation and mempool.
Fast randomness source.
Definition: random.h:386
I randrange(I range) noexcept
Generate a random integer in the range [0..range), with range > 0.
Definition: random.h:254
Generate a new block, without valid proof-of-work.
Definition: miner.h:57
void resize(size_type new_size)
Definition: prevector.h:276
256-bit opaque blob.
Definition: uint256.h:195
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:66
static constexpr size_t MINIMUM_WITNESS_COMMITMENT
Minimum size of a witness commitment structure.
Definition: validation.h:18
int GetWitnessCommitmentIndex(const CBlock &block)
Compute at which vout of the block's coinbase transaction the witness commitment occurs,...
Definition: validation.h:147
static const int COINBASE_MATURITY
Coinbase transaction outputs can only be spent after this number of new blocks (network rule)
Definition: consensus.h:19
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:8
BOOST_FIXTURE_TEST_SUITE(cuckoocache_tests, BasicTestingSetup)
Test Suite for CuckooCache.
BOOST_AUTO_TEST_SUITE_END()
#define BOOST_CHECK_EQUAL(v1, v2)
Definition: object.cpp:18
#define BOOST_CHECK(expr)
Definition: object.cpp:17
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:140
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:404
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:403
@ OP_TRUE
Definition: script.h:84
@ OP_VERIFY
Definition: script.h:110
@ OP_0
Definition: script.h:76
@ OP_RETURN
Definition: script.h:111
A mutable version of CTransaction.
Definition: transaction.h:358
std::vector< CTxOut > vout
Definition: transaction.h:360
std::vector< CTxIn > vin
Definition: transaction.h:359
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:130
const ResultType m_result_type
Result type.
Definition: validation.h:139
Identical to TestingSetup, but chain set to regtest.
Definition: setup_common.h:128
void BlockDisconnected(const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex) override
Notifies listeners of a block being disconnected Provides the block that was disconnected.
void BlockConnected(const ChainstateRole &role, const std::shared_ptr< const CBlock > &block, const CBlockIndex *pindex) override
Notifies listeners of a block being connected.
void UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) override
Notifies listeners when the block chain tip advances.
Information about chainstate that notifications are sent from.
Definition: types.h:18
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:88
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:68
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:72
std::shared_ptr< const CBlock > BadBlock(const uint256 &prev_hash)
std::shared_ptr< CBlock > Block(const uint256 &prev_hash)
std::shared_ptr< const CBlock > GoodBlock(const uint256 &prev_hash)
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)
std::shared_ptr< CBlock > FinalizeBlock(std::shared_ptr< CBlock > pblock)
#define LOCK(cs)
Definition: sync.h:259
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:290
COutPoint ProcessBlock(const NodeContext &node, const std::shared_ptr< CBlock > &block)
Returns the generated coin (or Null if the block was invalid).
Definition: mining.cpp:104
static const std::vector< uint8_t > WITNESS_STACK_ELEM_OP_TRUE
Definition: script.h:12
static const CScript P2WSH_OP_TRUE
Definition: script.h:13
assert(!tx.IsCoinBase())
BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering)