8#include <chainparams.h>
41#include <boost/multi_index/detail/hash_index_iterator.hpp>
60std::vector<std::pair<COutPoint, CAmount>> g_mature_coinbase;
65 std::shared_ptr<CBlock> block;
77 prefilledtxn.push_back(std::move(prefilledtx));
80 void RemoveCoinbasePrefill()
82 prefilledtxn.erase(prefilledtxn.begin());
85 void InsertCoinbaseShortTxID(uint64_t shorttxid)
87 shorttxids.insert(shorttxids.begin(), shorttxid);
90 void EraseShortTxIDs(
size_t index)
92 shorttxids.erase(shorttxids.begin() + index);
95 size_t PrefilledTxCount() {
96 return prefilledtxn.size();
99 size_t ShortTxIDCount() {
100 return shorttxids.size();
112 static const auto testing_setup = MakeNoLogFileContext<TestingSetup>();
116 testing_setup->m_node.validation_signals = std::make_unique<ValidationSignals>(std::make_unique<ImmediateBackgroundTaskRunner>());
131 auto& mempool = *
setup->m_node.mempool;
134 chainman.DisableNextWrite();
135 const size_t initial_index_size{
WITH_LOCK(chainman.GetMutex(),
return chainman.BlockIndex().size())};
140 mempool, *
setup->m_node.warnings,
142 .deterministic_rng = true,
144 connman.SetMsgProc(peerman.get());
146 setup->m_node.validation_signals->RegisterValidationInterface(peerman.get());
147 setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
151 std::vector<CNode*> peers;
152 for (
int i = 0; i < 4; ++i) {
154 CNode& p2p_node = *peers.back();
156 connman.AddTestNode(p2p_node);
160 std::vector<BlockInfo> info;
163 std::vector<std::pair<COutPoint, CAmount>> mature_coinbase = g_mature_coinbase;
165 const uint64_t initial_sequence{
WITH_LOCK(mempool.cs,
return mempool.GetSequence())};
175 unsigned long mempool_size = mempool.size();
180 amount_in = tx->vout[0].nValue;
183 auto info_it = info.begin();
185 auto tx_it = info_it->block->vtx.begin();
187 outpoint =
COutPoint(tx_it->get()->GetHash(), 0);
188 amount_in = tx_it->get()->vout[0].nValue;
190 auto coinbase_it = mature_coinbase.begin();
192 outpoint = coinbase_it->first;
193 amount_in = coinbase_it->second;
197 const auto script_sig =
CScript{};
205 tx_mut.
vin.push_back(in);
207 const CAmount amount_out = amount_in - AMOUNT_FEE;
214 auto create_block = [&]() {
220 prev = chainman.ActiveChain().Tip()->GetBlockHash();
221 height = chainman.ActiveChain().Height() + 1;
224 prev = info[index].hash;
225 height = info[index].height + 1;
228 const auto new_time =
WITH_LOCK(
::cs_main,
return chainman.ActiveChain().Tip()->GetMedianTimePast() + 1);
233 header.
nBits = g_nBits;
234 header.
nTime = new_time;
237 std::shared_ptr<CBlock> block = std::make_shared<CBlock>();
241 coinbase_tx.
vin.resize(1);
242 coinbase_tx.
vin[0].prevout.SetNull();
244 coinbase_tx.
vout.resize(1);
249 const auto mempool_size = mempool.size();
256 for (
size_t i = random_idx; i < random_idx + num_txns; ++i) {
257 CTransactionRef mempool_tx = mempool.txns_randomized[i % mempool_size].second->GetSharedTx();
258 block->vtx.push_back(mempool_tx);
265 for (
size_t i = 0; i < new_txns; ++i) {
267 block->vtx.push_back(non_mempool_tx);
272 chainman.GenerateCoinbaseCommitment(*block, pindexPrev);
278 BlockInfo block_info;
279 block_info.block = block;
280 block_info.hash = block->GetHash();
281 block_info.height = height;
288 bool sent_net_msg =
true;
289 bool requested_hb =
false;
290 bool sent_sendcmpct =
false;
291 bool valid_sendcmpct =
false;
297 std::shared_ptr<CBlock> cblock;
301 size_t index = fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, info.size() - 1);
302 cblock = info[index].block;
304 BlockInfo block_info = create_block();
305 cblock = block_info.block;
306 info.push_back(block_info);
310 FuzzedCBlockHeaderAndShortTxIDs cmpctblock(*cblock,
nonce);
313 CBlockHeaderAndShortTxIDs base_cmpctblock = cmpctblock;
314 net_msg = NetMsg::Make(NetMsgType::CMPCTBLOCK, base_cmpctblock);
319 size_t num_erased = 1;
320 size_t num_txs = cblock->vtx.size();
322 for (
size_t i = 0; i < num_txs; ++i) {
329 uint64_t coinbase_shortid = cmpctblock.GetShortID(cblock->vtx[0]->GetWitnessHash());
330 cmpctblock.RemoveCoinbasePrefill();
331 cmpctblock.InsertCoinbaseShortTxID(coinbase_shortid);
337 uint16_t prefill_idx = num_erased == 0 ? i : i - prev_idx - 1;
341 cmpctblock.AddPrefilledTx(std::move(prefilledtx));
344 cmpctblock.EraseShortTxIDs(i - num_erased);
348 assert(cmpctblock.PrefilledTxCount() + cmpctblock.ShortTxIDCount() == num_txs);
355 size_t num_blocks = info.size();
356 if (num_blocks == 0) {
357 sent_net_msg =
false;
363 const BlockInfo& block_info = info[index];
366 std::shared_ptr<CBlock> cblock = block_info.block;
368 for (
size_t i = 0; i < cblock->vtx.size(); i++) {
371 block_txn.
txn.push_back(cblock->vtx[i]);
378 size_t num_blocks = info.size();
379 if (num_blocks == 0) {
380 sent_net_msg =
false;
386 CBlock block = *info[index].block;
399 sent_sendcmpct =
true;
404 BlockInfo block_info = create_block();
405 info.push_back(block_info);
406 sent_net_msg =
false;
419 node_clock.set(tip_time);
422 sent_net_msg =
false;
430 connman.FlushSendBuffer(random_node);
431 (void)connman.ReceiveMsgFrom(random_node, std::move(net_msg));
433 bool more_work{
true};
437 more_work = connman.ProcessMessagesOnce(random_node);
438 peerman->SendMessages(random_node);
441 std::vector<CNodeStats> stats;
442 connman.GetNodeStats(stats);
447 if (stat.m_bip152_highbandwidth_to) {
449 CNode* hb_peer = peers[stat.nodeid];
463 setup->m_node.validation_signals->SyncWithValidationInterfaceQueue();
464 setup->m_node.validation_signals->UnregisterAllValidationInterfaces();
467 const size_t end_index_size{
WITH_LOCK(chainman.GetMutex(),
return chainman.BlockIndex().size())};
468 const uint64_t end_sequence{
WITH_LOCK(mempool.cs,
return mempool.GetSequence())};
470 if (initial_index_size != end_index_size || initial_sequence != end_sequence) {
int64_t CAmount
Amount in satoshis (Can be negative)
constexpr CAmount COIN
The amount of satoshis in one BTC.
const TestingSetup * g_setup
const CChainParams & Params()
Return the currently selected parameters.
Stochastic address manager.
std::vector< CTransactionRef > txn
CBlockHeaderAndShortTxIDs()=default
Dummy for deserialization.
std::vector< CTransactionRef > vtx
The block chain is a tree shaped structure starting with the genesis block at the root,...
const CBlock & GenesisBlock() const
Information about a peer.
bool IsInboundConn() const
bool IsOutboundOrBlockRelayConn() const
bool IsManualConn() const
bool IsAddrFetchConn() const
std::atomic_bool fPauseSend
std::atomic_bool fDisconnect
bool m_bip152_highbandwidth_from
An outpoint - a combination of a transaction hash and an index n into its vout.
Serialized script, used inside transaction inputs and outputs.
static constexpr uint32_t CURRENT_VERSION
An input of a transaction.
CScriptWitness scriptWitness
Only serialized through CTransaction.
Helper to initialize the global NodeClock, let a duration elapse, and reset it after use in a test.
Helper to initialize the global MockableSteadyClock, let a duration elapse, and reset it after use in...
T ConsumeIntegralInRange(T min, T max)
static Mutex g_msgproc_mutex
Mutex for anything that is only accessed via the msg processing thread.
static std::unique_ptr< PeerManager > make(CConnman &connman, AddrMan &addrman, BanMan *banman, ChainstateManager &chainman, CTxMemPool &pool, node::Warnings &warnings, Options opts)
static const uint256 ZERO
void MakeRandDeterministicDANGEROUS(const uint256 &seed) noexcept
Internal function to set g_determinstic_rng.
FUZZ_TARGET(cmpctblock,.init=initialize_cmpctblock)
void initialize_cmpctblock()
for(const auto &cache :caches)
LIMITED_WHILE(provider.remaining_bytes(), 10000)
uint256 BlockMerkleRoot(const CBlock &block, bool *mutated)
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
CSerializedNetMsg Make(std::string msg_type, Args &&... args)
constexpr const char * HEADERS
The headers message sends one or more block headers to a node which previously requested certain head...
constexpr const char * CMPCTBLOCK
Contains a CBlockHeaderAndShortTxIDs object - providing a header and list of "short txids".
constexpr const char * BLOCKTXN
Contains a BlockTransactions.
constexpr const char * SENDCMPCT
Contains a 1-byte bool and 8-byte LE version number.
constexpr const char * TX
The tx message transmits a single transaction.
constexpr uint64_t CMPCTBLOCKS_VERSION
The compactblocks version we support.
constexpr TransactionSerParams TX_WITH_WITNESS
static CTransactionRef MakeTransactionRef(Tx &&txIn)
std::shared_ptr< const CTransaction > CTransactionRef
A mutable version of CTransaction.
std::vector< CTxOut > vout
std::vector< std::vector< unsigned char > > stack
void Reset()
Reset the internal state.
void ResetIbd()
Reset the ibd cache to its initial state.
Testing setup that configures a complete environment.
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
SeedRandomStateForTest(SeedRand::ZEROS)
void FillNode(FuzzedDataProvider &fuzzed_data_provider, ConnmanTestMsg &connman, CNode &node) noexcept
std::unique_ptr< CNode > ConsumeNodeAsUniquePtr(FuzzedDataProvider &fdp, FakeSteadyClock &clock, const std::optional< NodeId > &node_id_in=std::nullopt)
NodeSeconds ConsumeTime(FuzzedDataProvider &fuzzed_data_provider, const std::optional< int64_t > &min, const std::optional< int64_t > &max) noexcept
uint32_t ConsumeSequence(FuzzedDataProvider &fuzzed_data_provider) noexcept
auto & PickValue(FuzzedDataProvider &fuzzed_data_provider, Collection &col)
size_t CallOneOf(FuzzedDataProvider &fuzzed_data_provider, Callables... callables)
void FinalizeHeader(CBlockHeader &header, const ChainstateManager &chainman)
@ ZEROS
Seed with a compile time constant of zeros.
static const std::vector< uint8_t > WITNESS_STACK_ELEM_OP_TRUE
static const CScript P2WSH_OP_TRUE
std::vector< std::pair< COutPoint, CAmount > > ResetChainmanAndMempool(TestingSetup &setup, FakeNodeClock &node_clock)
constexpr decltype(CTransaction::version) TRUC_VERSION
std::chrono::time_point< NodeClock, std::chrono::seconds > NodeSeconds
FuzzedDataProvider & fuzzed_data_provider