Bitcoin Core  27.99.0
P2P Digital Currency
validation_block_tests.cpp
Go to the documentation of this file.
1 // Copyright (c) 2018-2022 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 
23 
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 {
38 
39  explicit TestSubscriber(uint256 tip) : m_expected_tip(tip) {}
40 
41  void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload) override
42  {
43  BOOST_CHECK_EQUAL(m_expected_tip, pindexNew->GetBlockHash());
44  }
45 
46  void BlockConnected(ChainstateRole role, const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
47  {
48  BOOST_CHECK_EQUAL(m_expected_tip, block->hashPrevBlock);
49  BOOST_CHECK_EQUAL(m_expected_tip, pindex->pprev->GetBlockHash());
50 
51  m_expected_tip = block->GetHash();
52  }
53 
54  void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex) override
55  {
56  BOOST_CHECK_EQUAL(m_expected_tip, block->GetHash());
57  BOOST_CHECK_EQUAL(m_expected_tip, pindex->GetBlockHash());
58 
59  m_expected_tip = block->hashPrevBlock;
60  }
61 };
62 
63 std::shared_ptr<CBlock> MinerTestingSetup::Block(const uint256& prev_hash)
64 {
65  static int i = 0;
66  static uint64_t time = Params().GenesisBlock().nTime;
67 
68  auto ptemplate = BlockAssembler{m_node.chainman->ActiveChainstate(), m_node.mempool.get()}.CreateNewBlock(CScript{} << i++ << OP_TRUE);
69  auto pblock = std::make_shared<CBlock>(ptemplate->block);
70  pblock->hashPrevBlock = prev_hash;
71  pblock->nTime = ++time;
72 
73  // Make the coinbase transaction with two outputs:
74  // One zero-value one that has a unique pubkey to make sure that blocks at the same height can have a different hash
75  // Another one that has the coinbase reward in a P2WSH with OP_TRUE as witness program to make it easy to spend
76  CMutableTransaction txCoinbase(*pblock->vtx[0]);
77  txCoinbase.vout.resize(2);
78  txCoinbase.vout[1].scriptPubKey = P2WSH_OP_TRUE;
79  txCoinbase.vout[1].nValue = txCoinbase.vout[0].nValue;
80  txCoinbase.vout[0].nValue = 0;
81  txCoinbase.vin[0].scriptWitness.SetNull();
82  // Always pad with OP_0 at the end to avoid bad-cb-length error
83  txCoinbase.vin[0].scriptSig = CScript{} << WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(prev_hash)->nHeight + 1) << OP_0;
84  pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
85 
86  return pblock;
87 }
88 
89 std::shared_ptr<CBlock> MinerTestingSetup::FinalizeBlock(std::shared_ptr<CBlock> pblock)
90 {
91  const CBlockIndex* prev_block{WITH_LOCK(::cs_main, return m_node.chainman->m_blockman.LookupBlockIndex(pblock->hashPrevBlock))};
92  m_node.chainman->GenerateCoinbaseCommitment(*pblock, prev_block);
93 
94  pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
95 
96  while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
97  ++(pblock->nNonce);
98  }
99 
100  // submit block header, so that miner can get the block height from the
101  // global state and the node has the topology of the chain
102  BlockValidationState ignored;
103  BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlockHeaders({pblock->GetBlockHeader()}, true, ignored));
104 
105  return pblock;
106 }
107 
108 // construct a valid block
109 std::shared_ptr<const CBlock> MinerTestingSetup::GoodBlock(const uint256& prev_hash)
110 {
111  return FinalizeBlock(Block(prev_hash));
112 }
113 
114 // construct an invalid block (but with a valid header)
115 std::shared_ptr<const CBlock> MinerTestingSetup::BadBlock(const uint256& prev_hash)
116 {
117  auto pblock = Block(prev_hash);
118 
119  CMutableTransaction coinbase_spend;
120  coinbase_spend.vin.emplace_back(COutPoint(pblock->vtx[0]->GetHash(), 0), CScript(), 0);
121  coinbase_spend.vout.push_back(pblock->vtx[0]->vout[0]);
122 
123  CTransactionRef tx = MakeTransactionRef(coinbase_spend);
124  pblock->vtx.push_back(tx);
125 
126  auto ret = FinalizeBlock(pblock);
127  return ret;
128 }
129 
130 // NOLINTNEXTLINE(misc-no-recursion)
131 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)
132 {
133  if (height <= 0 || blocks.size() >= max_size) return;
134 
135  bool gen_invalid = InsecureRandRange(100) < invalid_rate;
136  bool gen_fork = InsecureRandRange(100) < branch_rate;
137 
138  const std::shared_ptr<const CBlock> pblock = gen_invalid ? BadBlock(root) : GoodBlock(root);
139  blocks.push_back(pblock);
140  if (!gen_invalid) {
141  BuildChain(pblock->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
142  }
143 
144  if (gen_fork) {
145  blocks.push_back(GoodBlock(root));
146  BuildChain(blocks.back()->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
147  }
148 }
149 
150 BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering)
151 {
152  // build a large-ish chain that's likely to have some forks
153  std::vector<std::shared_ptr<const CBlock>> blocks;
154  while (blocks.size() < 50) {
155  blocks.clear();
156  BuildChain(Params().GenesisBlock().GetHash(), 100, 15, 10, 500, blocks);
157  }
158 
159  bool ignored;
160  // Connect the genesis block and drain any outstanding events
161  BOOST_CHECK(Assert(m_node.chainman)->ProcessNewBlock(std::make_shared<CBlock>(Params().GenesisBlock()), true, true, &ignored));
162  m_node.validation_signals->SyncWithValidationInterfaceQueue();
163 
164  // subscribe to events (this subscriber will validate event ordering)
165  const CBlockIndex* initial_tip = nullptr;
166  {
167  LOCK(cs_main);
168  initial_tip = m_node.chainman->ActiveChain().Tip();
169  }
170  auto sub = std::make_shared<TestSubscriber>(initial_tip->GetBlockHash());
171  m_node.validation_signals->RegisterSharedValidationInterface(sub);
172 
173  // create a bunch of threads that repeatedly process a block generated above at random
174  // this will create parallelism and randomness inside validation - the ValidationInterface
175  // will subscribe to events generated during block validation and assert on ordering invariance
176  std::vector<std::thread> threads;
177  threads.reserve(10);
178  for (int i = 0; i < 10; i++) {
179  threads.emplace_back([&]() {
180  bool ignored;
181  FastRandomContext insecure;
182  for (int i = 0; i < 1000; i++) {
183  auto block = blocks[insecure.randrange(blocks.size() - 1)];
184  Assert(m_node.chainman)->ProcessNewBlock(block, true, true, &ignored);
185  }
186 
187  // to make sure that eventually we process the full chain - do it here
188  for (const auto& block : blocks) {
189  if (block->vtx.size() == 1) {
190  bool processed = Assert(m_node.chainman)->ProcessNewBlock(block, true, true, &ignored);
191  assert(processed);
192  }
193  }
194  });
195  }
196 
197  for (auto& t : threads) {
198  t.join();
199  }
200  m_node.validation_signals->SyncWithValidationInterfaceQueue();
201 
202  m_node.validation_signals->UnregisterSharedValidationInterface(sub);
203 
204  LOCK(cs_main);
205  BOOST_CHECK_EQUAL(sub->m_expected_tip, m_node.chainman->ActiveChain().Tip()->GetBlockHash());
206 }
207 
225 BOOST_AUTO_TEST_CASE(mempool_locks_reorg)
226 {
227  bool ignored;
228  auto ProcessBlock = [&](std::shared_ptr<const CBlock> block) -> bool {
229  return Assert(m_node.chainman)->ProcessNewBlock(block, /*force_processing=*/true, /*min_pow_checked=*/true, /*new_block=*/&ignored);
230  };
231 
232  // Process all mined blocks
233  BOOST_REQUIRE(ProcessBlock(std::make_shared<CBlock>(Params().GenesisBlock())));
234  auto last_mined = GoodBlock(Params().GenesisBlock().GetHash());
235  BOOST_REQUIRE(ProcessBlock(last_mined));
236 
237  // Run the test multiple times
238  for (int test_runs = 3; test_runs > 0; --test_runs) {
239  BOOST_CHECK_EQUAL(last_mined->GetHash(), WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()->GetBlockHash()));
240 
241  // Later on split from here
242  const uint256 split_hash{last_mined->hashPrevBlock};
243 
244  // Create a bunch of transactions to spend the miner rewards of the
245  // most recent blocks
246  std::vector<CTransactionRef> txs;
247  for (int num_txs = 22; num_txs > 0; --num_txs) {
249  mtx.vin.emplace_back(COutPoint{last_mined->vtx[0]->GetHash(), 1}, CScript{});
250  mtx.vin[0].scriptWitness.stack.push_back(WITNESS_STACK_ELEM_OP_TRUE);
251  mtx.vout.push_back(last_mined->vtx[0]->vout[1]);
252  mtx.vout[0].nValue -= 1000;
253  txs.push_back(MakeTransactionRef(mtx));
254 
255  last_mined = GoodBlock(last_mined->GetHash());
256  BOOST_REQUIRE(ProcessBlock(last_mined));
257  }
258 
259  // Mature the inputs of the txs
260  for (int j = COINBASE_MATURITY; j > 0; --j) {
261  last_mined = GoodBlock(last_mined->GetHash());
262  BOOST_REQUIRE(ProcessBlock(last_mined));
263  }
264 
265  // Mine a reorg (and hold it back) before adding the txs to the mempool
266  const uint256 tip_init{last_mined->GetHash()};
267 
268  std::vector<std::shared_ptr<const CBlock>> reorg;
269  last_mined = GoodBlock(split_hash);
270  reorg.push_back(last_mined);
271  for (size_t j = COINBASE_MATURITY + txs.size() + 1; j > 0; --j) {
272  last_mined = GoodBlock(last_mined->GetHash());
273  reorg.push_back(last_mined);
274  }
275 
276  // Add the txs to the tx pool
277  {
278  LOCK(cs_main);
279  for (const auto& tx : txs) {
280  const MempoolAcceptResult result = m_node.chainman->ProcessTransaction(tx);
281  BOOST_REQUIRE(result.m_result_type == MempoolAcceptResult::ResultType::VALID);
282  }
283  }
284 
285  // Check that all txs are in the pool
286  {
287  BOOST_CHECK_EQUAL(m_node.mempool->size(), txs.size());
288  }
289 
290  // Run a thread that simulates an RPC caller that is polling while
291  // validation is doing a reorg
292  std::thread rpc_thread{[&]() {
293  // This thread is checking that the mempool either contains all of
294  // the transactions invalidated by the reorg, or none of them, and
295  // not some intermediate amount.
296  while (true) {
297  LOCK(m_node.mempool->cs);
298  if (m_node.mempool->size() == 0) {
299  // We are done with the reorg
300  break;
301  }
302  // Internally, we might be in the middle of the reorg, but
303  // externally the reorg to the most-proof-of-work chain should
304  // be atomic. So the caller assumes that the returned mempool
305  // is consistent. That is, it has all txs that were there
306  // before the reorg.
307  assert(m_node.mempool->size() == txs.size());
308  continue;
309  }
310  LOCK(cs_main);
311  // We are done with the reorg, so the tip must have changed
312  assert(tip_init != m_node.chainman->ActiveChain().Tip()->GetBlockHash());
313  }};
314 
315  // Submit the reorg in this thread to invalidate and remove the txs from the tx pool
316  for (const auto& b : reorg) {
317  ProcessBlock(b);
318  }
319  // Check that the reorg was eventually successful
320  BOOST_CHECK_EQUAL(last_mined->GetHash(), WITH_LOCK(Assert(m_node.chainman)->GetMutex(), return m_node.chainman->ActiveChain().Tip()->GetBlockHash()));
321 
322  // We can join the other thread, which returns when the reorg was successful
323  rpc_thread.join();
324  }
325 }
326 
327 BOOST_AUTO_TEST_CASE(witness_commitment_index)
328 {
329  LOCK(Assert(m_node.chainman)->GetMutex());
330  CScript pubKey;
331  pubKey << 1 << OP_TRUE;
332  auto ptemplate = BlockAssembler{m_node.chainman->ActiveChainstate(), m_node.mempool.get()}.CreateNewBlock(pubKey);
333  CBlock pblock = ptemplate->block;
334 
335  CTxOut witness;
337  witness.scriptPubKey[0] = OP_RETURN;
338  witness.scriptPubKey[1] = 0x24;
339  witness.scriptPubKey[2] = 0xaa;
340  witness.scriptPubKey[3] = 0x21;
341  witness.scriptPubKey[4] = 0xa9;
342  witness.scriptPubKey[5] = 0xed;
343 
344  // A witness larger than the minimum size is still valid
345  CTxOut min_plus_one = witness;
347 
348  CTxOut invalid = witness;
349  invalid.scriptPubKey[0] = OP_VERIFY;
350 
351  CMutableTransaction txCoinbase(*pblock.vtx[0]);
352  txCoinbase.vout.resize(4);
353  txCoinbase.vout[0] = witness;
354  txCoinbase.vout[1] = witness;
355  txCoinbase.vout[2] = min_plus_one;
356  txCoinbase.vout[3] = invalid;
357  pblock.vtx[0] = MakeTransactionRef(std::move(txCoinbase));
358 
360 }
int ret
node::NodeContext m_node
Definition: bitcoin-gui.cpp:37
const CChainParams & Params()
Return the currently selected parameters.
#define Assert(val)
Identity function.
Definition: check.h:77
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:141
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: chain.h:147
uint256 GetBlockHash() const
Definition: chain.h:244
const CBlock & GenesisBlock() const
Definition: chainparams.h:97
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:414
An output of a transaction.
Definition: transaction.h:150
CScript scriptPubKey
Definition: transaction.h:153
Implement this to subscribe to events generated in validation and mempool.
Fast randomness source.
Definition: random.h:145
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
Definition: random.h:203
Generate a new block, without valid proof-of-work.
Definition: miner.h:135
void resize(size_type new_size)
Definition: prevector.h:330
256-bit opaque blob.
Definition: uint256.h:106
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:164
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_AUTO_TEST_SUITE_END()
ChainstateRole
This enum describes the various roles a specific Chainstate instance can take.
Definition: chain.h:25
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
Definition: merkle.cpp:65
#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:125
static CTransactionRef MakeTransactionRef(Tx &&txIn)
Definition: transaction.h:424
std::shared_ptr< const CTransaction > CTransactionRef
Definition: transaction.h:423
@ OP_TRUE
Definition: script.h:83
@ OP_VERIFY
Definition: script.h:109
@ OP_0
Definition: script.h:75
@ OP_RETURN
Definition: script.h:110
A mutable version of CTransaction.
Definition: transaction.h:378
std::vector< CTxOut > vout
Definition: transaction.h:380
std::vector< CTxIn > vin
Definition: transaction.h:379
Validation result for a transaction evaluated by MemPoolAccept (single or package).
Definition: validation.h:127
const ResultType m_result_type
Result type.
Definition: validation.h:136
Identical to TestingSetup, but chain set to regtest.
Definition: setup_common.h:92
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(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.
std::unique_ptr< ValidationSignals > validation_signals
Issues calls about blocks and transactions.
Definition: context.h:77
std::unique_ptr< CTxMemPool > mempool
Definition: context.h:58
std::unique_ptr< ChainstateManager > chainman
Definition: context.h:62
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< 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)
std::shared_ptr< CBlock > FinalizeBlock(std::shared_ptr< CBlock > pblock)
#define LOCK(cs)
Definition: sync.h:257
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:301
static uint64_t InsecureRandRange(uint64_t range)
Definition: random.h:60
static const std::vector< uint8_t > WITNESS_STACK_ELEM_OP_TRUE
Definition: script.h:11
static const CScript P2WSH_OP_TRUE
Definition: script.h:12
assert(!tx.IsCoinBase())
BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering)