Skip to content

Commit 0213fbe

Browse files
committed
merge bitcoin#21866: Farewell, global Chainstate!
1 parent e3687f7 commit 0213fbe

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+358
-457
lines changed

src/bench/duplicate_inputs.cpp

-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ static void DuplicateInputs(benchmark::Bench& bench)
2525
CMutableTransaction coinbaseTx{};
2626
CMutableTransaction naughtyTx{};
2727

28-
assert(std::addressof(::ChainActive()) == std::addressof(testing_setup->m_node.chainman->ActiveChain()));
2928
CBlockIndex* pindexPrev = testing_setup->m_node.chainman->ActiveChain().Tip();
3029
assert(pindexPrev != nullptr);
3130
block.nBits = GetNextWorkRequired(pindexPrev, &block, chainparams.GetConsensus());

src/dsnotificationinterface.cpp

+4-2
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ CDSNotificationInterface::CDSNotificationInterface(CConnman& connman,
2828
CMasternodeSync& mn_sync,
2929
CGovernanceManager& govman,
3030
PeerManager& peerman,
31+
const ChainstateManager& chainman,
3132
const CActiveMasternodeManager* const mn_activeman,
3233
const std::unique_ptr<CDeterministicMNManager>& dmnman,
3334
const std::unique_ptr<LLMQContext>& llmq_ctx,
@@ -36,15 +37,16 @@ CDSNotificationInterface::CDSNotificationInterface(CConnman& connman,
3637
m_mn_sync(mn_sync),
3738
m_govman(govman),
3839
m_peerman(peerman),
40+
m_chainman(chainman),
3941
m_mn_activeman(mn_activeman),
4042
m_dmnman(dmnman),
4143
m_llmq_ctx(llmq_ctx),
4244
m_cj_ctx(cj_ctx) {}
4345

4446
void CDSNotificationInterface::InitializeCurrentBlockTip()
4547
{
46-
SynchronousUpdatedBlockTip(::ChainActive().Tip(), nullptr, ::ChainstateActive().IsInitialBlockDownload());
47-
UpdatedBlockTip(::ChainActive().Tip(), nullptr, ::ChainstateActive().IsInitialBlockDownload());
48+
SynchronousUpdatedBlockTip(m_chainman.ActiveChain().Tip(), nullptr, m_chainman.ActiveChainstate().IsInitialBlockDownload());
49+
UpdatedBlockTip(m_chainman.ActiveChain().Tip(), nullptr, m_chainman.ActiveChainstate().IsInitialBlockDownload());
4850
}
4951

5052
void CDSNotificationInterface::AcceptedBlockHeader(const CBlockIndex *pindexNew)

src/dsnotificationinterface.h

+3
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ class CActiveMasternodeManager;
1111
class CConnman;
1212
class CDeterministicMNManager;
1313
class CGovernanceManager;
14+
class ChainstateManager;
1415
class CMasternodeSync;
1516
class PeerManager;
1617
struct CJContext;
@@ -23,6 +24,7 @@ class CDSNotificationInterface : public CValidationInterface
2324
CMasternodeSync& mn_sync,
2425
CGovernanceManager& govman,
2526
PeerManager& peerman,
27+
const ChainstateManager& chainman,
2628
const CActiveMasternodeManager* const mn_activeman,
2729
const std::unique_ptr<CDeterministicMNManager>& dmnman,
2830
const std::unique_ptr<LLMQContext>& llmq_ctx,
@@ -50,6 +52,7 @@ class CDSNotificationInterface : public CValidationInterface
5052
CMasternodeSync& m_mn_sync;
5153
CGovernanceManager& m_govman;
5254
PeerManager& m_peerman;
55+
const ChainstateManager& m_chainman;
5356
const CActiveMasternodeManager* const m_mn_activeman;
5457
const std::unique_ptr<CDeterministicMNManager>& m_dmnman;
5558
const std::unique_ptr<LLMQContext>& m_llmq_ctx;

src/index/base.cpp

+1-2
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
#include <tinyformat.h>
1111
#include <util/thread.h>
1212
#include <util/translation.h>
13-
#include <validation.h> // For g_chainman
13+
#include <validation.h>
1414
#include <warnings.h>
1515

1616
constexpr uint8_t DB_BEST_BLOCK{'B'};
@@ -349,7 +349,6 @@ void BaseIndex::Interrupt()
349349

350350
bool BaseIndex::Start(CChainState& active_chainstate)
351351
{
352-
assert(std::addressof(::ChainstateActive()) == std::addressof(active_chainstate));
353352
m_chainstate = &active_chainstate;
354353
// Need to register this ValidationInterface before running Init(), so that
355354
// callbacks are not missed if Init sets m_synced to true.

src/init.cpp

+22-22
Original file line numberDiff line numberDiff line change
@@ -402,7 +402,7 @@ void Shutdown(NodeContext& node)
402402
ECC_Stop();
403403
node.mempool.reset();
404404
node.fee_estimator.reset();
405-
node.chainman = nullptr;
405+
node.chainman.reset();
406406
node.scheduler.reset();
407407

408408
try {
@@ -883,12 +883,12 @@ static void StartupNotify(const ArgsManager& args)
883883
}
884884
#endif
885885

886-
static void PeriodicStats(ArgsManager& args, const CTxMemPool& mempool)
886+
static void PeriodicStats(ArgsManager& args, ChainstateManager& chainman, const CTxMemPool& mempool)
887887
{
888888
assert(args.GetBoolArg("-statsenabled", DEFAULT_STATSD_ENABLE));
889889
CCoinsStats stats{CoinStatsHashType::NONE};
890-
::ChainstateActive().ForceFlushStateToDisk();
891-
if (WITH_LOCK(cs_main, return GetUTXOStats(&::ChainstateActive().CoinsDB(), std::ref(g_chainman.m_blockman), stats, RpcInterruptionPoint, ::ChainActive().Tip()))) {
890+
chainman.ActiveChainstate().ForceFlushStateToDisk();
891+
if (WITH_LOCK(cs_main, return GetUTXOStats(&chainman.ActiveChainstate().CoinsDB(), std::ref(chainman.m_blockman), stats, RpcInterruptionPoint, chainman.ActiveChain().Tip()))) {
892892
statsClient.gauge("utxoset.tx", stats.nTransactions, 1.0f);
893893
statsClient.gauge("utxoset.txOutputs", stats.nTransactionOutputs, 1.0f);
894894
statsClient.gauge("utxoset.dbSizeBytes", stats.nDiskSize, 1.0f);
@@ -902,7 +902,7 @@ static void PeriodicStats(ArgsManager& args, const CTxMemPool& mempool)
902902
}
903903

904904
// short version of GetNetworkHashPS(120, -1);
905-
CBlockIndex *tip = ::ChainActive().Tip();
905+
CBlockIndex *tip = chainman.ActiveChain().Tip();
906906
CBlockIndex *pindex = tip;
907907
int64_t minTime = pindex->GetBlockTime();
908908
int64_t maxTime = minTime;
@@ -923,7 +923,7 @@ static void PeriodicStats(ArgsManager& args, const CTxMemPool& mempool)
923923
// No need for cs_main, we never use null tip here
924924
statsClient.gaugeDouble("network.difficulty", (double)GetDifficulty(tip));
925925

926-
statsClient.gauge("transactions.txCacheSize", WITH_LOCK(cs_main, return ::ChainstateActive().CoinsTip().GetCacheSize()), 1.0f);
926+
statsClient.gauge("transactions.txCacheSize", WITH_LOCK(cs_main, return chainman.ActiveChainstate().CoinsTip().GetCacheSize()), 1.0f);
927927
statsClient.gauge("transactions.totalTransactions", tip->nChainTx, 1.0f);
928928

929929
{
@@ -1716,8 +1716,8 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
17161716
node.mempool = std::make_unique<CTxMemPool>(node.fee_estimator.get(), check_ratio);
17171717

17181718
assert(!node.chainman);
1719-
node.chainman = &g_chainman;
1720-
ChainstateManager& chainman = *Assert(node.chainman);
1719+
node.chainman = std::make_unique<ChainstateManager>();
1720+
ChainstateManager& chainman = *node.chainman;
17211721

17221722
assert(!node.mn_metaman);
17231723
node.mn_metaman = std::make_unique<CMasternodeMetaMan>();
@@ -1913,7 +1913,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
19131913
#endif
19141914

19151915
pdsNotificationInterface = new CDSNotificationInterface(
1916-
*node.connman, *node.mn_sync, *node.govman, *node.peerman, node.mn_activeman.get(), node.dmnman, node.llmq_ctx, node.cj_ctx
1916+
*node.connman, *node.mn_sync, *node.govman, *node.peerman, chainman, node.mn_activeman.get(), node.dmnman, node.llmq_ctx, node.cj_ctx
19171917
);
19181918
RegisterValidationInterface(pdsNotificationInterface);
19191919

@@ -2016,7 +2016,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
20162016
node.llmq_ctx = std::make_unique<LLMQContext>(chainman.ActiveChainstate(), *node.connman, *node.dmnman, *node.evodb, *node.mn_metaman, *node.mnhf_manager, *node.sporkman,
20172017
*node.mempool, node.mn_activeman.get(), *node.mn_sync, node.peerman, /* unit_tests = */ false, /* wipe = */ fReset || fReindexChainState);
20182018
// Enable CMNHFManager::{Process, Undo}Block
2019-
node.mnhf_manager->ConnectManagers(node.chainman, node.llmq_ctx->qman.get());
2019+
node.mnhf_manager->ConnectManagers(node.chainman.get(), node.llmq_ctx->qman.get());
20202020
// Have to start it early to let VerifyDB check ChainLock signatures in coinbase
20212021
node.llmq_ctx->Start();
20222022

@@ -2050,12 +2050,12 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
20502050
// If the loaded chain has a wrong genesis, bail out immediately
20512051
// (we're likely using a testnet datadir, or the other way around).
20522052
if (!chainman.BlockIndex().empty() &&
2053-
!g_chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
2053+
!chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashGenesisBlock)) {
20542054
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
20552055
}
20562056

20572057
if (!chainparams.GetConsensus().hashDevnetGenesisBlock.IsNull() && !chainman.BlockIndex().empty() &&
2058-
!g_chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashDevnetGenesisBlock)) {
2058+
!chainman.m_blockman.LookupBlockIndex(chainparams.GetConsensus().hashDevnetGenesisBlock)) {
20592059
return InitError(_("Incorrect or no devnet genesis block found. Wrong datadir for devnet specified?"));
20602060
}
20612061

@@ -2088,7 +2088,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
20882088
// If we're not mid-reindex (based on disk + args), add a genesis block on disk
20892089
// (otherwise we use the one already on disk).
20902090
// This is called again in ThreadImport after the reindex completes.
2091-
if (!fReindex && !::ChainstateActive().LoadGenesisBlock()) {
2091+
if (!fReindex && !chainman.ActiveChainstate().LoadGenesisBlock()) {
20922092
strLoadError = _("Error initializing block database");
20932093
break;
20942094
}
@@ -2132,7 +2132,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
21322132
// TODO: CEvoDB instance should probably be a part of CChainState
21332133
// (for multiple chainstates to actually work in parallel)
21342134
// and not a global
2135-
if (&::ChainstateActive() == chainstate && !node.evodb->CommitRootTransaction()) {
2135+
if (&chainman.ActiveChainstate() == chainstate && !node.evodb->CommitRootTransaction()) {
21362136
strLoadError = _("Failed to commit EvoDB");
21372137
failed_chainstate_init = true;
21382138
break;
@@ -2210,7 +2210,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
22102210
// TODO: CEvoDB instance should probably be a part of CChainState
22112211
// (for multiple chainstates to actually work in parallel)
22122212
// and not a global
2213-
if (&::ChainstateActive() == chainstate && !node.evodb->IsEmpty()) {
2213+
if (&chainman.ActiveChainstate() == chainstate && !node.evodb->IsEmpty()) {
22142214
// EvoDB processed some blocks earlier but we have no blocks anymore, something is wrong
22152215
strLoadError = _("Error initializing block database");
22162216
failed_verification = true;
@@ -2271,7 +2271,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
22712271

22722272
// ********************************************************* Step 7d: Setup other Dash services
22732273

2274-
bool fLoadCacheFiles = !(fReindex || fReindexChainState) && (::ChainActive().Tip() != nullptr);
2274+
bool fLoadCacheFiles = !(fReindex || fReindexChainState) && (chainman.ActiveChain().Tip() != nullptr);
22752275

22762276
if (!node.netfulfilledman->LoadCache(fLoadCacheFiles)) {
22772277
auto file_path = (GetDataDir() / "netfulfilled.dat").string();
@@ -2302,21 +2302,21 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
23022302
// ********************************************************* Step 8: start indexers
23032303
if (args.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
23042304
g_txindex = std::make_unique<TxIndex>(nTxIndexCache, false, fReindex);
2305-
if (!g_txindex->Start(::ChainstateActive())) {
2305+
if (!g_txindex->Start(chainman.ActiveChainstate())) {
23062306
return false;
23072307
}
23082308
}
23092309

23102310
for (const auto& filter_type : g_enabled_filter_types) {
23112311
InitBlockFilterIndex(filter_type, filter_index_cache, false, fReindex);
2312-
if (!GetBlockFilterIndex(filter_type)->Start(::ChainstateActive())) {
2312+
if (!GetBlockFilterIndex(filter_type)->Start(chainman.ActiveChainstate())) {
23132313
return false;
23142314
}
23152315
}
23162316

23172317
if (args.GetBoolArg("-coinstatsindex", DEFAULT_COINSTATSINDEX)) {
23182318
g_coin_stats_index = std::make_unique<CoinStatsIndex>(/* cache size */ 0, false, fReindex);
2319-
if (!g_coin_stats_index->Start(::ChainstateActive())) {
2319+
if (!g_coin_stats_index->Start(chainman.ActiveChainstate())) {
23202320
return false;
23212321
}
23222322
}
@@ -2383,7 +2383,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
23832383

23842384
if (args.GetBoolArg("-statsenabled", DEFAULT_STATSD_ENABLE)) {
23852385
int nStatsPeriod = std::min(std::max((int)args.GetArg("-statsperiod", DEFAULT_STATSD_PERIOD), MIN_STATSD_PERIOD), MAX_STATSD_PERIOD);
2386-
node.scheduler->scheduleEvery(std::bind(&PeriodicStats, std::ref(*node.args), std::cref(*node.mempool)), std::chrono::seconds{nStatsPeriod});
2386+
node.scheduler->scheduleEvery(std::bind(&PeriodicStats, std::ref(*node.args), std::ref(chainman), std::cref(*node.mempool)), std::chrono::seconds{nStatsPeriod});
23872387
}
23882388

23892389
// ********************************************************* Step 11: import blocks
@@ -2400,7 +2400,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
24002400
// Either install a handler to notify us when genesis activates, or set fHaveGenesis directly.
24012401
// No locking, as this happens before any background thread is started.
24022402
boost::signals2::connection block_notify_genesis_wait_connection;
2403-
if (::ChainActive().Tip() == nullptr) {
2403+
if (chainman.ActiveChain().Tip() == nullptr) {
24042404
block_notify_genesis_wait_connection = uiInterface.NotifyBlockTip_connect(std::bind(BlockNotifyGenesisWait, std::placeholders::_2));
24052405
} else {
24062406
fHaveGenesis = true;
@@ -2476,7 +2476,7 @@ bool AppInitMain(const CoreContext& context, NodeContext& node, interfaces::Bloc
24762476
tip_info->header_time = ::pindexBestHeader->GetBlockTime();
24772477
}
24782478
}
2479-
LogPrintf("::ChainActive().Height() = %d\n", chain_active_height);
2479+
LogPrintf("nBestHeight = %d\n", chain_active_height);
24802480
if (node.peerman) node.peerman->SetBestHeight(chain_active_height);
24812481

24822482
// Map ports with UPnP or NAT-PMP.

src/miner.cpp

-2
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,6 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
132132
pblocktemplate->vTxSigOps.push_back(-1); // updated at end
133133

134134
LOCK2(cs_main, m_mempool.cs);
135-
assert(std::addressof(*::ChainActive().Tip()) == std::addressof(*m_chainstate.m_chain.Tip()));
136135
CBlockIndex* pindexPrev = m_chainstate.m_chain.Tip();
137136
assert(pindexPrev != nullptr);
138137
nHeight = pindexPrev->nHeight + 1;
@@ -265,7 +264,6 @@ std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& sc
265264
pblocktemplate->vTxSigOps[0] = GetLegacySigOpCount(*pblock->vtx[0]);
266265

267266
BlockValidationState state;
268-
assert(std::addressof(::ChainstateActive()) == std::addressof(m_chainstate));
269267
if (!TestBlockValidity(state, m_clhandler, m_evoDb, chainparams, m_chainstate, *pblock, pindexPrev, false, false)) {
270268
throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, state.ToString()));
271269
}

src/net_processing.cpp

-1
Original file line numberDiff line numberDiff line change
@@ -1899,7 +1899,6 @@ PeerManagerImpl::PeerManagerImpl(const CChainParams& chainparams, CConnman& conn
18991899
m_mn_activeman(mn_activeman),
19001900
m_ignore_incoming_txs(ignore_incoming_txs)
19011901
{
1902-
assert(std::addressof(g_chainman) == std::addressof(m_chainman));
19031902
// Stale tip checking and peer eviction are on two different timers, but we
19041903
// don't want them to get out of sync due to drift in the scheduler, so we
19051904
// combine them in one function and schedule at the quicker (peer-eviction)

src/node/blockstorage.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ void ThreadImport(ChainstateManager& chainman, CDeterministicMNManager& dmnman,
210210
}
211211

212212
if (mn_activeman != nullptr) {
213-
mn_activeman->Init(::ChainActive().Tip());
213+
mn_activeman->Init(chainman.ActiveTip());
214214
}
215215

216216
g_wallet_init_interface.AutoLockMasternodeCollaterals();

src/node/coin.cpp

-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ void FindCoins(const NodeContext& node, std::map<COutPoint, Coin>& coins)
1313
assert(node.mempool);
1414
assert(node.chainman);
1515
LOCK2(cs_main, node.mempool->cs);
16-
assert(std::addressof(::ChainstateActive()) == std::addressof(node.chainman->ActiveChainstate()));
1716
CCoinsViewCache& chain_view = node.chainman->ActiveChainstate().CoinsTip();
1817
CCoinsViewMemPool mempool_view(&chain_view, *node.mempool);
1918
for (auto& coin : coins) {

src/node/coinstats.cpp

-1
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,6 @@ static bool GetUTXOStats(CCoinsView* view, BlockManager& blockman, CCoinsStats&
113113

114114
if (!pindex) {
115115
LOCK(cs_main);
116-
assert(std::addressof(g_chainman.m_blockman) == std::addressof(blockman));
117116
pindex = blockman.LookupBlockIndex(view->GetBestBlock());
118117
}
119118
stats.nHeight = Assert(pindex)->nHeight;

src/node/context.cpp

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#include <scheduler.h>
2727
#include <spork.h>
2828
#include <txmempool.h>
29+
#include <validation.h>
2930

3031
NodeContext::NodeContext() {}
3132
NodeContext::~NodeContext() {}

src/node/context.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ struct NodeContext {
5858
std::unique_ptr<CTxMemPool> mempool;
5959
std::unique_ptr<CBlockPolicyEstimator> fee_estimator;
6060
std::unique_ptr<PeerManager> peerman;
61-
ChainstateManager* chainman{nullptr}; // Currently a raw pointer because the memory is not managed by this struct
61+
std::unique_ptr<ChainstateManager> chainman;
6262
std::unique_ptr<BanMan> banman;
6363
ArgsManager* args{nullptr}; // Currently a raw pointer because the memory is not managed by this struct
6464
std::unique_ptr<interfaces::Chain> chain;

0 commit comments

Comments
 (0)