Skip to content

Commit dd435ad

Browse files
committed
Add unit tests for signals generated by ProcessNewBlock()
After a recent bug discovered in callback ordering in MainSignals, this test checks invariants in ordering of BlockConnected / BlockDisconnected / UpdatedChainTip signals
1 parent a3ae8e6 commit dd435ad

File tree

4 files changed

+196
-2
lines changed

4 files changed

+196
-2
lines changed

src/Makefile.test.include

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,10 @@ BITCOIN_TESTS =\
8585
test/transaction_tests.cpp \
8686
test/txvalidation_tests.cpp \
8787
test/txvalidationcache_tests.cpp \
88-
test/versionbits_tests.cpp \
8988
test/uint256_tests.cpp \
90-
test/util_tests.cpp
89+
test/util_tests.cpp \
90+
test/validation_block_tests.cpp \
91+
test/versionbits_tests.cpp
9192

9293
if ENABLE_WALLET
9394
BITCOIN_TESTS += \

src/test/test_bitcoin.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,12 @@ FastRandomContext insecure_rand_ctx(insecure_rand_seed);
3838
extern bool fPrintToConsole;
3939
extern void noui_connect();
4040

41+
std::ostream& operator<<(std::ostream& os, const uint256& num)
42+
{
43+
os << num.ToString();
44+
return os;
45+
}
46+
4147
BasicTestingSetup::BasicTestingSetup(const std::string& chainName)
4248
{
4349
SHA256AutoDetect();

src/test/test_bitcoin.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,4 +120,7 @@ struct TestMemPoolEntryHelper
120120

121121
CBlock getBlock13b8a();
122122

123+
// define an implicit conversion here so that uint256 may be used directly in BOOST_CHECK_*
124+
std::ostream& operator<<(std::ostream& os, const uint256& num);
125+
123126
#endif

src/test/validation_block_tests.cpp

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,184 @@
1+
// Copyright (c) 2018 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 <miner.h>
11+
#include <pow.h>
12+
#include <random.h>
13+
#include <test/test_bitcoin.h>
14+
#include <validation.h>
15+
#include <validationinterface.h>
16+
17+
struct RegtestingSetup : public TestingSetup {
18+
RegtestingSetup() : TestingSetup(CBaseChainParams::REGTEST) {}
19+
};
20+
21+
BOOST_FIXTURE_TEST_SUITE(validation_block_tests, RegtestingSetup)
22+
23+
struct TestSubscriber : public CValidationInterface {
24+
uint256 m_expected_tip;
25+
26+
TestSubscriber(uint256 tip) : m_expected_tip(tip) {}
27+
28+
void UpdatedBlockTip(const CBlockIndex* pindexNew, const CBlockIndex* pindexFork, bool fInitialDownload)
29+
{
30+
BOOST_CHECK_EQUAL(m_expected_tip, pindexNew->GetBlockHash());
31+
}
32+
33+
void BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* pindex, const std::vector<CTransactionRef>& txnConflicted)
34+
{
35+
BOOST_CHECK_EQUAL(m_expected_tip, block->hashPrevBlock);
36+
BOOST_CHECK_EQUAL(m_expected_tip, pindex->pprev->GetBlockHash());
37+
38+
m_expected_tip = block->GetHash();
39+
}
40+
41+
void BlockDisconnected(const std::shared_ptr<const CBlock>& block)
42+
{
43+
BOOST_CHECK_EQUAL(m_expected_tip, block->GetHash());
44+
45+
m_expected_tip = block->hashPrevBlock;
46+
}
47+
};
48+
49+
std::shared_ptr<CBlock> Block(const uint256& prev_hash)
50+
{
51+
static int i = 0;
52+
static uint64_t time = Params().GenesisBlock().nTime;
53+
54+
CScript pubKey;
55+
pubKey << i++ << OP_TRUE;
56+
57+
auto ptemplate = BlockAssembler(Params()).CreateNewBlock(pubKey, false);
58+
auto pblock = std::make_shared<CBlock>(ptemplate->block);
59+
pblock->hashPrevBlock = prev_hash;
60+
pblock->nTime = ++time;
61+
62+
CMutableTransaction txCoinbase(*pblock->vtx[0]);
63+
txCoinbase.vout.resize(1);
64+
txCoinbase.vin[0].scriptWitness.SetNull();
65+
pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase));
66+
67+
return pblock;
68+
}
69+
70+
std::shared_ptr<CBlock> FinalizeBlock(std::shared_ptr<CBlock> pblock)
71+
{
72+
pblock->hashMerkleRoot = BlockMerkleRoot(*pblock);
73+
74+
while (!CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus())) {
75+
++(pblock->nNonce);
76+
}
77+
78+
return pblock;
79+
}
80+
81+
// construct a valid block
82+
const std::shared_ptr<const CBlock> GoodBlock(const uint256& prev_hash)
83+
{
84+
return FinalizeBlock(Block(prev_hash));
85+
}
86+
87+
// construct an invalid block (but with a valid header)
88+
const std::shared_ptr<const CBlock> BadBlock(const uint256& prev_hash)
89+
{
90+
auto pblock = Block(prev_hash);
91+
92+
CMutableTransaction coinbase_spend;
93+
coinbase_spend.vin.push_back(CTxIn(COutPoint(pblock->vtx[0]->GetHash(), 0), CScript(), 0));
94+
coinbase_spend.vout.push_back(pblock->vtx[0]->vout[0]);
95+
96+
CTransactionRef tx = MakeTransactionRef(coinbase_spend);
97+
pblock->vtx.push_back(tx);
98+
99+
auto ret = FinalizeBlock(pblock);
100+
return ret;
101+
}
102+
103+
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)
104+
{
105+
if (height <= 0 || blocks.size() >= max_size) return;
106+
107+
bool gen_invalid = GetRand(100) < invalid_rate;
108+
bool gen_fork = GetRand(100) < branch_rate;
109+
110+
const std::shared_ptr<const CBlock> pblock = gen_invalid ? BadBlock(root) : GoodBlock(root);
111+
blocks.push_back(pblock);
112+
if (!gen_invalid) {
113+
BuildChain(pblock->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
114+
}
115+
116+
if (gen_fork) {
117+
blocks.push_back(GoodBlock(root));
118+
BuildChain(blocks.back()->GetHash(), height - 1, invalid_rate, branch_rate, max_size, blocks);
119+
}
120+
}
121+
122+
BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering)
123+
{
124+
// build a large-ish chain that's likely to have some forks
125+
std::vector<std::shared_ptr<const CBlock>> blocks;
126+
while (blocks.size() < 50) {
127+
blocks.clear();
128+
BuildChain(Params().GenesisBlock().GetHash(), 100, 15, 10, 500, blocks);
129+
}
130+
131+
bool ignored;
132+
CValidationState state;
133+
std::vector<CBlockHeader> headers;
134+
std::transform(blocks.begin(), blocks.end(), std::back_inserter(headers), [](std::shared_ptr<const CBlock> b) { return b->GetBlockHeader(); });
135+
136+
// Process all the headers so we understand the toplogy of the chain
137+
BOOST_CHECK(ProcessNewBlockHeaders(headers, state, Params()));
138+
139+
// Connect the genesis block and drain any outstanding events
140+
ProcessNewBlock(Params(), std::make_shared<CBlock>(Params().GenesisBlock()), true, &ignored);
141+
SyncWithValidationInterfaceQueue();
142+
143+
// subscribe to events (this subscriber will validate event ordering)
144+
const CBlockIndex* initial_tip = nullptr;
145+
{
146+
LOCK(cs_main);
147+
initial_tip = chainActive.Tip();
148+
}
149+
TestSubscriber sub(initial_tip->GetBlockHash());
150+
RegisterValidationInterface(&sub);
151+
152+
// create a bunch of threads that repeatedly process a block generated above at random
153+
// this will create parallelism and randomness inside validation - the ValidationInterface
154+
// will subscribe to events generated during block validation and assert on ordering invariance
155+
boost::thread_group threads;
156+
for (int i = 0; i < 10; i++) {
157+
threads.create_thread([&blocks]() {
158+
bool ignored;
159+
for (int i = 0; i < 1000; i++) {
160+
auto block = blocks[GetRand(blocks.size() - 1)];
161+
ProcessNewBlock(Params(), block, true, &ignored);
162+
}
163+
164+
// to make sure that eventually we process the full chain - do it here
165+
for (auto block : blocks) {
166+
if (block->vtx.size() == 1) {
167+
bool processed = ProcessNewBlock(Params(), block, true, &ignored);
168+
assert(processed);
169+
}
170+
}
171+
});
172+
}
173+
174+
threads.join_all();
175+
while (GetMainSignals().CallbacksPending() > 0) {
176+
MilliSleep(100);
177+
}
178+
179+
UnregisterValidationInterface(&sub);
180+
181+
BOOST_CHECK_EQUAL(sub.m_expected_tip, chainActive.Tip()->GetBlockHash());
182+
}
183+
184+
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)