From 1f436f8aee9e12f7053cbc18dcb00004a853b53d Mon Sep 17 00:00:00 2001 From: Kittywhiskers Van Gogh <63189531+kittywhiskers@users.noreply.github.com> Date: Sat, 16 Oct 2021 16:24:22 +0530 Subject: [PATCH] merge bitcoin#15948: rename chainActive Co-authored-by: UdjinM6 --- src/dsnotificationinterface.cpp | 4 +- src/evo/deterministicmns.cpp | 16 +- src/evo/simplifiedmns.cpp | 4 +- src/governance/object.cpp | 4 +- src/index/base.cpp | 16 +- src/index/txindex.cpp | 2 +- src/init.cpp | 22 +-- src/interfaces/node.cpp | 12 +- src/interfaces/wallet.cpp | 6 +- src/llmq/blockprocessor.cpp | 16 +- src/llmq/chainlocks.cpp | 12 +- src/llmq/instantsend.cpp | 10 +- src/llmq/quorums.cpp | 2 +- src/llmq/signing.cpp | 6 +- src/masternode/payments.cpp | 2 +- src/miner.cpp | 2 +- src/net_processing.cpp | 92 ++++----- src/policy/fees.cpp | 2 +- src/qt/test/wallettests.cpp | 4 +- src/rest.cpp | 20 +- src/rpc/blockchain.cpp | 52 +++--- src/rpc/governance.cpp | 2 +- src/rpc/masternode.cpp | 8 +- src/rpc/mining.cpp | 28 +-- src/rpc/misc.cpp | 2 +- src/rpc/rawtransaction.cpp | 10 +- src/rpc/rpcevo.cpp | 18 +- src/rpc/rpcquorums.cpp | 8 +- src/spork.cpp | 4 +- src/test/blockfilter_index_tests.cpp | 12 +- src/test/denialofservice_tests.cpp | 4 +- src/test/evo_deterministicmns_tests.cpp | 88 ++++----- src/test/miner_tests.cpp | 62 +++---- src/test/test_dash.cpp | 6 +- src/test/txvalidationcache_tests.cpp | 10 +- src/test/validation_block_tests.cpp | 4 +- src/txmempool.h | 2 +- src/validation.cpp | 237 ++++++++++++------------ src/validation.h | 10 +- src/wallet/rpcdump.cpp | 30 +-- src/wallet/rpcwallet.cpp | 18 +- src/wallet/test/coinjoin_tests.cpp | 4 +- src/wallet/test/wallet_tests.cpp | 20 +- src/wallet/wallet.cpp | 52 +++--- 44 files changed, 474 insertions(+), 471 deletions(-) diff --git a/src/dsnotificationinterface.cpp b/src/dsnotificationinterface.cpp index 159beac860..35820a236c 100644 --- a/src/dsnotificationinterface.cpp +++ b/src/dsnotificationinterface.cpp @@ -23,8 +23,8 @@ void CDSNotificationInterface::InitializeCurrentBlockTip() { LOCK(cs_main); - SynchronousUpdatedBlockTip(chainActive.Tip(), nullptr, IsInitialBlockDownload()); - UpdatedBlockTip(chainActive.Tip(), nullptr, IsInitialBlockDownload()); + SynchronousUpdatedBlockTip(::ChainActive().Tip(), nullptr, IsInitialBlockDownload()); + UpdatedBlockTip(::ChainActive().Tip(), nullptr, IsInitialBlockDownload()); } void CDSNotificationInterface::AcceptedBlockHeader(const CBlockIndex *pindexNew) diff --git a/src/evo/deterministicmns.cpp b/src/evo/deterministicmns.cpp index 8a5de8fb94..898857695f 100644 --- a/src/evo/deterministicmns.cpp +++ b/src/evo/deterministicmns.cpp @@ -1174,7 +1174,7 @@ bool CDeterministicMNManager::UpgradeDBIfNeeded() { LOCK(cs_main); - if (chainActive.Tip() == nullptr) { + if (::ChainActive().Tip() == nullptr) { // should have no records return evoDb.IsEmpty(); } @@ -1186,15 +1186,15 @@ bool CDeterministicMNManager::UpgradeDBIfNeeded() // Removing the old EVODB_BEST_BLOCK value early results in older version to crash immediately, even if the upgrade // process is cancelled in-between. But if the new version sees that the old EVODB_BEST_BLOCK is already removed, // then we must assume that the upgrade process was already running before but was interrupted. - if (chainActive.Height() > 1 && !evoDb.GetRawDB().Exists(std::string("b_b"))) { + if (::ChainActive().Height() > 1 && !evoDb.GetRawDB().Exists(std::string("b_b"))) { return false; } evoDb.GetRawDB().Erase(std::string("b_b")); - if (chainActive.Height() < Params().GetConsensus().DIP0003Height) { + if (::ChainActive().Height() < Params().GetConsensus().DIP0003Height) { // not reached DIP3 height yet, so no upgrade needed auto dbTx = evoDb.BeginTransaction(); - evoDb.WriteBestBlock(chainActive.Tip()->GetBlockHash()); + evoDb.WriteBestBlock(::ChainActive().Tip()->GetBlockHash()); dbTx->Commit(); return true; } @@ -1205,10 +1205,10 @@ bool CDeterministicMNManager::UpgradeDBIfNeeded() CDeterministicMNList curMNList; curMNList.SetHeight(Params().GetConsensus().DIP0003Height - 1); - curMNList.SetBlockHash(chainActive[Params().GetConsensus().DIP0003Height - 1]->GetBlockHash()); + curMNList.SetBlockHash(::ChainActive()[Params().GetConsensus().DIP0003Height - 1]->GetBlockHash()); - for (int nHeight = Params().GetConsensus().DIP0003Height; nHeight <= chainActive.Height(); nHeight++) { - auto pindex = chainActive[nHeight]; + for (int nHeight = Params().GetConsensus().DIP0003Height; nHeight <= ::ChainActive().Height(); nHeight++) { + auto pindex = ::ChainActive()[nHeight]; CDeterministicMNList newMNList; UpgradeDiff(batch, pindex, curMNList, newMNList); @@ -1228,7 +1228,7 @@ bool CDeterministicMNManager::UpgradeDBIfNeeded() // Writing EVODB_BEST_BLOCK (which is b_b2 now) marks the DB as upgraded auto dbTx = evoDb.BeginTransaction(); - evoDb.WriteBestBlock(chainActive.Tip()->GetBlockHash()); + evoDb.WriteBestBlock(::ChainActive().Tip()->GetBlockHash()); dbTx->Commit(); evoDb.GetRawDB().CompactFull(); diff --git a/src/evo/simplifiedmns.cpp b/src/evo/simplifiedmns.cpp index fa6ffc946f..fa6532e328 100644 --- a/src/evo/simplifiedmns.cpp +++ b/src/evo/simplifiedmns.cpp @@ -189,7 +189,7 @@ bool BuildSimplifiedMNListDiff(const uint256& baseBlockHash, const uint256& bloc AssertLockHeld(cs_main); mnListDiffRet = CSimplifiedMNListDiff(); - const CBlockIndex* baseBlockIndex = chainActive.Genesis(); + const CBlockIndex* baseBlockIndex = ::ChainActive().Genesis(); if (!baseBlockHash.IsNull()) { baseBlockIndex = LookupBlockIndex(baseBlockHash); if (!baseBlockIndex) { @@ -204,7 +204,7 @@ bool BuildSimplifiedMNListDiff(const uint256& baseBlockHash, const uint256& bloc return false; } - if (!chainActive.Contains(baseBlockIndex) || !chainActive.Contains(blockIndex)) { + if (!::ChainActive().Contains(baseBlockIndex) || !::ChainActive().Contains(blockIndex)) { errorRet = strprintf("block %s and %s are not in the same chain", baseBlockHash.ToString(), blockHash.ToString()); return false; } diff --git a/src/governance/object.cpp b/src/governance/object.cpp index b482a03489..25831e7721 100644 --- a/src/governance/object.cpp +++ b/src/governance/object.cpp @@ -583,8 +583,8 @@ bool CGovernanceObject::IsCollateralValid(std::string& strError, bool& fMissingC int nConfirmationsIn = 0; if (nBlockHash != uint256()) { const CBlockIndex* pindex = LookupBlockIndex(nBlockHash); - if (pindex && chainActive.Contains(pindex)) { - nConfirmationsIn += chainActive.Height() - pindex->nHeight + 1; + if (pindex && ::ChainActive().Contains(pindex)) { + nConfirmationsIn += ::ChainActive().Height() - pindex->nHeight + 1; } } diff --git a/src/index/base.cpp b/src/index/base.cpp index 7881368386..970cc8798c 100644 --- a/src/index/base.cpp +++ b/src/index/base.cpp @@ -62,9 +62,9 @@ bool BaseIndex::Init() if (locator.IsNull()) { m_best_block_index = nullptr; } else { - m_best_block_index = FindForkInGlobalIndex(chainActive, locator); + m_best_block_index = FindForkInGlobalIndex(::ChainActive(), locator); } - m_synced = m_best_block_index.load() == chainActive.Tip(); + m_synced = m_best_block_index.load() == ::ChainActive().Tip(); return true; } @@ -73,15 +73,15 @@ static const CBlockIndex* NextSyncBlock(const CBlockIndex* pindex_prev) EXCLUSIV AssertLockHeld(cs_main); if (!pindex_prev) { - return chainActive.Genesis(); + return ::ChainActive().Genesis(); } - const CBlockIndex* pindex = chainActive.Next(pindex_prev); + const CBlockIndex* pindex = ::ChainActive().Next(pindex_prev); if (pindex) { return pindex; } - return chainActive.Next(chainActive.FindFork(pindex_prev)); + return ::ChainActive().Next(::ChainActive().FindFork(pindex_prev)); } void BaseIndex::ThreadSync() @@ -167,7 +167,7 @@ bool BaseIndex::Commit() bool BaseIndex::CommitInternal(CDBBatch& batch) { LOCK(cs_main); - GetDB().WriteBestBlock(batch, chainActive.GetLocator(m_best_block_index)); + GetDB().WriteBestBlock(batch, ::ChainActive().GetLocator(m_best_block_index)); return true; } @@ -279,9 +279,9 @@ bool BaseIndex::BlockUntilSyncedToCurrentChain() { // Skip the queue-draining stuff if we know we're caught up with - // chainActive.Tip(). + // ::ChainActive().Tip(). LOCK(cs_main); - const CBlockIndex* chain_tip = chainActive.Tip(); + const CBlockIndex* chain_tip = ::ChainActive().Tip(); const CBlockIndex* best_block_index = m_best_block_index.load(); if (best_block_index->GetAncestor(chain_tip->nHeight) == chain_tip) { return true; diff --git a/src/index/txindex.cpp b/src/index/txindex.cpp index 7a3df975f4..c7c60d5337 100644 --- a/src/index/txindex.cpp +++ b/src/index/txindex.cpp @@ -206,7 +206,7 @@ bool TxIndex::Init() // Attempt to migrate txindex from the old database to the new one. Even if // chain_tip is null, the node could be reindexing and we still want to // delete txindex records in the old database. - if (!m_db->MigrateData(*pblocktree, chainActive.GetLocator())) { + if (!m_db->MigrateData(*pblocktree, ::ChainActive().GetLocator())) { return false; } diff --git a/src/init.cpp b/src/init.cpp index d837a483e5..0822c7f50e 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -665,7 +665,7 @@ void SetupServerArgs() hidden_args.emplace_back("-zmqpubrawtxlocksighwm="); #endif - gArgs.AddArg("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST); + gArgs.AddArg("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, ::ChainActive() and mapBlocksUnlinked occasionally. (default: %u, regtest: %u)", defaultChainParams->DefaultConsistencyChecks(), regtestChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-checkblocks=", strprintf("How many blocks to check at startup (default: %u, 0 = all)", DEFAULT_CHECKBLOCKS), true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-checklevel=", strprintf("How thorough the block verification of -checkblocks is: " "level 0 reads the blocks from disk, " @@ -949,7 +949,7 @@ static void ThreadImport(std::vector vImportFiles) // force UpdatedBlockTip to initialize nCachedBlockHeight for DS, MN payments and budgets // but don't call it directly to prevent triggering of other listeners like zmq etc. - // GetMainSignals().UpdatedBlockTip(chainActive.Tip()); + // GetMainSignals().UpdatedBlockTip(::ChainActive().Tip()); pdsNotificationInterface->InitializeCurrentBlockTip(); { @@ -971,7 +971,7 @@ static void ThreadImport(std::vector vImportFiles) const CBlockIndex* pindexTip; { LOCK(cs_main); - pindexTip = chainActive.Tip(); + pindexTip = ::ChainActive().Tip(); } activeMasternodeManager->Init(pindexTip); } @@ -1004,7 +1004,7 @@ void PeriodicStats() CBlockIndex *tip; { LOCK(cs_main); - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); assert(tip); } CBlockIndex *pindex = tip; @@ -2114,12 +2114,12 @@ bool AppInitMain(InitInterfaces& interfaces) bool is_coinsview_empty = fReset || fReindexChainState || pcoinsTip->GetBestBlock().IsNull(); if (!is_coinsview_empty) { - // LoadChainTip sets chainActive based on pcoinsTip's best block + // LoadChainTip sets ::ChainActive() based on pcoinsTip's best block if (!LoadChainTip(chainparams)) { strLoadError = _("Error initializing block database"); break; } - assert(chainActive.Tip() != NULL); + assert(::ChainActive().Tip() != NULL); } if (is_coinsview_empty && !evoDb->IsEmpty()) { @@ -2140,7 +2140,7 @@ bool AppInitMain(InitInterfaces& interfaces) MIN_BLOCKS_TO_KEEP); } - CBlockIndex* tip = chainActive.Tip(); + CBlockIndex* tip = ::ChainActive().Tip(); RPCNotifyBlockChange(true, tip); if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) { strLoadError = _("The block database contains a block which appears to be from the future. " @@ -2298,7 +2298,7 @@ bool AppInitMain(InitInterfaces& interfaces) { LOCK(cs_main); // was blocks/chainstate deleted? - if (chainActive.Tip() == nullptr) { + if (::ChainActive().Tip() == nullptr) { fLoadCacheFiles = false; } } @@ -2382,7 +2382,7 @@ bool AppInitMain(InitInterfaces& interfaces) // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly. // No locking, as this happens before any background thread is started. - if (chainActive.Tip() == nullptr) { + if (::ChainActive().Tip() == nullptr) { uiInterface.NotifyBlockTip_connect(BlockNotifyGenesisWait); } else { fHaveGenesis = true; @@ -2425,9 +2425,9 @@ bool AppInitMain(InitInterfaces& interfaces) { LOCK(cs_main); LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); - chain_active_height = chainActive.Height(); + chain_active_height = ::ChainActive().Height(); } - LogPrintf("chainActive.Height() = %d\n", chain_active_height); + LogPrintf("::ChainActive().Height() = %d\n", chain_active_height); if (gArgs.GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) StartTorControl(); diff --git a/src/interfaces/node.cpp b/src/interfaces/node.cpp index 4da114d665..445e1dfb3b 100644 --- a/src/interfaces/node.cpp +++ b/src/interfaces/node.cpp @@ -294,21 +294,21 @@ public: int getNumBlocks() override { LOCK(::cs_main); - return ::chainActive.Height(); + return ::ChainActive().Height(); } int64_t getLastBlockTime() override { LOCK(::cs_main); - if (::chainActive.Tip()) { - return ::chainActive.Tip()->GetBlockTime(); + if (::ChainActive().Tip()) { + return ::ChainActive().Tip()->GetBlockTime(); } return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network } std::string getLastBlockHash() override { LOCK(::cs_main); - if (::chainActive.Tip()) { - return ::chainActive.Tip()->GetBlockHash().ToString(); + if (::ChainActive().Tip()) { + return ::ChainActive().Tip()->GetBlockHash().ToString(); } return Params().GenesisBlock().GetHash().ToString(); // Genesis block's hash of current network } @@ -317,7 +317,7 @@ public: const CBlockIndex* tip; { LOCK(::cs_main); - tip = ::chainActive.Tip(); + tip = ::ChainActive().Tip(); } return GuessVerificationProgress(Params().TxData(), tip); } diff --git a/src/interfaces/wallet.cpp b/src/interfaces/wallet.cpp index dc0012dd5a..5125885189 100644 --- a/src/interfaces/wallet.cpp +++ b/src/interfaces/wallet.cpp @@ -383,7 +383,7 @@ public: return false; } tx_status = MakeWalletTxStatus(*locked_chain, mi->second); - block_time = ::chainActive.Tip()->GetBlockTime(); + block_time = ::ChainActive().Tip()->GetBlockTime(); return true; } WalletTx getWalletTxDetails(const uint256& txid, @@ -396,7 +396,7 @@ public: LOCK(m_wallet->cs_wallet); auto mi = m_wallet->mapWallet.find(txid); if (mi != m_wallet->mapWallet.end()) { - num_blocks = ::chainActive.Height(); + num_blocks = ::ChainActive().Height(); in_mempool = mi->second.InMempool(); order_form = mi->second.vOrderForm; tx_status = MakeWalletTxStatus(*locked_chain, mi->second); @@ -431,7 +431,7 @@ public: return false; } balances = getBalances(); - num_blocks = ::chainActive.Height(); + num_blocks = ::ChainActive().Height(); return true; } CAmount getBalance() override diff --git a/src/llmq/blockprocessor.cpp b/src/llmq/blockprocessor.cpp index a48202cef6..6551a9b48d 100644 --- a/src/llmq/blockprocessor.cpp +++ b/src/llmq/blockprocessor.cpp @@ -78,7 +78,7 @@ void CQuorumBlockProcessor::ProcessMessage(CNode* pfrom, const std::string& strC // fully synced return; } - if (chainActive.Tip()->GetAncestor(pquorumIndex->nHeight) != pquorumIndex) { + if (::ChainActive().Tip()->GetAncestor(pquorumIndex->nHeight) != pquorumIndex) { LogPrint(BCLog::LLMQ, "CQuorumBlockProcessor::%s -- block %s not in active chain, peer=%d\n", __func__, qc.quorumHash.ToString(), pfrom->GetId()); // same, can't punish @@ -143,7 +143,7 @@ bool CQuorumBlockProcessor::ProcessBlock(const CBlock& block, const CBlockIndex* // Note: must only check quorums that were enabled at the _previous_ block height to match mining logic for (const auto& type : CLLMQUtils::GetEnabledQuorumTypes(pindex->pprev)) { // skip these checks when replaying blocks after the crash - if (!chainActive.Tip()) { + if (!::ChainActive().Tip()) { break; } @@ -194,7 +194,7 @@ bool CQuorumBlockProcessor::ProcessCommitment(int nHeight, const uint256& blockH uint256 quorumHash = GetQuorumBlockHash(qc.llmqType, nHeight); // skip `bad-qc-block` checks below when replaying blocks after the crash - if (!chainActive.Tip()) { + if (!::ChainActive().Tip()) { quorumHash = qc.quorumHash; } @@ -287,20 +287,20 @@ bool CQuorumBlockProcessor::UpgradeDB() { LOCK(cs_main); - if (chainActive.Tip() == nullptr) { + if (::ChainActive().Tip() == nullptr) { // should have no records return evoDb.IsEmpty(); } uint256 bestBlock; - if (evoDb.GetRawDB().Read(DB_BEST_BLOCK_UPGRADE, bestBlock) && bestBlock == chainActive.Tip()->GetBlockHash()) { + if (evoDb.GetRawDB().Read(DB_BEST_BLOCK_UPGRADE, bestBlock) && bestBlock == ::ChainActive().Tip()->GetBlockHash()) { return true; } LogPrintf("CQuorumBlockProcessor::%s -- Upgrading DB...\n", __func__); - if (chainActive.Height() >= Params().GetConsensus().DIP0003EnforcementHeight) { - auto pindex = chainActive[Params().GetConsensus().DIP0003EnforcementHeight]; + if (::ChainActive().Height() >= Params().GetConsensus().DIP0003EnforcementHeight) { + auto pindex = ::ChainActive()[Params().GetConsensus().DIP0003EnforcementHeight]; while (pindex) { if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) { // Too late, we already pruned blocks we needed to reprocess commitments @@ -326,7 +326,7 @@ bool CQuorumBlockProcessor::UpgradeDB() evoDb.GetRawDB().Write(DB_BEST_BLOCK_UPGRADE, pindex->GetBlockHash()); - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); } } diff --git a/src/llmq/chainlocks.cpp b/src/llmq/chainlocks.cpp index 14a6acffd4..0855d70820 100644 --- a/src/llmq/chainlocks.cpp +++ b/src/llmq/chainlocks.cpp @@ -225,7 +225,7 @@ void CChainLocksHandler::CheckActiveState() bool fDIP0008Active; { LOCK(cs_main); - fDIP0008Active = chainActive.Tip() && chainActive.Tip()->pprev && chainActive.Tip()->pprev->nHeight >= Params().GetConsensus().DIP0008Height; + fDIP0008Active = ::ChainActive().Tip() && ::ChainActive().Tip()->pprev && ::ChainActive().Tip()->pprev->nHeight >= Params().GetConsensus().DIP0008Height; } bool oldIsEnforced = isEnforced; @@ -262,7 +262,7 @@ void CChainLocksHandler::TrySignChainTip() const CBlockIndex* pindex; { LOCK(cs_main); - pindex = chainActive.Tip(); + pindex = ::ChainActive().Tip(); } if (!pindex->pprev) { @@ -519,7 +519,7 @@ void CChainLocksHandler::EnforceBestChainLock() // Go backwards through the chain referenced by clsig until we find a block that is part of the main chain. // For each of these blocks, check if there are children that are NOT part of the chain referenced by clsig // and mark all of them as conflicting. - while (pindex && !chainActive.Contains(pindex)) { + while (pindex && !::ChainActive().Contains(pindex)) { // Mark all blocks that have the same prevBlockHash but are not equal to blockHash as conflicting auto itp = mapPrevBlockIndex.equal_range(pindex->pprev->GetBlockHash()); for (auto jt = itp.first; jt != itp.second; ++jt) { @@ -545,7 +545,7 @@ void CChainLocksHandler::EnforceBestChainLock() ResetBlockFailureFlags(LookupBlockIndex(currentBestChainLockBlockIndex->GetBlockHash())); } - activateNeeded = chainActive.Tip()->GetAncestor(currentBestChainLockBlockIndex->nHeight) != currentBestChainLockBlockIndex; + activateNeeded = ::ChainActive().Tip()->GetAncestor(currentBestChainLockBlockIndex->nHeight) != currentBestChainLockBlockIndex; } if (activateNeeded) { @@ -554,7 +554,7 @@ void CChainLocksHandler::EnforceBestChainLock() return; } LOCK(cs_main); - if (chainActive.Tip()->GetAncestor(currentBestChainLockBlockIndex->nHeight) != currentBestChainLockBlockIndex) { + if (::ChainActive().Tip()->GetAncestor(currentBestChainLockBlockIndex->nHeight) != currentBestChainLockBlockIndex) { return; } } @@ -702,7 +702,7 @@ void CChainLocksHandler::Cleanup() it = txFirstSeenTime.erase(it); } else if (!hashBlock.IsNull()) { auto pindex = LookupBlockIndex(hashBlock); - if (chainActive.Tip()->GetAncestor(pindex->nHeight) == pindex && chainActive.Height() - pindex->nHeight >= 6) { + if (::ChainActive().Tip()->GetAncestor(pindex->nHeight) == pindex && ::ChainActive().Height() - pindex->nHeight >= 6) { // tx got confirmed >= 6 times, so we can stop keeping track of it it = txFirstSeenTime.erase(it); } else { diff --git a/src/llmq/instantsend.cpp b/src/llmq/instantsend.cpp index fe3dff1daf..8e9788bdcd 100644 --- a/src/llmq/instantsend.cpp +++ b/src/llmq/instantsend.cpp @@ -621,7 +621,7 @@ bool CInstantSendManager::CheckCanLock(const COutPoint& outpoint, bool printDebu { LOCK(cs_main); pindexMined = LookupBlockIndex(hashBlock); - nTxAge = chainActive.Height() - pindexMined->nHeight + 1; + nTxAge = ::ChainActive().Height() - pindexMined->nHeight + 1; } if (nTxAge < nInstantSendConfirmationsRequired && !llmq::chainLocksHandler->HasChainLock(pindexMined->nHeight, pindexMined->GetBlockHash())) { @@ -714,8 +714,8 @@ void CInstantSendManager::TrySignInstantSendLock(const CTransaction& tx) { LOCK(cs_main); const auto dkgInterval = GetLLMQParams(llmqType).dkgInterval; - const auto quorumHeight = chainActive.Height() - (chainActive.Height() % dkgInterval); - islock.cycleHash = chainActive[quorumHeight]->GetBlockHash(); + const auto quorumHeight = ::ChainActive().Height() - (::ChainActive().Height() % dkgInterval); + islock.cycleHash = ::ChainActive()[quorumHeight]->GetBlockHash(); } auto id = islock.GetRequestId(); @@ -942,7 +942,7 @@ std::unordered_set CInstantSendManager::ProcessPend } const auto dkgInterval = GetLLMQParams(Params().GetConsensus().llmqTypeInstantSend).dkgInterval; - if (blockIndex->nHeight + dkgInterval < chainActive.Height()) { + if (blockIndex->nHeight + dkgInterval < ::ChainActive().Height()) { nSignHeight = blockIndex->nHeight + dkgInterval - 1; } } @@ -1459,7 +1459,7 @@ void CInstantSendManager::RemoveConflictingLock(const uint256& islockHash, const LogPrintf("CInstantSendManager::%s -- txid=%s, islock=%s: Removing ISLOCK and its chained children\n", __func__, islock.txid.ToString(), islockHash.ToString()); - int tipHeight = WITH_LOCK(cs_main, return chainActive.Height()); + int tipHeight = WITH_LOCK(cs_main, return ::ChainActive().Height()); auto removedIslocks = db.RemoveChainedInstantSendLocks(islockHash, islock.txid, tipHeight); for (const auto& h : removedIslocks) { diff --git a/src/llmq/quorums.cpp b/src/llmq/quorums.cpp index c2d8541886..aabd275b1a 100644 --- a/src/llmq/quorums.cpp +++ b/src/llmq/quorums.cpp @@ -422,7 +422,7 @@ bool CQuorumManager::RequestQuorumData(CNode* pFrom, Consensus::LLMQType llmqTyp std::vector CQuorumManager::ScanQuorums(Consensus::LLMQType llmqType, size_t nCountRequested) const { - const CBlockIndex* pindex = WITH_LOCK(cs_main, return chainActive.Tip()); + const CBlockIndex* pindex = WITH_LOCK(cs_main, return ::ChainActive().Tip()); return ScanQuorums(llmqType, pindex, nCountRequested); } diff --git a/src/llmq/signing.cpp b/src/llmq/signing.cpp index 8ac37e2518..5c0f80f75d 100644 --- a/src/llmq/signing.cpp +++ b/src/llmq/signing.cpp @@ -1007,13 +1007,13 @@ CQuorumCPtr CSigningManager::SelectQuorumForSigning(Consensus::LLMQType llmqType { LOCK(cs_main); if (signHeight == -1) { - signHeight = chainActive.Height(); + signHeight = ::ChainActive().Height(); } int startBlockHeight = signHeight - signOffset; - if (startBlockHeight > chainActive.Height() || startBlockHeight < 0) { + if (startBlockHeight > ::ChainActive().Height() || startBlockHeight < 0) { return {}; } - pindexStart = chainActive[startBlockHeight]; + pindexStart = ::ChainActive()[startBlockHeight]; } auto quorums = quorumManager->ScanQuorums(llmqType, pindexStart, poolSize); diff --git a/src/masternode/payments.cpp b/src/masternode/payments.cpp index fbf60d40d0..bf58772f3a 100644 --- a/src/masternode/payments.cpp +++ b/src/masternode/payments.cpp @@ -270,7 +270,7 @@ bool CMasternodePayments::GetBlockTxOuts(int nBlockHeight, CAmount blockReward, { LOCK(cs_main); - pindex = chainActive[nBlockHeight - 1]; + pindex = ::ChainActive()[nBlockHeight - 1]; const Consensus::Params& consensusParams = Params().GetConsensus(); if (VersionBitsState(pindex, consensusParams, Consensus::DEPLOYMENT_REALLOC, versionbitscache) == ThresholdState::ACTIVE) { diff --git a/src/miner.cpp b/src/miner.cpp index 14fb090623..7a2a3a9417 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -127,7 +127,7 @@ std::unique_ptr BlockAssembler::CreateNewBlock(const CScript& sc LOCK2(cs_main, mempool.cs); - CBlockIndex* pindexPrev = chainActive.Tip(); + CBlockIndex* pindexPrev = ::ChainActive().Tip(); assert(pindexPrev != nullptr); nHeight = pindexPrev->nHeight + 1; diff --git a/src/net_processing.cpp b/src/net_processing.cpp index bb5f3e31d6..4bb6e0f9bd 100644 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -640,7 +640,7 @@ static bool TipMayBeStale(const Consensus::Params &consensusParams) EXCLUSIVE_LO static bool CanDirectFetch(const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { - return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20; + return ::ChainActive().Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20; } static bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main) @@ -666,7 +666,7 @@ static void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vec // Make sure pindexBestKnownBlock is up to date, we'll need it. ProcessBlockAvailability(nodeid); - if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) { + if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < ::ChainActive().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) { // This peer has nothing interesting. return; } @@ -674,7 +674,7 @@ static void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vec if (state->pindexLastCommonBlock == nullptr) { // Bootstrap quickly by guessing a parent of our best tip is the forking point. // Guessing wrong in either direction is not a problem. - state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; + state->pindexLastCommonBlock = ::ChainActive()[std::min(state->pindexBestKnownBlock->nHeight, ::ChainActive().Height())]; } // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor @@ -712,7 +712,7 @@ static void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vec // We consider the chain that this peer is on invalid. return; } - if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) { + if (pindex->nStatus & BLOCK_HAVE_DATA || ::ChainActive().Contains(pindex)) { if (pindex->HaveTxsDownloaded()) state->pindexLastCommonBlock = pindex; } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { @@ -1155,7 +1155,7 @@ bool IsBanned(NodeId pnode) static bool BlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); - if (chainActive.Contains(pindex)) return true; + if (::ChainActive().Contains(pindex)) return true; return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) && (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT); @@ -1278,7 +1278,7 @@ void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std: /** * Update our best height and announce any block hashes which weren't previously - * in chainActive to our peers. + * in ::ChainActive() to our peers. */ void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) { const int nNewHeight = pindexNew->nHeight; @@ -1367,13 +1367,13 @@ bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) case MSG_LEGACY_TXLOCK_REQUEST: // we treat legacy IX messages as TX messages { assert(recentRejects); - if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) + if (::ChainActive().Tip()->GetBlockHash() != hashRecentRejectsChainTip) { // If the chain tip has changed previously rejected transactions // might be now valid, e.g. due to a nLockTime'd tx becoming valid, // or a double-spend. Reset the rejects filter and give those // txs a second chance. - hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash(); + hashRecentRejectsChainTip = ::ChainActive().Tip()->GetBlockHash(); recentRejects->reset(); } @@ -1541,7 +1541,7 @@ void static ProcessGetBlockData(CNode* pfrom, const CChainParams& chainparams, c } // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold if (send && !pfrom->HasPermission(PF_NOBAN) && ( - (((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) ) + (((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (::ChainActive().Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) ) )) { LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n", pfrom->GetId()); @@ -1603,7 +1603,7 @@ void static ProcessGetBlockData(CNode* pfrom, const CChainParams& chainparams, c // and we don't feel like constructing the object for them, so // instead we respond with the full, non-compact block. if (CanDirectFetch(consensusParams) && - pindex->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) { + pindex->nHeight >= ::ChainActive().Height() - MAX_CMPCTBLOCK_DEPTH) { if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::CMPCTBLOCK, *a_recent_compact_block)); @@ -1623,7 +1623,7 @@ void static ProcessGetBlockData(CNode* pfrom, const CChainParams& chainparams, c // and we want it right after the last block so they don't // wait for other stuff first. std::vector vInv; - vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash())); + vInv.push_back(CInv(MSG_BLOCK, ::ChainActive().Tip()->GetBlockHash())); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv)); pfrom->hashContinue.SetNull(); } @@ -1863,7 +1863,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve // nUnconnectingHeaders gets reset back to 0. if (!LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) { nodestate->nUnconnectingHeaders++; - connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256())); + connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), uint256())); LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n", headers[0].GetHash().ToString(), headers[0].hashPrevBlock.ToString(), @@ -1960,26 +1960,26 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve // because it is set in UpdateBlockAvailability. Some nullptr checks // are still present, however, as belt-and-suspenders. - if (received_new_header && pindexLast->nChainWork > chainActive.Tip()->nChainWork) { + if (received_new_header && pindexLast->nChainWork > ::ChainActive().Tip()->nChainWork) { nodestate->m_last_block_announcement = GetTime(); } if (nCount == MAX_HEADERS_RESULTS) { // Headers message had its maximum size; the peer may have more headers. - // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue + // TODO: optimize: if pindexLast is an ancestor of ::ChainActive().Tip or pindexBestHeader, continue // from there instead. LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight); - connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256())); + connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexLast), uint256())); } bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus()); // If this set of headers is valid and ends in a block with at least as // much work as our tip, download as much as possible. - if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) { + if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && ::ChainActive().Tip()->nChainWork <= pindexLast->nChainWork) { std::vector vToFetch; const CBlockIndex *pindexWalk = pindexLast; // Calculate all the blocks we'd need to switch to pindexLast, up to a limit. - while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { + while (pindexWalk && !::ChainActive().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) && !mapBlocksInFlight.count(pindexWalk->GetBlockHash())) { // We don't have this block, and it's not yet in flight. @@ -1991,7 +1991,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve // very large reorg at a time we think we're close to caught up to // the main chain -- this shouldn't really happen. Bail out on the // direct fetch and rely on parallel download instead. - if (!chainActive.Contains(pindexWalk)) { + if (!::ChainActive().Contains(pindexWalk)) { LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n", pindexLast->GetBlockHash().ToString(), pindexLast->nHeight); @@ -2031,7 +2031,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve // us sync -- disconnect if using an outbound slot (unless // whitelisted or addnode). // Note: We compare their tip to nMinimumChainWork (rather than - // chainActive.Tip()) because we won't start block download + // ::ChainActive().Tip()) because we won't start block download // until we have a headers chain that has at least // nMinimumChainWork, even if a peer has a chain past our tip, // as an anti-DoS measure. @@ -2045,7 +2045,7 @@ bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::ve if (!pfrom->fDisconnect && IsOutboundDisconnectionCandidate(pfrom) && nodestate->pindexBestKnownBlock != nullptr) { // If this is an outbound peer, check to see if we should protect // it from the bad/lagging chain logic. - if (g_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) { + if (g_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= ::ChainActive().Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) { LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom->GetId()); nodestate->m_chain_sync.m_protect = true; ++g_outbound_peers_with_protect_from_disconnect; @@ -2846,7 +2846,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr // fell back to inv we probably have a reorg which we should get the headers for first, // we now only provide a getheaders response here. When we receive the headers, we will // then ask for the blocks we need. - connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash)); + connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), inv.hash)); LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId()); } } @@ -2925,14 +2925,14 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr LOCK(cs_main); // Find the last block the caller has in the main chain - const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator); + const CBlockIndex* pindex = FindForkInGlobalIndex(::ChainActive(), locator); // Send the rest of the chain if (pindex) - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); int nLimit = 500; LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->GetId()); - for (; pindex; pindex = chainActive.Next(pindex)) + for (; pindex; pindex = ::ChainActive().Next(pindex)) { if (pindex->GetBlockHash() == hashStop) { @@ -2942,7 +2942,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr // If pruning, don't inv blocks unless we have on disk and are likely to still have // for some reasonable time window (1 hour) that block relay might require. const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing; - if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave)) + if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= ::ChainActive().Tip()->nHeight - nPrunedBlocksLikelyToHave)) { LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); break; @@ -2986,7 +2986,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr return true; } - if (pindex->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) { + if (pindex->nHeight < ::ChainActive().Height() - MAX_BLOCKTXN_DEPTH) { // If an older block is requested (should never happen in practice, // but can happen in tests) send a block response instead of a // blocktxn response. Sending a full block response instead of a @@ -3046,23 +3046,23 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr else { // Find the last block the caller has in the main chain - pindex = FindForkInGlobalIndex(chainActive, locator); + pindex = FindForkInGlobalIndex(::ChainActive(), locator); if (pindex) - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); } // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end std::vector vHeaders; int nLimit = MAX_HEADERS_RESULTS; LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId()); - for (; pindex; pindex = chainActive.Next(pindex)) + for (; pindex; pindex = ::ChainActive().Next(pindex)) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } - // pindex can be nullptr either if we sent chainActive.Tip() OR - // if our peer has chainActive.Tip() (and thus we are sending an empty + // pindex can be nullptr either if we sent ::ChainActive().Tip() OR + // if our peer has ::ChainActive().Tip() (and thus we are sending an empty // headers message). In both cases it's safe to update // pindexBestHeaderSent to be our tip. // @@ -3073,7 +3073,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr // without the new block. By resetting the BestHeaderSent, we ensure we // will re-announce the new block via headers (or compact blocks again) // in the SendMessages logic. - nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip(); + nodestate->pindexBestHeaderSent = pindex ? pindex : ::ChainActive().Tip(); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders)); return true; } @@ -3128,7 +3128,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr CDeterministicMNCPtr dmn{nullptr}; { LOCK(cs_main); - pindex = chainActive.Tip(); + pindex = ::ChainActive().Tip(); } // It could be that a MN is no longer in the list but its DSTX is not yet mined. // Try to find a MN up to 24 blocks deep to make sure such dstx-es are relayed and processed correctly. @@ -3313,7 +3313,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) { // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers if (!IsInitialBlockDownload()) - connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256())); + connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), uint256())); return true; } @@ -3363,7 +3363,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr // If this was a new header with more work than our tip, update the // peer's last block announcement time - if (received_new_header && pindex->nChainWork > chainActive.Tip()->nChainWork) { + if (received_new_header && pindex->nChainWork > ::ChainActive().Tip()->nChainWork) { nodestate->m_last_block_announcement = GetTime(); } @@ -3373,7 +3373,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here return true; - if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better + if (pindex->nChainWork <= ::ChainActive().Tip()->nChainWork || // We know something better pindex->nTx != 0) { // We had this block at some point, but pruned it if (fAlreadyInFlight) { // We requested this block for some reason, but our mempool will probably be useless @@ -3391,7 +3391,7 @@ bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStr // We want to be a bit conservative just to be extra careful about DoS // possibilities in compact block processing... - if (pindex->nHeight <= chainActive.Height() + 2) { + if (pindex->nHeight <= ::ChainActive().Height() + 2) { if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) || (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) { std::list::iterator *queuedBlockIt = nullptr; @@ -4125,7 +4125,7 @@ void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds) // their chain has more work than ours, we should sync to it, // unless it's invalid, in which case we should find that out and // disconnect from them elsewhere). - if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork) { + if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= ::ChainActive().Tip()->nChainWork) { if (state.m_chain_sync.m_timeout != 0) { state.m_chain_sync.m_timeout = 0; state.m_chain_sync.m_work_header = nullptr; @@ -4137,7 +4137,7 @@ void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds) // where we checked against our tip. // Either way, set a new timeout based on current tip. state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT; - state.m_chain_sync.m_work_header = chainActive.Tip(); + state.m_chain_sync.m_work_header = ::ChainActive().Tip(); state.m_chain_sync.m_sent_getheaders = false; } else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) { // No evidence yet that our peer has synced to a chain with work equal to that @@ -4150,7 +4150,7 @@ void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds) } else { assert(state.m_chain_sync.m_work_header); LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "", state.m_chain_sync.m_work_header->GetBlockHash().ToString()); - connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(state.m_chain_sync.m_work_header->pprev), uint256())); + connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(state.m_chain_sync.m_work_header->pprev), uint256())); state.m_chain_sync.m_sent_getheaders = true; constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes // Bump the timeout to allow a response, which could clear the timeout @@ -4357,7 +4357,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto) // Start block sync if (pindexBestHeader == nullptr) - pindexBestHeader = chainActive.Tip(); + pindexBestHeader = ::ChainActive().Tip(); bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do. if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex && pto->CanRelay()) { // Only actively request headers from a single peer, unless we're close to end of initial download. @@ -4376,7 +4376,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto) if (pindexStart->pprev) pindexStart = pindexStart->pprev; LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight); - connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256())); + connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexStart), uint256())); } } @@ -4418,11 +4418,11 @@ bool PeerLogicValidation::SendMessages(CNode* pto) bool fFoundStartingHeader = false; // Try to find first header that our peer doesn't have, and // then send all headers past that one. If we come across any - // headers that aren't on chainActive, give up. + // headers that aren't on ::ChainActive(), give up. for (const uint256 &hash : pto->vBlockHashesToAnnounce) { const CBlockIndex* pindex = LookupBlockIndex(hash); assert(pindex); - if (chainActive[pindex->nHeight] != pindex) { + if (::ChainActive()[pindex->nHeight] != pindex) { // Bail out if we reorged away from this block fRevertToInv = true; break; @@ -4520,9 +4520,9 @@ bool PeerLogicValidation::SendMessages(CNode* pto) // Warn if we're announcing a block that is not on the main chain. // This should be very rare and could be optimized out. // Just log for now. - if (chainActive[pindex->nHeight] != pindex) { + if (::ChainActive()[pindex->nHeight] != pindex) { LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n", - hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString()); + hashToAnnounce.ToString(), ::ChainActive().Tip()->GetBlockHash().ToString()); } // If the peer's chain has this block, don't inv it back. diff --git a/src/policy/fees.cpp b/src/policy/fees.cpp index b5dcc28432..2014f282bc 100644 --- a/src/policy/fees.cpp +++ b/src/policy/fees.cpp @@ -559,7 +559,7 @@ void CBlockPolicyEstimator::processTransaction(const CTxMemPoolEntry& entry, boo if (txHeight != nBestSeenHeight) { // Ignore side chains and re-orgs; assuming they are random they don't // affect the estimate. We'll potentially double count transactions in 1-block reorgs. - // Ignore txs if BlockPolicyEstimator is not in sync with chainActive.Tip(). + // Ignore txs if BlockPolicyEstimator is not in sync with ::ChainActive().Tip(). // It will be synced next time a block is processed. return; } diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp index 0eea7f8aa3..ce1105050b 100644 --- a/src/qt/test/wallettests.cpp +++ b/src/qt/test/wallettests.cpp @@ -124,9 +124,9 @@ void TestGUI() const CBlockIndex* const null_block = nullptr; const CBlockIndex *stop_block, *failed_block; QCOMPARE( - wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver, failed_block, stop_block, true /* fUpdate */), + wallet->ScanForWalletTransactions(::ChainActive().Genesis(), nullptr, reserver, failed_block, stop_block, true /* fUpdate */), CWallet::ScanResult::SUCCESS); - QCOMPARE(stop_block, chainActive.Tip()); + QCOMPARE(stop_block, ::ChainActive().Tip()); QCOMPARE(failed_block, null_block); } wallet->SetBroadcastTransactions(true); diff --git a/src/rest.cpp b/src/rest.cpp index 579c9f31ac..3c2f51c709 100644 --- a/src/rest.cpp +++ b/src/rest.cpp @@ -136,13 +136,13 @@ static bool rest_headers(HTTPRequest* req, headers.reserve(count); { LOCK(cs_main); - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); const CBlockIndex* pindex = LookupBlockIndex(hash); - while (pindex != nullptr && chainActive.Contains(pindex)) { + while (pindex != nullptr && ::ChainActive().Contains(pindex)) { headers.push_back(pindex); if (headers.size() == (unsigned long)count) break; - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); } } @@ -204,7 +204,7 @@ static bool rest_block(HTTPRequest* req, CBlockIndex* tip = nullptr; { LOCK(cs_main); - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); pblockindex = LookupBlockIndex(hash); if (!pblockindex) { return RESTERR(req, HTTP_NOT_FOUND, hashStr + " not found"); @@ -517,7 +517,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) // serialize data // use exact same output as mentioned in Bip64 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION); - ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs; + ssGetUTXOResponse << ::ChainActive().Height() << ::ChainActive().Tip()->GetBlockHash() << bitmap << outs; std::string ssGetUTXOResponseString = ssGetUTXOResponse.str(); req->WriteHeader("Content-Type", "application/octet-stream"); @@ -527,7 +527,7 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) case RetFormat::HEX: { CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION); - ssGetUTXOResponse << chainActive.Height() << chainActive.Tip()->GetBlockHash() << bitmap << outs; + ssGetUTXOResponse << ::ChainActive().Height() << ::ChainActive().Tip()->GetBlockHash() << bitmap << outs; std::string strHex = HexStr(ssGetUTXOResponse) + "\n"; req->WriteHeader("Content-Type", "text/plain"); @@ -540,8 +540,8 @@ static bool rest_getutxos(HTTPRequest* req, const std::string& strURIPart) // pack in some essentials // use more or less the same output as mentioned in Bip64 - objGetUTXOResponse.pushKV("chainHeight", chainActive.Height()); - objGetUTXOResponse.pushKV("chaintipHash", chainActive.Tip()->GetBlockHash().GetHex()); + objGetUTXOResponse.pushKV("chainHeight", ::ChainActive().Height()); + objGetUTXOResponse.pushKV("chaintipHash", ::ChainActive().Tip()->GetBlockHash().GetHex()); objGetUTXOResponse.pushKV("bitmap", bitmapStringRepresentation); UniValue utxos(UniValue::VARR); @@ -585,10 +585,10 @@ static bool rest_blockhash_by_height(HTTPRequest* req, CBlockIndex* pblockindex = nullptr; { LOCK(cs_main); - if (blockheight > chainActive.Height()) { + if (blockheight > ::ChainActive().Height()) { return RESTERR(req, HTTP_NOT_FOUND, "Block height out of range"); } - pblockindex = chainActive[blockheight]; + pblockindex = ::ChainActive()[blockheight]; } switch (rf) { case RetFormat::BINARY: { diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 3b2e77b7ff..a362b62b79 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -201,7 +201,7 @@ static UniValue getblockcount(const JSONRPCRequest& request) ); LOCK(cs_main); - return chainActive.Height(); + return ::ChainActive().Height(); } static UniValue getbestblockhash(const JSONRPCRequest& request) @@ -219,7 +219,7 @@ static UniValue getbestblockhash(const JSONRPCRequest& request) ); LOCK(cs_main); - return chainActive.Tip()->GetBlockHash().GetHex(); + return ::ChainActive().Tip()->GetBlockHash().GetHex(); } static UniValue getbestchainlock(const JSONRPCRequest& request) @@ -434,7 +434,7 @@ static UniValue getdifficulty(const JSONRPCRequest& request) ); LOCK(cs_main); - return GetDifficulty(chainActive.Tip()); + return GetDifficulty(::ChainActive().Tip()); } static std::string EntryDescriptionString() @@ -817,10 +817,10 @@ static UniValue getblockhash(const JSONRPCRequest& request) LOCK(cs_main); int nHeight = request.params[0].get_int(); - if (nHeight < 0 || nHeight > chainActive.Height()) + if (nHeight < 0 || nHeight > ::ChainActive().Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); - CBlockIndex* pblockindex = chainActive[nHeight]; + CBlockIndex* pblockindex = ::ChainActive()[nHeight]; return pblockindex->GetBlockHash().GetHex(); } @@ -876,7 +876,7 @@ static UniValue getblockheader(const JSONRPCRequest& request) { LOCK(cs_main); pblockindex = LookupBlockIndex(hash); - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); } if (!pblockindex) { @@ -967,7 +967,7 @@ static UniValue getblockheaders(const JSONRPCRequest& request) if (!fVerbose) { - for (; pblockindex; pblockindex = chainActive.Next(pblockindex)) + for (; pblockindex; pblockindex = ::ChainActive().Next(pblockindex)) { CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION); ssBlock << pblockindex->GetBlockHeader(); @@ -979,9 +979,9 @@ static UniValue getblockheaders(const JSONRPCRequest& request) return arrHeaders; } - for (; pblockindex; pblockindex = chainActive.Next(pblockindex)) + for (; pblockindex; pblockindex = ::ChainActive().Next(pblockindex)) { - arrHeaders.push_back(blockheaderToJSON(chainActive.Tip(), pblockindex)); + arrHeaders.push_back(blockheaderToJSON(::ChainActive().Tip(), pblockindex)); if (--nCount <= 0) break; } @@ -1066,7 +1066,7 @@ static UniValue getmerkleblocks(const JSONRPCRequest& request) UniValue arrMerkleBlocks(UniValue::VARR); - for (; pblockindex; pblockindex = chainActive.Next(pblockindex)) + for (; pblockindex; pblockindex = ::ChainActive().Next(pblockindex)) { if (--nCount < 0) { break; @@ -1179,7 +1179,7 @@ static UniValue getblock(const JSONRPCRequest& request) return strHex; } - return blockToJSON(block, chainActive.Tip(), pblockindex, verbosity >= 2); + return blockToJSON(block, ::ChainActive().Tip(), pblockindex, verbosity >= 2); } static UniValue pruneblockchain(const JSONRPCRequest& request) @@ -1213,7 +1213,7 @@ static UniValue pruneblockchain(const JSONRPCRequest& request) // too low to be a block time (corresponds to timestamp from Sep 2001). if (heightParam > 1000000000) { // Add a 2 hour buffer to include blocks which might have had old timestamps - CBlockIndex* pindex = chainActive.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW); + CBlockIndex* pindex = ::ChainActive().FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW); if (!pindex) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp."); } @@ -1221,7 +1221,7 @@ static UniValue pruneblockchain(const JSONRPCRequest& request) } unsigned int height = (unsigned int) heightParam; - unsigned int chainHeight = (unsigned int) chainActive.Height(); + unsigned int chainHeight = (unsigned int) ::ChainActive().Height(); if (chainHeight < Params().PruneAfterHeight()) throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning."); else if (height > chainHeight) @@ -1528,10 +1528,10 @@ UniValue getblockchaininfo(const JSONRPCRequest& request) std::string strChainName = gArgs.IsArgSet("-devnet") ? gArgs.GetDevNetName() : Params().NetworkIDString(); - const CBlockIndex* tip = chainActive.Tip(); + const CBlockIndex* tip = ::ChainActive().Tip(); UniValue obj(UniValue::VOBJ); obj.pushKV("chain", strChainName); - obj.pushKV("blocks", (int)chainActive.Height()); + obj.pushKV("blocks", (int)::ChainActive().Height()); obj.pushKV("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1); obj.pushKV("bestblockhash", tip->GetBlockHash().GetHex()); obj.pushKV("difficulty", (double)GetDifficulty(tip)); @@ -1640,11 +1640,11 @@ static UniValue getchaintips(const JSONRPCRequest& request) LOCK(cs_main); /* - * Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them. + * Idea: the set of chain tips is ::ChainActive().tip, plus orphan blocks which do not have another orphan building off of them. * Algorithm: * - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers. * - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip. - * - add chainActive.Tip() + * - add ::ChainActive().Tip() */ std::set setTips; std::set setOrphans; @@ -1652,7 +1652,7 @@ static UniValue getchaintips(const JSONRPCRequest& request) for (const std::pair& item : mapBlockIndex) { - if (!chainActive.Contains(item.second)) { + if (!::ChainActive().Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); } @@ -1666,7 +1666,7 @@ static UniValue getchaintips(const JSONRPCRequest& request) } // Always report the currently active tip. - setTips.insert(chainActive.Tip()); + setTips.insert(::ChainActive().Tip()); int nBranchMin = -1; int nCountMax = INT_MAX; @@ -1681,7 +1681,7 @@ static UniValue getchaintips(const JSONRPCRequest& request) UniValue res(UniValue::VARR); for (const CBlockIndex* block : setTips) { - const CBlockIndex* pindexFork = chainActive.FindFork(block); + const CBlockIndex* pindexFork = ::ChainActive().FindFork(block); const int branchLen = block->nHeight - pindexFork->nHeight; if(branchLen < nBranchMin) continue; @@ -1696,7 +1696,7 @@ static UniValue getchaintips(const JSONRPCRequest& request) obj.pushKV("forkpoint", pindexFork->phashBlock->GetHex()); std::string status; - if (chainActive.Contains(block)) { + if (::ChainActive().Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { @@ -1928,7 +1928,7 @@ static UniValue getchaintxstats(const JSONRPCRequest& request) if (request.params[1].isNull()) { LOCK(cs_main); - pindex = chainActive.Tip(); + pindex = ::ChainActive().Tip(); } else { uint256 hash = uint256S(request.params[1].get_str()); LOCK(cs_main); @@ -1936,7 +1936,7 @@ static UniValue getchaintxstats(const JSONRPCRequest& request) if (!pindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } - if (!chainActive.Contains(pindex)) { + if (!::ChainActive().Contains(pindex)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain"); } } @@ -2105,7 +2105,7 @@ static UniValue getblockstats(const JSONRPCRequest& request) CBlockIndex* pindex; if (request.params[0].isNum()) { const int height = request.params[0].get_int(); - const int current_tip = chainActive.Height(); + const int current_tip = ::ChainActive().Height(); if (height < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height)); } @@ -2113,7 +2113,7 @@ static UniValue getblockstats(const JSONRPCRequest& request) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip)); } - pindex = chainActive[height]; + pindex = ::ChainActive()[height]; } else { const uint256 hash = ParseHashV(request.params[0], "parameter 1"); if (mapBlockIndex.count(hash) == 0) @@ -2123,7 +2123,7 @@ static UniValue getblockstats(const JSONRPCRequest& request) // if (!pindex) { // throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); // } - if (!chainActive.Contains(pindex)) { + if (!::ChainActive().Contains(pindex)) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Block is not in chain %s", Params().NetworkIDString())); } } diff --git a/src/rpc/governance.cpp b/src/rpc/governance.cpp index 6f6747616e..784fd5c110 100644 --- a/src/rpc/governance.cpp +++ b/src/rpc/governance.cpp @@ -1202,7 +1202,7 @@ static UniValue getgovernanceinfo(const JSONRPCRequest& request) } int nLastSuperblock = 0, nNextSuperblock = 0; - int nBlockHeight = WITH_LOCK(cs_main, return chainActive.Height()); + int nBlockHeight = WITH_LOCK(cs_main, return ::ChainActive().Height()); CSuperblock::GetNearestSuperblocksHeights(nBlockHeight, nLastSuperblock, nNextSuperblock); diff --git a/src/rpc/masternode.cpp b/src/rpc/masternode.cpp index 39e75def46..039c709ac8 100644 --- a/src/rpc/masternode.cpp +++ b/src/rpc/masternode.cpp @@ -325,7 +325,7 @@ static UniValue masternode_winners(const JSONRPCRequest& request) const CBlockIndex* pindexTip{nullptr}; { LOCK(cs_main); - pindexTip = chainActive.Tip(); + pindexTip = ::ChainActive().Tip(); if (!pindexTip) return NullUniValue; } @@ -414,7 +414,7 @@ static UniValue masternode_payments(const JSONRPCRequest& request) if (request.params[1].isNull()) { LOCK(cs_main); - pindex = chainActive.Tip(); + pindex = ::ChainActive().Tip(); } else { LOCK(cs_main); uint256 blockHash = ParseHashV(request.params[1], "blockhash"); @@ -492,7 +492,7 @@ static UniValue masternode_payments(const JSONRPCRequest& request) if (nCount > 0) { LOCK(cs_main); - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); } else { pindex = pindex->pprev; } @@ -609,7 +609,7 @@ static UniValue masternodelist(const JSONRPCRequest& request) } LOCK(cs_main); - const CBlockIndex* pindex = chainActive[dmn->pdmnState->nLastPaidHeight]; + const CBlockIndex* pindex = ::ChainActive()[dmn->pdmnState->nLastPaidHeight]; return (int)pindex->nTime; }; diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 2957983bd1..752bb25e54 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -46,10 +46,10 @@ * If 'height' is nonnegative, compute the estimate at the time when a given block was found. */ static UniValue GetNetworkHashPS(int lookup, int height) { - CBlockIndex *pb = chainActive.Tip(); + CBlockIndex *pb = ::ChainActive().Tip(); - if (height >= 0 && height < chainActive.Height()) - pb = chainActive[height]; + if (height >= 0 && height < ::ChainActive().Height()) + pb = ::ChainActive()[height]; if (pb == nullptr || !pb->nHeight) return 0; @@ -117,7 +117,7 @@ UniValue generateBlocks(std::shared_ptr coinbaseScript, int nGen { // Don't keep cs_main locked LOCK(cs_main); - nHeight = chainActive.Height(); + nHeight = ::ChainActive().Height(); nHeightEnd = nHeight+nGenerate; } unsigned int nExtraNonce = 0; @@ -130,7 +130,7 @@ UniValue generateBlocks(std::shared_ptr coinbaseScript, int nGen CBlock *pblock = &pblocktemplate->block; { LOCK(cs_main); - IncrementExtraNonce(pblock, chainActive.Tip(), nExtraNonce); + IncrementExtraNonce(pblock, ::ChainActive().Tip(), nExtraNonce); } while (nMaxTries > 0 && pblock->nNonce < std::numeric_limits::max() && !CheckProofOfWork(pblock->GetHash(), pblock->nBits, Params().GetConsensus()) && !ShutdownRequested()) { ++pblock->nNonce; @@ -231,10 +231,10 @@ static UniValue getmininginfo(const JSONRPCRequest& request) LOCK(cs_main); UniValue obj(UniValue::VOBJ); - obj.pushKV("blocks", (int)chainActive.Height()); + obj.pushKV("blocks", (int)::ChainActive().Height()); obj.pushKV("currentblocksize", (uint64_t)nLastBlockSize); obj.pushKV("currentblocktx", (uint64_t)nLastBlockTx); - obj.pushKV("difficulty", (double)GetDifficulty(chainActive.Tip())); + obj.pushKV("difficulty", (double)GetDifficulty(::ChainActive().Tip())); obj.pushKV("networkhashps", getnetworkhashps(request)); obj.pushKV("pooledtx", (uint64_t)mempool.size()); obj.pushKV("chain", Params().NetworkIDString()); @@ -457,7 +457,7 @@ static UniValue getblocktemplate(const JSONRPCRequest& request) return "duplicate-inconclusive"; } - CBlockIndex* const pindexPrev = chainActive.Tip(); + CBlockIndex* const pindexPrev = ::ChainActive().Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; @@ -496,7 +496,7 @@ static UniValue getblocktemplate(const JSONRPCRequest& request) // next bock is a superblock and we need governance info to correctly construct it if (AreSuperblocksEnabled() && !masternodeSync.IsSynced() - && CSuperblock::IsValidBlockHeight(chainActive.Height() + 1)) + && CSuperblock::IsValidBlockHeight(::ChainActive().Height() + 1)) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME "is syncing with network..."); static unsigned int nTransactionsUpdatedLast; @@ -519,7 +519,7 @@ static UniValue getblocktemplate(const JSONRPCRequest& request) else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier - hashWatchedChain = chainActive.Tip()->GetBlockHash(); + hashWatchedChain = ::ChainActive().Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } @@ -551,15 +551,15 @@ static UniValue getblocktemplate(const JSONRPCRequest& request) static CBlockIndex* pindexPrev; static int64_t nStart; static std::unique_ptr pblocktemplate; - if (pindexPrev != chainActive.Tip() || + if (pindexPrev != ::ChainActive().Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = nullptr; - // Store the chainActive.Tip() used before CreateNewBlock, to avoid races + // Store the ::ChainActive().Tip() used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); - CBlockIndex* pindexPrevNew = chainActive.Tip(); + CBlockIndex* pindexPrevNew = ::ChainActive().Tip(); nStart = GetTime(); // Create new block @@ -684,7 +684,7 @@ static UniValue getblocktemplate(const JSONRPCRequest& request) result.pushKV("transactions", transactions); result.pushKV("coinbaseaux", aux); result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->GetValueOut()); - result.pushKV("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)); + result.pushKV("longpollid", ::ChainActive().Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)); result.pushKV("target", hashTarget.GetHex()); result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1); result.pushKV("mutable", aMutable); diff --git a/src/rpc/misc.cpp b/src/rpc/misc.cpp index 61a5a608f2..cc3adf6e35 100644 --- a/src/rpc/misc.cpp +++ b/src/rpc/misc.cpp @@ -852,7 +852,7 @@ static UniValue getaddressbalance(const JSONRPCRequest& request) } } - int nHeight = WITH_LOCK(cs_main, return chainActive.Height()); + int nHeight = WITH_LOCK(cs_main, return ::ChainActive().Height()); CAmount balance = 0; CAmount balance_spendable = 0; diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index a55e0d72c2..a81bc4b849 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -84,9 +84,9 @@ void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) entry.pushKV("blockhash", hashBlock.GetHex()); CBlockIndex* pindex = LookupBlockIndex(hashBlock); if (pindex) { - if (chainActive.Contains(pindex)) { + if (::ChainActive().Contains(pindex)) { entry.pushKV("height", pindex->nHeight); - entry.pushKV("confirmations", 1 + chainActive.Height() - pindex->nHeight); + entry.pushKV("confirmations", 1 + ::ChainActive().Height() - pindex->nHeight); entry.pushKV("time", pindex->GetBlockTime()); entry.pushKV("blocktime", pindex->GetBlockTime()); @@ -212,7 +212,7 @@ static UniValue getrawtransaction(const JSONRPCRequest& request) if (!blockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found"); } - in_active_chain = chainActive.Contains(blockindex); + in_active_chain = ::ChainActive().Contains(blockindex); } bool f_txindex_ready = false; @@ -314,7 +314,7 @@ static UniValue gettxoutproof(const JSONRPCRequest& request) for (const auto& tx : setTxids) { const Coin& coin = AccessByTxid(*pcoinsTip, tx); if (!coin.IsSpent()) { - pblockindex = chainActive[coin.nHeight]; + pblockindex = ::ChainActive()[coin.nHeight]; break; } } @@ -392,7 +392,7 @@ static UniValue verifytxoutproof(const JSONRPCRequest& request) LOCK(cs_main); const CBlockIndex* pindex = LookupBlockIndex(merkleBlock.header.GetHash()); - if (!pindex || !chainActive.Contains(pindex) || pindex->nTx == 0) { + if (!pindex || !::ChainActive().Contains(pindex) || pindex->nTx == 0) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); } diff --git a/src/rpc/rpcevo.cpp b/src/rpc/rpcevo.cpp index 476342a24b..9d5f8efc64 100644 --- a/src/rpc/rpcevo.cpp +++ b/src/rpc/rpcevo.cpp @@ -277,7 +277,7 @@ static std::string SignAndSendSpecialTx(const CMutableTransaction& tx, bool fSub LOCK(cs_main); CValidationState state; - if (!CheckSpecialTx(CTransaction(tx), chainActive.Tip(), state, *pcoinsTip.get())) { + if (!CheckSpecialTx(CTransaction(tx), ::ChainActive().Tip(), state, *pcoinsTip.get())) { throw std::runtime_error(FormatStateMessage(state)); } } // cs_main @@ -1065,8 +1065,8 @@ static UniValue protx_list(const JSONRPCRequest& request) bool detailed = !request.params[2].isNull() ? ParseBoolV(request.params[2], "detailed") : false; - int height = !request.params[3].isNull() ? ParseInt32V(request.params[3], "height") : chainActive.Height(); - if (height < 1 || height > chainActive.Height()) { + int height = !request.params[3].isNull() ? ParseInt32V(request.params[3], "height") : ::ChainActive().Height(); + if (height < 1 || height > ::ChainActive().Height()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid height specified"); } @@ -1077,7 +1077,7 @@ static UniValue protx_list(const JSONRPCRequest& request) setOutpts.emplace(outpt); } - CDeterministicMNList mnList = deterministicMNManager->GetListForBlock(chainActive[height]); + CDeterministicMNList mnList = deterministicMNManager->GetListForBlock(::ChainActive()[height]); mnList.ForEachMN(false, [&](const CDeterministicMNCPtr& dmn) { if (setOutpts.count(dmn->collateralOutpoint) || CheckWalletOwnsKey(pwallet, dmn->pdmnState->keyIDOwner) || @@ -1097,12 +1097,12 @@ static UniValue protx_list(const JSONRPCRequest& request) bool detailed = !request.params[2].isNull() ? ParseBoolV(request.params[2], "detailed") : false; - int height = !request.params[3].isNull() ? ParseInt32V(request.params[3], "height") : chainActive.Height(); - if (height < 1 || height > chainActive.Height()) { + int height = !request.params[3].isNull() ? ParseInt32V(request.params[3], "height") : ::ChainActive().Height(); + if (height < 1 || height > ::ChainActive().Height()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "invalid height specified"); } - CDeterministicMNList mnList = deterministicMNManager->GetListForBlock(chainActive[height]); + CDeterministicMNList mnList = deterministicMNManager->GetListForBlock(::ChainActive()[height]); bool onlyValid = type == "valid"; mnList.ForEachMN(onlyValid, [&](const CDeterministicMNCPtr& dmn) { ret.push_back(BuildDMNListEntry(pwallet, dmn, detailed)); @@ -1183,9 +1183,9 @@ static uint256 ParseBlock(const UniValue& v, std::string strName) EXCLUSIVE_LOCK return ParseHashV(v, strName); } catch (...) { int h = ParseInt32V(v, strName); - if (h < 1 || h > chainActive.Height()) + if (h < 1 || h > ::ChainActive().Height()) throw std::runtime_error(strprintf("%s must be a block hash or chain height and not %s", strName, v.getValStr())); - return *chainActive[h]->phashBlock; + return *::ChainActive()[h]->phashBlock; } } diff --git a/src/rpc/rpcquorums.cpp b/src/rpc/rpcquorums.cpp index e350f11cab..1dca88d7ad 100644 --- a/src/rpc/rpcquorums.cpp +++ b/src/rpc/rpcquorums.cpp @@ -64,7 +64,7 @@ static UniValue quorum_list(const JSONRPCRequest& request) UniValue ret(UniValue::VOBJ); - CBlockIndex* pindexTip = WITH_LOCK(cs_main, return chainActive.Tip()); + CBlockIndex* pindexTip = WITH_LOCK(cs_main, return ::ChainActive().Tip()); for (auto& type : llmq::CLLMQUtils::GetEnabledQuorumTypes(pindexTip)) { const auto& llmq_params = llmq::GetLLMQParams(type); @@ -195,7 +195,7 @@ static UniValue quorum_dkgstatus(const JSONRPCRequest& request) auto ret = status.ToJson(detailLevel); - CBlockIndex* pindexTip = WITH_LOCK(cs_main, return chainActive.Tip()); + CBlockIndex* pindexTip = WITH_LOCK(cs_main, return ::ChainActive().Tip()); int tipHeight = pindexTip->nHeight; auto proTxHash = WITH_LOCK(activeMasternodeInfoCs, return activeMasternodeInfo.proTxHash); @@ -205,7 +205,7 @@ static UniValue quorum_dkgstatus(const JSONRPCRequest& request) const auto& llmq_params = llmq::GetLLMQParams(type); if (fMasternodeMode) { - const CBlockIndex* pindexQuorum = WITH_LOCK(cs_main, return chainActive[tipHeight - (tipHeight % llmq_params.dkgInterval)]); + const CBlockIndex* pindexQuorum = WITH_LOCK(cs_main, return ::ChainActive()[tipHeight - (tipHeight % llmq_params.dkgInterval)]); auto allConnections = llmq::CLLMQUtils::GetQuorumConnections(llmq_params.type, pindexQuorum, proTxHash, false); auto outboundConnections = llmq::CLLMQUtils::GetQuorumConnections(llmq_params.type, pindexQuorum, proTxHash, true); std::map foundConnections; @@ -279,7 +279,7 @@ static UniValue quorum_memberof(const JSONRPCRequest& request) } } - const CBlockIndex* pindexTip = WITH_LOCK(cs_main, return chainActive.Tip()); + const CBlockIndex* pindexTip = WITH_LOCK(cs_main, return ::ChainActive().Tip()); auto mnList = deterministicMNManager->GetListForBlock(pindexTip); auto dmn = mnList.GetMN(protxHash); diff --git a/src/spork.cpp b/src/spork.cpp index 9cd1a93a5e..850fdecc14 100644 --- a/src/spork.cpp +++ b/src/spork.cpp @@ -111,8 +111,8 @@ void CSporkManager::ProcessSpork(CNode* pfrom, const std::string& strCommand, CD { LOCK(cs_main); EraseObjectRequest(pfrom->GetId(), CInv(MSG_SPORK, hash)); - if(!chainActive.Tip()) return; - strLogMsg = strprintf("SPORK -- hash: %s id: %d value: %10d bestHeight: %d peer=%d", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Height(), pfrom->GetId()); + if(!::ChainActive().Tip()) return; + strLogMsg = strprintf("SPORK -- hash: %s id: %d value: %10d bestHeight: %d peer=%d", hash.ToString(), spork.nSporkID, spork.nValue, ::ChainActive().Height(), pfrom->GetId()); } if (spork.nTimeSigned > GetAdjustedTime() + 2 * 60 * 60) { diff --git a/src/test/blockfilter_index_tests.cpp b/src/test/blockfilter_index_tests.cpp index 89dd39aa83..989b0c95b4 100644 --- a/src/test/blockfilter_index_tests.cpp +++ b/src/test/blockfilter_index_tests.cpp @@ -125,9 +125,9 @@ BOOST_FIXTURE_TEST_CASE(blockfilter_index_initial_sync, TestChain100Setup) std::vector filters; std::vector filter_hashes; - for (const CBlockIndex* block_index = chainActive.Genesis(); + for (const CBlockIndex* block_index = ::ChainActive().Genesis(); block_index != nullptr; - block_index = chainActive.Next(block_index)) { + block_index = ::ChainActive().Next(block_index)) { BOOST_CHECK(!filter_index.LookupFilter(block_index, filter)); BOOST_CHECK(!filter_index.LookupFilterHeader(block_index, filter_header)); BOOST_CHECK(!filter_index.LookupFilterRange(block_index->nHeight, block_index, filters)); @@ -153,9 +153,9 @@ BOOST_FIXTURE_TEST_CASE(blockfilter_index_initial_sync, TestChain100Setup) { LOCK(cs_main); const CBlockIndex* block_index; - for (block_index = chainActive.Genesis(); + for (block_index = ::ChainActive().Genesis(); block_index != nullptr; - block_index = chainActive.Next(block_index)) { + block_index = ::ChainActive().Next(block_index)) { CheckFilterLookups(filter_index, block_index, last_header); } } @@ -164,7 +164,7 @@ BOOST_FIXTURE_TEST_CASE(blockfilter_index_initial_sync, TestChain100Setup) const CBlockIndex* tip; { LOCK(cs_main); - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); } CScript coinbase_script_pub_key = GetScriptForDestination(coinbaseKey.GetPubKey().GetID()); std::vector> chainA, chainB; @@ -250,7 +250,7 @@ BOOST_FIXTURE_TEST_CASE(blockfilter_index_initial_sync, TestChain100Setup) { LOCK(cs_main); - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); } BOOST_CHECK(filter_index.LookupFilterRange(0, tip, filters)); BOOST_CHECK(filter_index.LookupFilterHashRange(0, tip, filter_hashes)); diff --git a/src/test/denialofservice_tests.cpp b/src/test/denialofservice_tests.cpp index 9c1f50eb0b..9677c502b3 100644 --- a/src/test/denialofservice_tests.cpp +++ b/src/test/denialofservice_tests.cpp @@ -91,8 +91,8 @@ BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction) // This test requires that we have a chain with non-zero work. { LOCK(cs_main); - BOOST_CHECK(chainActive.Tip() != nullptr); - BOOST_CHECK(chainActive.Tip()->nChainWork > 0); + BOOST_CHECK(::ChainActive().Tip() != nullptr); + BOOST_CHECK(::ChainActive().Tip()->nChainWork > 0); } // Test starts here diff --git a/src/test/evo_deterministicmns_tests.cpp b/src/test/evo_deterministicmns_tests.cpp index 9ff24570f6..b331f47c0e 100644 --- a/src/test/evo_deterministicmns_tests.cpp +++ b/src/test/evo_deterministicmns_tests.cpp @@ -46,7 +46,7 @@ static std::vector SelectUTXOs(SimpleUTXOMap& utoxs, CAmount amount, while (!utoxs.empty()) { bool found = false; for (auto it = utoxs.begin(); it != utoxs.end(); ++it) { - if (chainActive.Height() - it->second.first < 101) { + if (::ChainActive().Height() - it->second.first < 101) { continue; } @@ -240,24 +240,24 @@ BOOST_FIXTURE_TEST_CASE(dip3_activation, TestChainDIP3BeforeActivationSetup) auto tx = CreateProRegTx(utxos, 1, GetScriptForDestination(payoutDest), coinbaseKey, ownerKey, operatorKey); std::vector txns = {tx}; - int nHeight = chainActive.Height(); + int nHeight = ::ChainActive().Height(); // We start one block before DIP3 activation, so mining a block with a DIP3 transaction should fail auto block = std::make_shared(CreateBlock(txns, coinbaseKey)); ProcessNewBlock(Params(), block, true, nullptr); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight); - BOOST_ASSERT(block->GetHash() != chainActive.Tip()->GetBlockHash()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight); + BOOST_ASSERT(block->GetHash() != ::ChainActive().Tip()->GetBlockHash()); BOOST_ASSERT(!deterministicMNManager->GetListAtChainTip().HasMN(tx.GetHash())); // This block should activate DIP3 CreateAndProcessBlock({}, coinbaseKey); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); // Mining a block with a DIP3 transaction should succeed now block = std::make_shared(CreateBlock(txns, coinbaseKey)); BOOST_ASSERT(ProcessNewBlock(Params(), block, true, nullptr)); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 2); - BOOST_CHECK_EQUAL(block->GetHash(), chainActive.Tip()->GetBlockHash()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 2); + BOOST_CHECK_EQUAL(block->GetHash(), ::ChainActive().Tip()->GetBlockHash()); BOOST_ASSERT(deterministicMNManager->GetListAtChainTip().HasMN(tx.GetHash())); } @@ -270,7 +270,7 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) auto utxos = BuildSimpleUtxoMap(m_coinbase_txns); - int nHeight = chainActive.Height(); + int nHeight = ::ChainActive().Height(); int port = 1; std::vector dmnHashes; @@ -293,25 +293,25 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) auto tx2 = MalleateProTxPayout(tx); CValidationState dummyState; // Technically, the payload is still valid... - BOOST_ASSERT(CheckProRegTx(CTransaction(tx), chainActive.Tip(), dummyState, *pcoinsTip.get())); - BOOST_ASSERT(CheckProRegTx(CTransaction(tx2), chainActive.Tip(), dummyState, *pcoinsTip.get())); + BOOST_ASSERT(CheckProRegTx(CTransaction(tx), ::ChainActive().Tip(), dummyState, *pcoinsTip.get())); + BOOST_ASSERT(CheckProRegTx(CTransaction(tx2), ::ChainActive().Tip(), dummyState, *pcoinsTip.get())); // But the signature should not verify anymore BOOST_ASSERT(CheckTransactionSignature(tx)); BOOST_ASSERT(!CheckTransactionSignature(tx2)); CreateAndProcessBlock({tx}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); BOOST_ASSERT(deterministicMNManager->GetListAtChainTip().HasMN(tx.GetHash())); nHeight++; } int DIP0003EnforcementHeightBackup = Params().GetConsensus().DIP0003EnforcementHeight; - const_cast(Params().GetConsensus()).DIP0003EnforcementHeight = chainActive.Height() + 1; + const_cast(Params().GetConsensus()).DIP0003EnforcementHeight = ::ChainActive().Height() + 1; CreateAndProcessBlock({}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); nHeight++; // check MN reward payments @@ -319,7 +319,7 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) auto dmnExpectedPayee = deterministicMNManager->GetListAtChainTip().GetMNPayee(); CBlock block = CreateAndProcessBlock({}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); BOOST_ASSERT(!block.vtx.empty()); auto dmnPayout = FindPayoutDmn(block); @@ -342,8 +342,8 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) txns.emplace_back(tx); } CreateAndProcessBlock(txns, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); for (size_t j = 0; j < 3; j++) { BOOST_ASSERT(deterministicMNManager->GetListAtChainTip().HasMN(txns[j].GetHash())); @@ -355,8 +355,8 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) // test ProUpServTx auto tx = CreateProUpServTx(utxos, dmnHashes[0], operatorKeys[dmnHashes[0]], 1000, CScript(), coinbaseKey); CreateAndProcessBlock({tx}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); nHeight++; auto dmn = deterministicMNManager->GetListAtChainTip().GetMN(dmnHashes[0]); @@ -365,8 +365,8 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) // test ProUpRevTx tx = CreateProUpRevTx(utxos, dmnHashes[0], operatorKeys[dmnHashes[0]], coinbaseKey); CreateAndProcessBlock({tx}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); nHeight++; dmn = deterministicMNManager->GetListAtChainTip().GetMN(dmnHashes[0]); @@ -378,7 +378,7 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) BOOST_ASSERT(dmnExpectedPayee->proTxHash != dmnHashes[0]); CBlock block = CreateAndProcessBlock({}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); BOOST_ASSERT(!block.vtx.empty()); auto dmnPayout = FindPayoutDmn(block); @@ -396,20 +396,20 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) // check malleability protection again, but this time by also relying on the signature inside the ProUpRegTx auto tx2 = MalleateProTxPayout(tx); CValidationState dummyState; - BOOST_ASSERT(CheckProUpRegTx(CTransaction(tx), chainActive.Tip(), dummyState, *pcoinsTip.get())); - BOOST_ASSERT(!CheckProUpRegTx(CTransaction(tx2), chainActive.Tip(), dummyState, *pcoinsTip.get())); + BOOST_ASSERT(CheckProUpRegTx(CTransaction(tx), ::ChainActive().Tip(), dummyState, *pcoinsTip.get())); + BOOST_ASSERT(!CheckProUpRegTx(CTransaction(tx2), ::ChainActive().Tip(), dummyState, *pcoinsTip.get())); BOOST_ASSERT(CheckTransactionSignature(tx)); BOOST_ASSERT(!CheckTransactionSignature(tx2)); // now process the block CreateAndProcessBlock({tx}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); nHeight++; tx = CreateProUpServTx(utxos, dmnHashes[0], newOperatorKey, 100, CScript(), coinbaseKey); CreateAndProcessBlock({tx}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); nHeight++; dmn = deterministicMNManager->GetListAtChainTip().GetMN(dmnHashes[0]); @@ -425,7 +425,7 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) } CBlock block = CreateAndProcessBlock({}, coinbaseKey); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); BOOST_ASSERT(!block.vtx.empty()); auto dmnPayout = FindPayoutDmn(block); @@ -441,7 +441,7 @@ BOOST_FIXTURE_TEST_CASE(dip3_protx, TestChainDIP3Setup) BOOST_FIXTURE_TEST_CASE(dip3_test_mempool_reorg, TestChainDIP3Setup) { - int nHeight = chainActive.Height(); + int nHeight = ::ChainActive().Height(); auto utxos = BuildSimpleUtxoMap(m_coinbase_txns); CKey ownerKey; @@ -464,9 +464,9 @@ BOOST_FIXTURE_TEST_CASE(dip3_test_mempool_reorg, TestChainDIP3Setup) auto block = std::make_shared(CreateBlock({tx_collateral}, coinbaseKey)); BOOST_ASSERT(ProcessNewBlock(Params(), block, true, nullptr)); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); - BOOST_CHECK_EQUAL(block->GetHash(), chainActive.Tip()->GetBlockHash()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); + BOOST_CHECK_EQUAL(block->GetHash(), ::ChainActive().Tip()->GetBlockHash()); CProRegTx payload; payload.addr = LookupNumeric("1.1.1.1", 1); @@ -572,7 +572,7 @@ BOOST_FIXTURE_TEST_CASE(dip3_test_mempool_dual_proregtx, TestChainDIP3Setup) BOOST_FIXTURE_TEST_CASE(dip3_verify_db, TestChainDIP3Setup) { - int nHeight = chainActive.Height(); + int nHeight = ::ChainActive().Height(); auto utxos = BuildSimpleUtxoMap(m_coinbase_txns); CKey ownerKey; @@ -595,9 +595,9 @@ BOOST_FIXTURE_TEST_CASE(dip3_verify_db, TestChainDIP3Setup) auto block = std::make_shared(CreateBlock({tx_collateral}, coinbaseKey)); BOOST_ASSERT(ProcessNewBlock(Params(), block, true, nullptr)); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 1); - BOOST_CHECK_EQUAL(block->GetHash(), chainActive.Tip()->GetBlockHash()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 1); + BOOST_CHECK_EQUAL(block->GetHash(), ::ChainActive().Tip()->GetBlockHash()); CProRegTx payload; payload.addr = LookupNumeric("1.1.1.1", 1); @@ -626,9 +626,9 @@ BOOST_FIXTURE_TEST_CASE(dip3_verify_db, TestChainDIP3Setup) block = std::make_shared(CreateBlock({tx_reg}, coinbaseKey)); BOOST_ASSERT(ProcessNewBlock(Params(), block, true, nullptr)); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 2); - BOOST_CHECK_EQUAL(block->GetHash(), chainActive.Tip()->GetBlockHash()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 2); + BOOST_CHECK_EQUAL(block->GetHash(), ::ChainActive().Tip()->GetBlockHash()); BOOST_ASSERT(deterministicMNManager->GetListAtChainTip().HasMN(tx_reg_hash)); // Now spend the collateral while updating the same MN @@ -638,9 +638,9 @@ BOOST_FIXTURE_TEST_CASE(dip3_verify_db, TestChainDIP3Setup) block = std::make_shared(CreateBlock({proUpRevTx}, coinbaseKey)); BOOST_ASSERT(ProcessNewBlock(Params(), block, true, nullptr)); - deterministicMNManager->UpdatedBlockTip(chainActive.Tip()); - BOOST_CHECK_EQUAL(chainActive.Height(), nHeight + 3); - BOOST_CHECK_EQUAL(block->GetHash(), chainActive.Tip()->GetBlockHash()); + deterministicMNManager->UpdatedBlockTip(::ChainActive().Tip()); + BOOST_CHECK_EQUAL(::ChainActive().Height(), nHeight + 3); + BOOST_CHECK_EQUAL(block->GetHash(), ::ChainActive().Tip()->GetBlockHash()); BOOST_ASSERT(!deterministicMNManager->GetListAtChainTip().HasMN(tx_reg_hash)); // Verify db consistency diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp index df8969e9b3..b1d578caf8 100644 --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -79,7 +79,7 @@ static CBlockIndex CreateBlockIndex(int nHeight) { CBlockIndex index; index.nHeight = nHeight; - index.pprev = chainActive.Tip(); + index.pprev = ::ChainActive().Tip(); return index; } @@ -222,21 +222,21 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) std::vector txFirst; auto createAndProcessEmptyBlock = [&]() { - int i = chainActive.Height(); + int i = ::ChainActive().Height(); CBlock *pblock = &pemptyblocktemplate->block; // pointer for convenience { LOCK(cs_main); pblock->nVersion = 2; - pblock->nTime = chainActive.Tip()->GetMedianTimePast()+1; + pblock->nTime = ::ChainActive().Tip()->GetMedianTimePast()+1; CMutableTransaction txCoinbase(*pblock->vtx[0]); txCoinbase.nVersion = 1; - txCoinbase.vin[0].scriptSig = CScript() << (chainActive.Height() + 1); + txCoinbase.vin[0].scriptSig = CScript() << (::ChainActive().Height() + 1); txCoinbase.vin[0].scriptSig.push_back(blockinfo[i].extranonce); - txCoinbase.vin[0].scriptSig.push_back(chainActive.Height()); + txCoinbase.vin[0].scriptSig.push_back(::ChainActive().Height()); txCoinbase.vout[0].scriptPubKey = CScript(); pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase)); if (txFirst.size() == 0) - baseheight = chainActive.Height(); + baseheight = ::ChainActive().Height(); if (txFirst.size() < 4) txFirst.push_back(pblock->vtx[0]); pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); @@ -392,42 +392,42 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) mempool.clear(); // subsidy changing - // int nHeight = chainActive.Height(); + // int nHeight = ::ChainActive().Height(); // // Create an actual 209999-long block chain (without valid blocks). - // while (chainActive.Tip()->nHeight < 209999) { - // CBlockIndex* prev = chainActive.Tip(); + // while (::ChainActive().Tip()->nHeight < 209999) { + // CBlockIndex* prev = ::ChainActive().Tip(); // CBlockIndex* next = new CBlockIndex(); // next->phashBlock = new uint256(InsecureRand256()); // pcoinsTip->SetBestBlock(next->GetBlockHash()); // next->pprev = prev; // next->nHeight = prev->nHeight + 1; // next->BuildSkip(); - // chainActive.SetTip(next); + // ::ChainActive().SetTip(next); // } //BOOST_CHECK(pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey)); // // Extend to a 210000-long block chain. - // while (chainActive.Tip()->nHeight < 210000) { - // CBlockIndex* prev = chainActive.Tip(); + // while (::ChainActive().Tip()->nHeight < 210000) { + // CBlockIndex* prev = ::ChainActive().Tip(); // CBlockIndex* next = new CBlockIndex(); // next->phashBlock = new uint256(InsecureRand256()); // pcoinsTip->SetBestBlock(next->GetBlockHash()); // next->pprev = prev; // next->nHeight = prev->nHeight + 1; // next->BuildSkip(); - // chainActive.SetTip(next); + // ::ChainActive().SetTip(next); // } //BOOST_CHECK(pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey)); // // Delete the dummy blocks again. - // while (chainActive.Tip()->nHeight > nHeight) { - // CBlockIndex* del = chainActive.Tip(); - // chainActive.SetTip(del->pprev); + // while (::ChainActive().Tip()->nHeight > nHeight) { + // CBlockIndex* del = ::ChainActive().Tip(); + // ::ChainActive().SetTip(del->pprev); // pcoinsTip->SetBestBlock(del->pprev->GetBlockHash()); // delete del->phashBlock; // delete del; // } // non-final txs in mempool - SetMockTime(chainActive.Tip()->GetMedianTimePast()+1); + SetMockTime(::ChainActive().Tip()->GetMedianTimePast()+1); int flags = LOCKTIME_VERIFY_SEQUENCE|LOCKTIME_MEDIAN_TIME_PAST; // height map std::vector prevheights; @@ -439,7 +439,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) tx.vin[0].prevout.hash = txFirst[0]->GetHash(); // only 1 transaction tx.vin[0].prevout.n = 0; tx.vin[0].scriptSig = CScript() << OP_1; - tx.vin[0].nSequence = chainActive.Tip()->nHeight + 1; // txFirst[0] is the 2nd block + tx.vin[0].nSequence = ::ChainActive().Tip()->nHeight + 1; // txFirst[0] is the 2nd block prevheights[0] = baseheight + 1; tx.vout.resize(1); tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE; @@ -449,11 +449,11 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) mempool.addUnchecked(entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); BOOST_CHECK(CheckFinalTx(CTransaction(tx), flags)); // Locktime passes BOOST_CHECK(!TestSequenceLocks(CTransaction(tx), flags)); // Sequence locks fail - BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 2))); // Sequence locks pass on 2nd block + BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, &prevheights, CreateBlockIndex(::ChainActive().Tip()->nHeight + 2))); // Sequence locks pass on 2nd block // relative time locked tx.vin[0].prevout.hash = txFirst[1]->GetHash(); - tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | (((chainActive.Tip()->GetMedianTimePast()+1-chainActive[1]->GetMedianTimePast()) >> CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) + 1); // txFirst[1] is the 3rd block + tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | (((::ChainActive().Tip()->GetMedianTimePast()+1-::ChainActive()[1]->GetMedianTimePast()) >> CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) + 1); // txFirst[1] is the 3rd block prevheights[0] = baseheight + 2; hash = tx.GetHash(); mempool.addUnchecked(entry.Time(GetTime()).FromTx(tx)); @@ -461,36 +461,36 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) BOOST_CHECK(!TestSequenceLocks(CTransaction(tx), flags)); // Sequence locks fail for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) - chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast - BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 1))); // Sequence locks pass 512 seconds later + ::ChainActive().Tip()->GetAncestor(::ChainActive().Tip()->nHeight - i)->nTime += 512; // Trick the MedianTimePast + BOOST_CHECK(SequenceLocks(CTransaction(tx), flags, &prevheights, CreateBlockIndex(::ChainActive().Tip()->nHeight + 1))); // Sequence locks pass 512 seconds later for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) - chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime -= 512; //undo tricked MTP + ::ChainActive().Tip()->GetAncestor(::ChainActive().Tip()->nHeight - i)->nTime -= 512; //undo tricked MTP // absolute height locked tx.vin[0].prevout.hash = txFirst[2]->GetHash(); tx.vin[0].nSequence = CTxIn::SEQUENCE_FINAL - 1; prevheights[0] = baseheight + 3; - tx.nLockTime = chainActive.Tip()->nHeight + 1; + tx.nLockTime = ::ChainActive().Tip()->nHeight + 1; hash = tx.GetHash(); mempool.addUnchecked(entry.Time(GetTime()).FromTx(tx)); BOOST_CHECK(!CheckFinalTx(CTransaction(tx), flags)); // Locktime fails BOOST_CHECK(TestSequenceLocks(CTransaction(tx), flags)); // Sequence locks pass - BOOST_CHECK(IsFinalTx(CTransaction(tx), chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast())); // Locktime passes on 2nd block + BOOST_CHECK(IsFinalTx(CTransaction(tx), ::ChainActive().Tip()->nHeight + 2, ::ChainActive().Tip()->GetMedianTimePast())); // Locktime passes on 2nd block // absolute time locked tx.vin[0].prevout.hash = txFirst[3]->GetHash(); - tx.nLockTime = chainActive.Tip()->GetMedianTimePast(); + tx.nLockTime = ::ChainActive().Tip()->GetMedianTimePast(); prevheights.resize(1); prevheights[0] = baseheight + 4; hash = tx.GetHash(); mempool.addUnchecked(entry.Time(GetTime()).FromTx(tx)); BOOST_CHECK(!CheckFinalTx(CTransaction(tx), flags)); // Locktime fails BOOST_CHECK(TestSequenceLocks(CTransaction(tx), flags)); // Sequence locks pass - BOOST_CHECK(IsFinalTx(CTransaction(tx), chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast() + 1)); // Locktime passes 1 second later + BOOST_CHECK(IsFinalTx(CTransaction(tx), ::ChainActive().Tip()->nHeight + 2, ::ChainActive().Tip()->GetMedianTimePast() + 1)); // Locktime passes 1 second later // mempool-dependent transactions (not added) tx.vin[0].prevout.hash = hash; - prevheights[0] = chainActive.Tip()->nHeight + 1; + prevheights[0] = ::ChainActive().Tip()->nHeight + 1; tx.nLockTime = 0; tx.vin[0].nSequence = 0; BOOST_CHECK(CheckFinalTx(CTransaction(tx), flags)); // Locktime passes @@ -511,7 +511,7 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3U); // However if we advance height by 1 and time by 512, all of them should be mined for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) - chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast + ::ChainActive().Tip()->GetAncestor(::ChainActive().Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast } // unlock cs_main while calling createAndProcessEmptyBlock @@ -520,13 +520,13 @@ BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) LOCK(cs_main); - SetMockTime(chainActive.Tip()->GetMedianTimePast() + 1); + SetMockTime(::ChainActive().Tip()->GetMedianTimePast() + 1); BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 5U); CValidationState state; - InvalidateBlock(state, chainparams, chainActive.Tip()); + InvalidateBlock(state, chainparams, ::ChainActive().Tip()); SetMockTime(0); mempool.clear(); diff --git a/src/test/test_dash.cpp b/src/test/test_dash.cpp index 5987c588ca..83564d4928 100644 --- a/src/test/test_dash.cpp +++ b/src/test/test_dash.cpp @@ -211,10 +211,10 @@ CBlock TestChainSetup::CreateBlock(const std::vector& txns, BOOST_ASSERT(false); } CValidationState state; - if (!CalcCbTxMerkleRootMNList(block, chainActive.Tip(), cbTx.merkleRootMNList, state, *pcoinsTip.get())) { + if (!CalcCbTxMerkleRootMNList(block, ::ChainActive().Tip(), cbTx.merkleRootMNList, state, *pcoinsTip.get())) { BOOST_ASSERT(false); } - if (!CalcCbTxMerkleRootQuorums(block, chainActive.Tip(), cbTx.merkleRootQuorums, state)) { + if (!CalcCbTxMerkleRootQuorums(block, ::ChainActive().Tip(), cbTx.merkleRootQuorums, state)) { BOOST_ASSERT(false); } CMutableTransaction tmpTx{*block.vtx[0]}; @@ -226,7 +226,7 @@ CBlock TestChainSetup::CreateBlock(const std::vector& txns, { LOCK(cs_main); unsigned int extraNonce = 0; - IncrementExtraNonce(&block, chainActive.Tip(), extraNonce); + IncrementExtraNonce(&block, ::ChainActive().Tip(), extraNonce); } while (!CheckProofOfWork(block.GetHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce; diff --git a/src/test/txvalidationcache_tests.cpp b/src/test/txvalidationcache_tests.cpp index ada3f06969..244b1ea0b5 100644 --- a/src/test/txvalidationcache_tests.cpp +++ b/src/test/txvalidationcache_tests.cpp @@ -68,7 +68,7 @@ BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup) block = CreateAndProcessBlock(spends, scriptPubKey); { LOCK(cs_main); - BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash()); + BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash()); } // Test 2: ... and should be rejected if spend1 is in the memory pool @@ -76,7 +76,7 @@ BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup) block = CreateAndProcessBlock(spends, scriptPubKey); { LOCK(cs_main); - BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash()); + BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash()); } mempool.clear(); @@ -85,7 +85,7 @@ BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup) block = CreateAndProcessBlock(spends, scriptPubKey); { LOCK(cs_main); - BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash()); + BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash()); } mempool.clear(); @@ -96,7 +96,7 @@ BOOST_FIXTURE_TEST_CASE(tx_mempool_block_doublespend, TestChain100Setup) block = CreateAndProcessBlock(oneSpend, scriptPubKey); { LOCK(cs_main); - BOOST_CHECK(chainActive.Tip()->GetBlockHash() == block.GetHash()); + BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() == block.GetHash()); } // spends[1] should have been removed from the mempool when the // block with spends[0] is accepted: @@ -227,7 +227,7 @@ BOOST_FIXTURE_TEST_CASE(checkinputs_test, TestChain100Setup) block = CreateAndProcessBlock({spend_tx}, p2pk_scriptPubKey); LOCK(cs_main); - BOOST_CHECK(chainActive.Tip()->GetBlockHash() == block.GetHash()); + BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() == block.GetHash()); BOOST_CHECK(pcoinsTip->GetBestBlock() == block.GetHash()); // Test P2SH: construct a transaction that is valid without P2SH, and diff --git a/src/test/validation_block_tests.cpp b/src/test/validation_block_tests.cpp index 8108ba9c33..df367743d4 100644 --- a/src/test/validation_block_tests.cpp +++ b/src/test/validation_block_tests.cpp @@ -140,7 +140,7 @@ BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering) const CBlockIndex* initial_tip = nullptr; { LOCK(cs_main); - initial_tip = chainActive.Tip(); + initial_tip = ::ChainActive().Tip(); } TestSubscriber sub(initial_tip->GetBlockHash()); RegisterValidationInterface(&sub); @@ -177,7 +177,7 @@ BOOST_AUTO_TEST_CASE(processnewblock_signals_ordering) UnregisterValidationInterface(&sub); - BOOST_CHECK_EQUAL(sub.m_expected_tip, chainActive.Tip()->GetBlockHash()); + BOOST_CHECK_EQUAL(sub.m_expected_tip, ::ChainActive().Tip()->GetBlockHash()); } BOOST_AUTO_TEST_SUITE_END() diff --git a/src/txmempool.h b/src/txmempool.h index 4505aacadd..1211e2f3cd 100644 --- a/src/txmempool.h +++ b/src/txmempool.h @@ -502,7 +502,7 @@ public: * By design, it is guaranteed that: * * 1. Locking both `cs_main` and `mempool.cs` will give a view of mempool - * that is consistent with current chain tip (`chainActive` and + * that is consistent with current chain tip (`::ChainActive()` and * `pcoinsTip`) and is fully populated. Fully populated means that if the * current active chain is missing transactions that were present in a * previously active chain, all the missing transactions will have been diff --git a/src/validation.cpp b/src/validation.cpp index 6d281e53b5..9497fd3b68 100644 --- a/src/validation.cpp +++ b/src/validation.cpp @@ -179,7 +179,9 @@ private: CCriticalSection m_cs_chainstate; public: - CChain chainActive; + //! The current chain of blockheaders we consult and build on. + //! @see CChain, CBlockIndex. + CChain m_chain; BlockMap mapBlockIndex; PrevBlockMap mapPrevBlockIndex; std::multimap mapBlocksUnlinked; @@ -240,6 +242,8 @@ private: bool RollforwardBlock(const CBlockIndex* pindex, CCoinsViewCache& inputs, const CChainParams& params) EXCLUSIVE_LOCKS_REQUIRED(cs_main); } g_chainstate; +CChain& ChainActive() { return g_chainstate.m_chain; } + /** * Mutex to guard access to validation specific variables, such as reading * or changing the chainstate. @@ -254,7 +258,6 @@ RecursiveMutex cs_main; BlockMap& mapBlockIndex = g_chainstate.mapBlockIndex; PrevBlockMap& mapPrevBlockIndex = g_chainstate.mapPrevBlockIndex; -CChain& chainActive = g_chainstate.chainActive; CBlockIndex *pindexBestHeader = nullptr; Mutex g_best_block_mutex; std::condition_variable g_best_block_cv; @@ -363,13 +366,13 @@ bool CheckFinalTx(const CTransaction &tx, int flags) // scheduled, so no flags are set. flags = std::max(flags, 0); - // CheckFinalTx() uses chainActive.Height()+1 to evaluate + // CheckFinalTx() uses ::ChainActive().Height()+1 to evaluate // nLockTime because when IsFinalTx() is called within // CBlock::AcceptBlock(), the height of the block *being* // evaluated is what is used. Thus if we want to know if a // transaction can be part of the *next* block, we need to call - // IsFinalTx() with one more than chainActive.Height(). - const int nBlockHeight = chainActive.Height() + 1; + // IsFinalTx() with one more than ::ChainActive().Height(). + const int nBlockHeight = ::ChainActive().Height() + 1; // BIP113 requires that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. @@ -377,7 +380,7 @@ bool CheckFinalTx(const CTransaction &tx, int flags) // chain tip, so we use that to calculate the median time passed to // IsFinalTx() if LOCKTIME_MEDIAN_TIME_PAST is set. const int64_t nBlockTime = (flags & LOCKTIME_MEDIAN_TIME_PAST) - ? chainActive.Tip()->GetMedianTimePast() + ? ::ChainActive().Tip()->GetMedianTimePast() : GetAdjustedTime(); return IsFinalTx(tx, nBlockHeight, nBlockTime); @@ -390,9 +393,9 @@ bool TestLockPointValidity(const LockPoints* lp) // If there are relative lock times then the maxInputBlock will be set // If there are no relative lock times, the LockPoints don't depend on the chain if (lp->maxInputBlock) { - // Check whether chainActive is an extension of the block at which the LockPoints + // Check whether ::ChainActive() is an extension of the block at which the LockPoints // calculation was valid. If not LockPoints are no longer valid - if (!chainActive.Contains(lp->maxInputBlock)) { + if (!::ChainActive().Contains(lp->maxInputBlock)) { return false; } } @@ -406,17 +409,17 @@ bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flag AssertLockHeld(cs_main); AssertLockHeld(pool.cs); - CBlockIndex* tip = chainActive.Tip(); + CBlockIndex* tip = ::ChainActive().Tip(); assert(tip != nullptr); CBlockIndex index; index.pprev = tip; - // CheckSequenceLocks() uses chainActive.Height()+1 to evaluate + // CheckSequenceLocks() uses ::ChainActive().Height()+1 to evaluate // height based locks because when SequenceLocks() is called within // ConnectBlock(), the height of the block *being* // evaluated is what is used. // Thus if we want to know if a transaction can be part of the - // *next* block, we need to use one more than chainActive.Height() + // *next* block, we need to use one more than ::ChainActive().Height() index.nHeight = tip->nHeight + 1; std::pair lockPair; @@ -426,7 +429,7 @@ bool CheckSequenceLocks(const CTxMemPool& pool, const CTransaction& tx, int flag lockPair.second = lp->time; } else { - // pcoinsTip contains the UTXO set for chainActive.Tip() + // pcoinsTip contains the UTXO set for ::ChainActive().Tip() CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool); std::vector prevheights; prevheights.resize(tx.vin.size()); @@ -495,7 +498,7 @@ int GetUTXOConfirmations(const COutPoint& outpoint) // -1 means UTXO is yet unknown or already spent LOCK(cs_main); int nPrevoutHeight = GetUTXOHeight(outpoint); - return (nPrevoutHeight > -1 && chainActive.Tip()) ? chainActive.Height() - nPrevoutHeight + 1 : -1; + return (nPrevoutHeight > -1 && ::ChainActive().Tip()) ? ::ChainActive().Height() - nPrevoutHeight + 1 : -1; } @@ -551,9 +554,9 @@ static bool IsCurrentForFeeEstimation() EXCLUSIVE_LOCKS_REQUIRED(cs_main) AssertLockHeld(cs_main); if (IsInitialBlockDownload()) return false; - if (chainActive.Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE)) + if (::ChainActive().Tip()->GetBlockTime() < (GetTime() - MAX_FEE_ESTIMATION_TIP_AGE)) return false; - if (chainActive.Height() < pindexBestHeader->nHeight - 1) + if (::ChainActive().Height() < pindexBestHeader->nHeight - 1) return false; return true; } @@ -605,7 +608,7 @@ static void UpdateMempoolForReorg(DisconnectedBlockTransactions &disconnectpool, mempool.UpdateTransactionsFromBlock(vHashUpdate); // We also need to remove any now-immature transactions - mempool.removeForReorg(pcoinsTip.get(), chainActive.Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); + mempool.removeForReorg(pcoinsTip.get(), ::ChainActive().Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); // Re-limit mempool size, in case we added any transactions LimitMempoolSize(mempool, gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000, gArgs.GetArg("-mempoolexpiry", DEFAULT_MEMPOOL_EXPIRY) * 60 * 60); } @@ -669,7 +672,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool if (!CheckTransaction(tx, state)) return false; // state filled in by CheckTransaction - if (!ContextualCheckTransaction(tx, state, chainparams.GetConsensus(), chainActive.Tip())) + if (!ContextualCheckTransaction(tx, state, chainparams.GetConsensus(), ::ChainActive().Tip())) return error("%s: ContextualCheckTransaction: %s, %s", __func__, hash.ToString(), FormatStateMessage(state)); if (tx.nVersion == 3 && tx.nType == TRANSACTION_QUORUM_COMMITMENT) { @@ -800,7 +803,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool } } - CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(), + CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, ::ChainActive().Height(), fSpendsCoinbase, nSigOps, lp); unsigned int nSize = entry.GetTxSize(); @@ -843,7 +846,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool // DoS scoring a node for non-critical errors, e.g. duplicate keys because a TX is received that was already // mined // NOTE: we use UTXO here and do NOT allow mempool txes as masternode collaterals - if (!CheckSpecialTx(tx, chainActive.Tip(), state, *pcoinsTip.get())) + if (!CheckSpecialTx(tx, ::ChainActive().Tip(), state, *pcoinsTip.get())) return false; if (pool.existsProviderTxConflict(tx)) { @@ -873,7 +876,7 @@ static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool // There is a similar check in CreateNewBlock() to prevent creating // invalid blocks (using TestBlockValidity), however allowing such // transactions into the mempool can be exploited as a DoS attack. - unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(chainActive.Tip(), chainparams.GetConsensus()); + unsigned int currentBlockScriptVerifyFlags = GetBlockScriptFlags(::ChainActive().Tip(), chainparams.GetConsensus()); if (!CheckInputsFromMempoolAndCache(tx, state, view, pool, currentBlockScriptVerifyFlags, true, txdata)) { return error("%s: BUG! PLEASE REPORT THIS! CheckInputs failed against latest-block but not STANDARD flags %s, %s", __func__, hash.ToString(), FormatStateMessage(state)); @@ -1262,11 +1265,11 @@ bool IsInitialBlockDownload() return false; if (fImporting || fReindex) return true; - if (chainActive.Tip() == nullptr) + if (::ChainActive().Tip() == nullptr) return true; - if (chainActive.Tip()->nChainWork < nMinimumChainWork) + if (::ChainActive().Tip()->nChainWork < nMinimumChainWork) return true; - if (chainActive.Tip()->GetBlockTime() < (GetTime() - nMaxTipAge)) + if (::ChainActive().Tip()->GetBlockTime() < (GetTime() - nMaxTipAge)) return true; LogPrintf("Leaving InitialBlockDownload (latching to false)\n"); latchToFalse.store(true, std::memory_order_relaxed); @@ -1303,10 +1306,10 @@ static void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main) // If our best fork is no longer within 72 blocks (+/- 3 hours if no one mines it) // of our head, drop it - if (pindexBestForkTip && chainActive.Height() - pindexBestForkTip->nHeight >= 72) + if (pindexBestForkTip && ::ChainActive().Height() - pindexBestForkTip->nHeight >= 72) pindexBestForkTip = nullptr; - if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > chainActive.Tip()->nChainWork + (GetBlockProof(*chainActive.Tip()) * 6))) + if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > ::ChainActive().Tip()->nChainWork + (GetBlockProof(*::ChainActive().Tip()) * 6))) { if (!GetfLargeWorkForkFound() && pindexBestForkBase) { @@ -1327,7 +1330,7 @@ static void CheckForkWarningConditions() EXCLUSIVE_LOCKS_REQUIRED(cs_main) } else { - if(pindexBestInvalid->nHeight > chainActive.Height() + 6) + if(pindexBestInvalid->nHeight > ::ChainActive().Height() + 6) LogPrintf("%s: Warning: Found invalid chain at least ~6 blocks longer than our best chain.\nChain state database corruption likely.\n", __func__); else LogPrintf("%s: Warning: Found invalid chain which has higher work (at least ~6 blocks worth of work) than our best chain.\nChain state database corruption likely.\n", __func__); @@ -1346,7 +1349,7 @@ static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) E AssertLockHeld(cs_main); // If we are on a fork that is sufficiently large, set a warning flag CBlockIndex* pfork = pindexNewForkTip; - CBlockIndex* plonger = chainActive.Tip(); + CBlockIndex* plonger = ::ChainActive().Tip(); while (pfork && pfork != plonger) { while (plonger && plonger->nHeight > pfork->nHeight) @@ -1365,7 +1368,7 @@ static void CheckForkWarningConditionsOnNewFork(CBlockIndex* pindexNewForkTip) E // the 7-block condition and from this always have the most-likely-to-cause-warning fork if (pfork && (!pindexBestForkTip || pindexNewForkTip->nHeight > pindexBestForkTip->nHeight) && pindexNewForkTip->nChainWork - pfork->nChainWork > (GetBlockProof(*pfork) * 7) && - chainActive.Height() - pindexNewForkTip->nHeight < 72) + ::ChainActive().Height() - pindexNewForkTip->nHeight < 72) { pindexBestForkTip = pindexNewForkTip; pindexBestForkBase = pfork; @@ -1384,10 +1387,10 @@ void static InvalidChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIRED(c LogPrintf("%s: invalid block=%s height=%d log2_work=%.8f date=%s\n", __func__, pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime())); - CBlockIndex *tip = chainActive.Tip(); + CBlockIndex *tip = ::ChainActive().Tip(); assert (tip); LogPrintf("%s: current best=%s height=%d log2_work=%.8f date=%s\n", __func__, - tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0), + tip->GetBlockHash().ToString(), ::ChainActive().Height(), log(tip->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(tip->GetBlockTime())); CheckForkWarningConditions(); } @@ -1399,10 +1402,10 @@ void static ConflictingChainFound(CBlockIndex* pindexNew) EXCLUSIVE_LOCKS_REQUIR LogPrintf("%s: conflicting block=%s height=%d log2_work=%.8f date=%s\n", __func__, pindexNew->GetBlockHash().ToString(), pindexNew->nHeight, log(pindexNew->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(pindexNew->GetBlockTime())); - CBlockIndex *tip = chainActive.Tip(); + CBlockIndex *tip = ::ChainActive().Tip(); assert (tip); LogPrintf("%s: current best=%s height=%d log2_work=%.8f date=%s\n", __func__, - tip->GetBlockHash().ToString(), chainActive.Height(), log(tip->nChainWork.getdouble())/log(2.0), + tip->GetBlockHash().ToString(), ::ChainActive().Height(), log(tip->nChainWork.getdouble())/log(2.0), FormatISO8601DateTime(tip->GetBlockTime())); CheckForkWarningConditions(); } @@ -1944,10 +1947,10 @@ int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Para bool GetBlockHash(uint256& hashRet, int nBlockHeight) { LOCK(cs_main); - if(chainActive.Tip() == nullptr) return false; - if(nBlockHeight < -1 || nBlockHeight > chainActive.Height()) return false; - if(nBlockHeight == -1) nBlockHeight = chainActive.Height(); - hashRet = chainActive[nBlockHeight]->GetBlockHash(); + if(::ChainActive().Tip() == nullptr) return false; + if(nBlockHeight < -1 || nBlockHeight > ::ChainActive().Height()) return false; + if(nBlockHeight == -1) nBlockHeight = ::ChainActive().Height(); + hashRet = ::ChainActive()[nBlockHeight]->GetBlockHash(); return true; } @@ -2462,7 +2465,7 @@ bool CChainState::ConnectBlock(const CBlock& block, CValidationState& state, CBl boost::posix_time::time_duration diff = finish - start; statsClient.timing("ConnectBlock_ms", diff.total_milliseconds(), 1.0f); statsClient.gauge("blocks.tip.SizeBytes", ::GetSerializeSize(block, PROTOCOL_VERSION), 1.0f); - statsClient.gauge("blocks.tip.Height", chainActive.Height(), 1.0f); + statsClient.gauge("blocks.tip.Height", m_chain.Height(), 1.0f); statsClient.gauge("blocks.tip.Version", block.nVersion, 1.0f); statsClient.gauge("blocks.tip.NumTransactions", block.vtx.size(), 1.0f); statsClient.gauge("blocks.tip.SigOps", nSigOps, 1.0f); @@ -2603,7 +2606,7 @@ bool static FlushStateToDisk(const CChainParams& chainparams, CValidationState & } if (full_flush_completed) { // Update best block in wallet (so we can detect restored wallets). - GetMainSignals().ChainStateFlushed(chainActive.GetLocator()); + GetMainSignals().ChainStateFlushed(::ChainActive().GetLocator()); } } catch (const std::runtime_error& e) { return AbortNode(state, std::string("System error while flushing: ") + e.what()); @@ -2696,7 +2699,7 @@ void static UpdateTip(const CBlockIndex *pindexNew, const CChainParams& chainPar LogPrintf("%s\n", strMessage); } -/** Disconnect chainActive's tip. +/** Disconnect m_chain's tip. * After calling, the mempool will be in an inconsistent state, with * transactions from disconnected blocks being added to disconnectpool. You * should make the mempool consistent again by calling UpdateMempoolForReorg. @@ -2710,7 +2713,7 @@ bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& cha { AssertLockHeld(cs_main); - CBlockIndex *pindexDelete = chainActive.Tip(); + CBlockIndex *pindexDelete = m_chain.Tip(); assert(pindexDelete); // Read block from disk. std::shared_ptr pblock = std::make_shared(); @@ -2748,7 +2751,7 @@ bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& cha } } - chainActive.SetTip(pindexDelete->pprev); + m_chain.SetTip(pindexDelete->pprev); UpdateTip(pindexDelete->pprev, chainparams); // Let wallets know transactions went from 1-confirmed to @@ -2826,7 +2829,7 @@ public: }; /** - * Connect a new block to chainActive. pblock is either nullptr or a pointer to a CBlock + * Connect a new block to m_chain. pblock is either nullptr or a pointer to a CBlock * corresponding to pindexNew, to bypass loading it again from disk. * * The block is added to connectTrace if connection succeeds. @@ -2834,7 +2837,7 @@ public: bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool) { boost::posix_time::ptime start = boost::posix_time::microsec_clock::local_time(); - assert(pindexNew->pprev == chainActive.Tip()); + assert(pindexNew->pprev == m_chain.Tip()); // Read block from disk. int64_t nTime1 = GetTimeMicros(); std::shared_ptr pthisBlock; @@ -2878,8 +2881,8 @@ bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainp // Remove conflicting transactions from the mempool.; mempool.removeForBlock(blockConnecting.vtx, pindexNew->nHeight); disconnectpool.removeForBlock(blockConnecting.vtx); - // Update chainActive & related variables. - chainActive.SetTip(pindexNew); + // Update m_chain & related variables. + m_chain.SetTip(pindexNew); UpdateTip(pindexNew, chainparams); int64_t nTime6 = GetTimeMicros(); nTimePostConnect += nTime6 - nTime5; nTimeTotal += nTime6 - nTime1; @@ -2914,7 +2917,7 @@ CBlockIndex* CChainState::FindMostWorkChain() { // Just going until the active chain is an optimization, as we know all blocks in it are valid already. CBlockIndex *pindexTest = pindexNew; bool fInvalidAncestor = false; - while (pindexTest && !chainActive.Contains(pindexTest)) { + while (pindexTest && !m_chain.Contains(pindexTest)) { assert(pindexTest->HaveTxsDownloaded() || pindexTest->nHeight == 0); // Pruned nodes may have entries in setBlockIndexCandidates for @@ -2961,7 +2964,7 @@ void CChainState::PruneBlockIndexCandidates() { // Note that we can't delete the current block itself, as we may need to return to it later in case a // reorganization to a better block fails. std::set::iterator it = setBlockIndexCandidates.begin(); - while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, chainActive.Tip())) { + while (it != setBlockIndexCandidates.end() && setBlockIndexCandidates.value_comp()(*it, m_chain.Tip())) { setBlockIndexCandidates.erase(it++); } // Either the current tip or a successor of it we're working towards is left in setBlockIndexCandidates. @@ -2976,13 +2979,13 @@ bool CChainState::ActivateBestChainStep(CValidationState& state, const CChainPar { AssertLockHeld(cs_main); - const CBlockIndex *pindexOldTip = chainActive.Tip(); - const CBlockIndex *pindexFork = chainActive.FindFork(pindexMostWork); + const CBlockIndex *pindexOldTip = m_chain.Tip(); + const CBlockIndex *pindexFork = m_chain.FindFork(pindexMostWork); // Disconnect active blocks which are no longer in the best chain. bool fBlocksDisconnected = false; DisconnectedBlockTransactions disconnectpool; - while (chainActive.Tip() && chainActive.Tip() != pindexFork) { + while (m_chain.Tip() && m_chain.Tip() != pindexFork) { if (!DisconnectTip(state, chainparams, &disconnectpool)) { // This is likely a fatal error, but keep the mempool consistent, // just in case. Only remove from the mempool in this case. @@ -3035,7 +3038,7 @@ bool CChainState::ActivateBestChainStep(CValidationState& state, const CChainPar } } else { PruneBlockIndexCandidates(); - if (!pindexOldTip || chainActive.Tip()->nChainWork > pindexOldTip->nChainWork) { + if (!pindexOldTip || m_chain.Tip()->nChainWork > pindexOldTip->nChainWork) { // We're in a better position than we were. Return temporarily to release the lock. fContinue = false; break; @@ -3124,7 +3127,7 @@ bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams& { LOCK(cs_main); - CBlockIndex* starting_tip = chainActive.Tip(); + CBlockIndex* starting_tip = m_chain.Tip(); bool blocks_connected = false; do { // We absolutely may not unlock cs_main until we've made forward progress @@ -3136,7 +3139,7 @@ bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams& } // Whether we have anything to do at all. - if (pindexMostWork == nullptr || pindexMostWork == chainActive.Tip()) { + if (pindexMostWork == nullptr || pindexMostWork == m_chain.Tip()) { break; } @@ -3150,16 +3153,16 @@ bool CChainState::ActivateBestChain(CValidationState &state, const CChainParams& // Wipe cache, we may need another branch now. pindexMostWork = nullptr; } - pindexNewTip = chainActive.Tip(); + pindexNewTip = m_chain.Tip(); for (const PerBlockConnectTrace& trace : connectTrace.GetBlocksConnected()) { assert(trace.pblock && trace.pindex); GetMainSignals().BlockConnected(trace.pblock, trace.pindex, trace.conflictedTxs); } - } while (!chainActive.Tip() || (starting_tip && CBlockIndexWorkComparator()(chainActive.Tip(), starting_tip))); + } while (!m_chain.Tip() || (starting_tip && CBlockIndexWorkComparator()(m_chain.Tip(), starting_tip))); if (!blocks_connected) return true; - const CBlockIndex* pindexFork = chainActive.FindFork(starting_tip); + const CBlockIndex* pindexFork = m_chain.FindFork(starting_tip); bool fInitialDownload = IsInitialBlockDownload(); // Notify external listeners about the new tip. @@ -3206,15 +3209,15 @@ bool CChainState::PreciousBlock(CValidationState& state, const CChainParams& par { { LOCK(cs_main); - if (pindex->nChainWork < chainActive.Tip()->nChainWork) { + if (pindex->nChainWork < m_chain.Tip()->nChainWork) { // Nothing to do, this block is not at the tip. return true; } - if (chainActive.Tip()->nChainWork > nLastPreciousChainwork) { + if (m_chain.Tip()->nChainWork > nLastPreciousChainwork) { // The chain has been extended since the last call, reset the counter. nBlockReverseSequenceId = -1; } - nLastPreciousChainwork = chainActive.Tip()->nChainWork; + nLastPreciousChainwork = m_chain.Tip()->nChainWork; setBlockIndexCandidates.erase(pindex); pindex->nSequenceId = nBlockReverseSequenceId; if (nBlockReverseSequenceId > std::numeric_limits::min()) { @@ -3245,7 +3248,7 @@ bool CChainState::InvalidateBlock(CValidationState& state, const CChainParams& c // nStatus" criteria for inclusion in setBlockIndexCandidates). bool pindex_was_in_chain = false; - CBlockIndex *invalid_walk_tip = chainActive.Tip(); + CBlockIndex *invalid_walk_tip = m_chain.Tip(); if (pindex == pindexBestHeader) { pindexBestInvalid = pindexBestHeader; @@ -3253,10 +3256,10 @@ bool CChainState::InvalidateBlock(CValidationState& state, const CChainParams& c } DisconnectedBlockTransactions disconnectpool; - while (chainActive.Contains(pindex)) { - const CBlockIndex* pindexOldTip = chainActive.Tip(); + while (m_chain.Contains(pindex)) { + const CBlockIndex* pindexOldTip = m_chain.Tip(); pindex_was_in_chain = true; - // ActivateBestChain considers blocks already in chainActive + // ActivateBestChain considers blocks already in m_chain // unconditionally valid already, so force disconnect away from it. if (!DisconnectTip(state, chainparams, &disconnectpool)) { // It's probably hopeless to try to make the mempool consistent @@ -3293,15 +3296,15 @@ bool CChainState::InvalidateBlock(CValidationState& state, const CChainParams& c // add it again. BlockMap::iterator it = mapBlockIndex.begin(); while (it != mapBlockIndex.end()) { - if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && !(it->second->nStatus & BLOCK_CONFLICT_CHAINLOCK) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) { + if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && !(it->second->nStatus & BLOCK_CONFLICT_CHAINLOCK) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) { setBlockIndexCandidates.insert(it->second); } it++; } InvalidChainFound(pindex); - GetMainSignals().SynchronousUpdatedBlockTip(chainActive.Tip(), nullptr, IsInitialBlockDownload()); - GetMainSignals().UpdatedBlockTip(chainActive.Tip(), nullptr, IsInitialBlockDownload()); + GetMainSignals().SynchronousUpdatedBlockTip(m_chain.Tip(), nullptr, IsInitialBlockDownload()); + GetMainSignals().UpdatedBlockTip(m_chain.Tip(), nullptr, IsInitialBlockDownload()); // Only notify about a new block tip if the active chain was modified. if (pindex_was_in_chain) { @@ -3321,17 +3324,17 @@ bool CChainState::MarkConflictingBlock(CValidationState& state, const CChainPara // We first disconnect backwards and then mark the blocks as conflicting. bool pindex_was_in_chain = false; - CBlockIndex *conflicting_walk_tip = chainActive.Tip(); + CBlockIndex *conflicting_walk_tip = m_chain.Tip(); if (pindex == pindexBestHeader) { pindexBestHeader = pindexBestHeader->pprev; } DisconnectedBlockTransactions disconnectpool; - while (chainActive.Contains(pindex)) { - const CBlockIndex* pindexOldTip = chainActive.Tip(); + while (m_chain.Contains(pindex)) { + const CBlockIndex* pindexOldTip = m_chain.Tip(); pindex_was_in_chain = true; - // ActivateBestChain considers blocks already in chainActive + // ActivateBestChain considers blocks already in m_chain // unconditionally valid already, so force disconnect away from it. if (!DisconnectTip(state, chainparams, &disconnectpool)) { // It's probably hopeless to try to make the mempool consistent @@ -3364,15 +3367,15 @@ bool CChainState::MarkConflictingBlock(CValidationState& state, const CChainPara // add it again. BlockMap::iterator it = mapBlockIndex.begin(); while (it != mapBlockIndex.end()) { - if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && !(it->second->nStatus & BLOCK_CONFLICT_CHAINLOCK) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, chainActive.Tip())) { + if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && !(it->second->nStatus & BLOCK_CONFLICT_CHAINLOCK) && it->second->HaveTxsDownloaded() && !setBlockIndexCandidates.value_comp()(it->second, m_chain.Tip())) { setBlockIndexCandidates.insert(it->second); } it++; } ConflictingChainFound(pindex); - GetMainSignals().SynchronousUpdatedBlockTip(chainActive.Tip(), nullptr, IsInitialBlockDownload()); - GetMainSignals().UpdatedBlockTip(chainActive.Tip(), nullptr, IsInitialBlockDownload()); + GetMainSignals().SynchronousUpdatedBlockTip(m_chain.Tip(), nullptr, IsInitialBlockDownload()); + GetMainSignals().UpdatedBlockTip(m_chain.Tip(), nullptr, IsInitialBlockDownload()); // Only notify about a new block tip if the active chain was modified. if (pindex_was_in_chain) { @@ -3389,7 +3392,7 @@ void CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) { AssertLockHeld(cs_main); if (!pindex) { - if (pindexBestInvalid && pindexBestInvalid->GetAncestor(chainActive.Height()) == chainActive.Tip()) { + if (pindexBestInvalid && pindexBestInvalid->GetAncestor(m_chain.Height()) == m_chain.Tip()) { LogPrintf("%s: the best known invalid block (%s) is ahead of our tip, reconsidering\n", __func__, pindexBestInvalid->GetBlockHash().ToString()); pindex = pindexBestInvalid; @@ -3406,7 +3409,7 @@ void CChainState::ResetBlockFailureFlags(CBlockIndex *pindex) { if (!it->second->IsValid() && it->second->GetAncestor(nHeight) == pindex) { it->second->nStatus &= ~BLOCK_FAILED_MASK; setDirtyBlockIndex.insert(it->second); - if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && !(it->second->nStatus & BLOCK_CONFLICT_CHAINLOCK) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(chainActive.Tip(), it->second)) { + if (it->second->IsValid(BLOCK_VALID_TRANSACTIONS) && !(it->second->nStatus & BLOCK_CONFLICT_CHAINLOCK) && it->second->HaveTxsDownloaded() && setBlockIndexCandidates.value_comp()(m_chain.Tip(), it->second)) { setBlockIndexCandidates.insert(it->second); } if (it->second == pindexBestInvalid) { @@ -3516,7 +3519,7 @@ void CChainState::ReceivedBlockTransactions(const CBlock& block, CBlockIndex* pi LOCK(cs_nBlockSequenceId); pindex->nSequenceId = nBlockSequenceId++; } - if (chainActive.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, chainActive.Tip())) { + if (m_chain.Tip() == nullptr || !setBlockIndexCandidates.value_comp()(pindex, m_chain.Tip())) { if (!(pindex->nStatus & BLOCK_CONFLICT_CHAINLOCK)) { setBlockIndexCandidates.insert(pindex); } @@ -3551,7 +3554,7 @@ static bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int n // when the undo file is keeping up with the block file, we want to flush it explicitly // when it is lagging behind (more blocks arrive than are being connected), we let the // undo block write case handle it - finalize_undo = (vinfoBlockFile[nFile].nHeightLast == (unsigned int)chainActive.Tip()->nHeight); + finalize_undo = (vinfoBlockFile[nFile].nHeightLast == (unsigned int)::ChainActive().Tip()->nHeight); nFile++; if (vinfoBlockFile.size() <= nFile) { vinfoBlockFile.resize(nFile + 1); @@ -3985,13 +3988,13 @@ bool CChainState::AcceptBlock(const std::shared_ptr& pblock, CVali // process an unrequested block if it's new and has enough work to // advance our tip, and isn't too many blocks ahead. bool fAlreadyHave = pindex->nStatus & BLOCK_HAVE_DATA; - bool fHasMoreOrSameWork = (chainActive.Tip() ? pindex->nChainWork >= chainActive.Tip()->nChainWork : true); + bool fHasMoreOrSameWork = (m_chain.Tip() ? pindex->nChainWork >= m_chain.Tip()->nChainWork : true); // Blocks that are too out-of-order needlessly limit the effectiveness of // pruning, because pruning will not delete block files that contain any // blocks which are too close in height to the tip. Apply this test // regardless of whether pruning is enabled; it should generally be safe to // not process unrequested blocks. - bool fTooFarAhead = (pindex->nHeight > int(chainActive.Height() + MIN_BLOCKS_TO_KEEP)); + bool fTooFarAhead = (pindex->nHeight > int(m_chain.Height() + MIN_BLOCKS_TO_KEEP)); // TODO: Decouple this function from the block download logic by removing fRequested // This requires some new chain data structure to efficiently look up if a @@ -4024,7 +4027,7 @@ bool CChainState::AcceptBlock(const std::shared_ptr& pblock, CVali // Header is valid/has work, merkle tree is good...RELAY NOW // (but if it does not build on our best tip, let the SendMessages loop relay it) - if (!IsInitialBlockDownload() && chainActive.Tip() == pindex->pprev) + if (!IsInitialBlockDownload() && m_chain.Tip() == pindex->pprev) GetMainSignals().NewPoWValidBlock(pindex, pblock); // Write block to history file @@ -4092,7 +4095,7 @@ bool ProcessNewBlock(const CChainParams& chainparams, const std::shared_ptrHasConflictingChainLock(pindexPrev->nHeight + 1, hash)) { @@ -4190,11 +4193,11 @@ static void FindFilesToPruneManual(std::set& setFilesToPrune, int nManualPr assert(fPruneMode && nManualPruneHeight > 0); LOCK2(cs_main, cs_LastBlockFile); - if (chainActive.Tip() == nullptr) + if (::ChainActive().Tip() == nullptr) return; // last block to prune is the lesser of (user-specified height, MIN_BLOCKS_TO_KEEP from the tip) - unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP); + unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, ::ChainActive().Tip()->nHeight - MIN_BLOCKS_TO_KEEP); int count=0; for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) { if (vinfoBlockFile[fileNumber].nSize == 0 || vinfoBlockFile[fileNumber].nHeightLast > nLastBlockWeCanPrune) @@ -4234,14 +4237,14 @@ void PruneBlockFilesManual(int nManualPruneHeight) static void FindFilesToPrune(std::set& setFilesToPrune, uint64_t nPruneAfterHeight) { LOCK2(cs_main, cs_LastBlockFile); - if (chainActive.Tip() == nullptr || nPruneTarget == 0) { + if (::ChainActive().Tip() == nullptr || nPruneTarget == 0) { return; } - if ((uint64_t)chainActive.Tip()->nHeight <= nPruneAfterHeight) { + if ((uint64_t)::ChainActive().Tip()->nHeight <= nPruneAfterHeight) { return; } - unsigned int nLastBlockWeCanPrune = chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP; + unsigned int nLastBlockWeCanPrune = ::ChainActive().Tip()->nHeight - MIN_BLOCKS_TO_KEEP; uint64_t nCurrentUsage = CalculateCurrentUsage(); // We don't check to prune until after we've allocated new space for files // So we should leave a buffer under our target to account for another allocation @@ -4456,11 +4459,11 @@ bool LoadChainTip(const CChainParams& chainparams) { AssertLockHeld(cs_main); - if (chainActive.Tip() && chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true; + if (::ChainActive().Tip() && ::ChainActive().Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) return true; if (pcoinsTip->GetBestBlock().IsNull() && mapBlockIndex.size() == 1) { // In case we just added the genesis block, connect it now, so - // that we always have a chainActive.Tip() when we return. + // that we always have a ::ChainActive().Tip() when we return. LogPrintf("%s: Connecting genesis block...\n", __func__); CValidationState state; if (!ActivateBestChain(state, chainparams)) { @@ -4474,14 +4477,14 @@ bool LoadChainTip(const CChainParams& chainparams) if (!pindex) { return false; } - chainActive.SetTip(pindex); + ::ChainActive().SetTip(pindex); g_chainstate.PruneBlockIndexCandidates(); LogPrintf("Loaded best chain: hashBestChain=%s height=%d date=%s progress=%f\n", - chainActive.Tip()->GetBlockHash().ToString(), chainActive.Height(), - FormatISO8601DateTime(chainActive.Tip()->GetBlockTime()), - GuessVerificationProgress(chainparams.TxData(), chainActive.Tip())); + ::ChainActive().Tip()->GetBlockHash().ToString(), ::ChainActive().Height(), + FormatISO8601DateTime(::ChainActive().Tip()->GetBlockTime()), + GuessVerificationProgress(chainparams.TxData(), ::ChainActive().Tip())); return true; } @@ -4498,15 +4501,15 @@ CVerifyDB::~CVerifyDB() bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, int nCheckLevel, int nCheckDepth) { LOCK(cs_main); - if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr) + if (::ChainActive().Tip() == nullptr || ::ChainActive().Tip()->pprev == nullptr) return true; // begin tx and let it rollback auto dbTx = evoDb->BeginTransaction(); // Verify blocks in the best chain - if (nCheckDepth <= 0 || nCheckDepth > chainActive.Height()) - nCheckDepth = chainActive.Height(); + if (nCheckDepth <= 0 || nCheckDepth > ::ChainActive().Height()) + nCheckDepth = ::ChainActive().Height(); nCheckLevel = std::max(0, std::min(4, nCheckLevel)); LogPrintf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel); CCoinsViewCache coins(coinsview); @@ -4516,16 +4519,16 @@ bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, CValidationState state; int reportDone = 0; LogPrintf("[0%%]..."); /* Continued */ - for (pindex = chainActive.Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { + for (pindex = ::ChainActive().Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); - const int percentageDone = std::max(1, std::min(99, (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))); + const int percentageDone = std::max(1, std::min(99, (int)(((double)(::ChainActive().Height() - pindex->nHeight)) / (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))); if (reportDone < percentageDone/10) { // report every 10% step LogPrintf("[%d%%]...", percentageDone); /* Continued */ reportDone = percentageDone/10; } uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false); - if (pindex->nHeight <= chainActive.Height()-nCheckDepth) + if (pindex->nHeight <= ::ChainActive().Height()-nCheckDepth) break; if (fPruneMode && !(pindex->nStatus & BLOCK_HAVE_DATA)) { // If pruning, only go back as far as we have data. @@ -4567,23 +4570,23 @@ bool CVerifyDB::VerifyDB(const CChainParams& chainparams, CCoinsView *coinsview, return true; } if (pindexFailure) - return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", chainActive.Height() - pindexFailure->nHeight + 1, nGoodTransactions); + return error("VerifyDB(): *** coin database inconsistencies found (last %i blocks, %i good transactions before that)\n", ::ChainActive().Height() - pindexFailure->nHeight + 1, nGoodTransactions); // store block count as we move pindex at check level >= 4 - int block_count = chainActive.Height() - pindex->nHeight; + int block_count = ::ChainActive().Height() - pindex->nHeight; // check level 4: try reconnecting blocks if (nCheckLevel >= 4) { - while (pindex != chainActive.Tip()) { + while (pindex != ::ChainActive().Tip()) { boost::this_thread::interruption_point(); - const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(chainActive.Height() - pindex->nHeight)) / (double)nCheckDepth * 50))); + const int percentageDone = std::max(1, std::min(99, 100 - (int)(((double)(::ChainActive().Height() - pindex->nHeight)) / (double)nCheckDepth * 50))); if (reportDone < percentageDone/10) { // report every 10% step LogPrintf("[%d%%]...", percentageDone); /* Continued */ reportDone = percentageDone/10; } uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false); - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); CBlock block; if (!ReadBlockFromDisk(block, pindex, chainparams.GetConsensus())) return error("VerifyDB(): *** ReadBlockFromDisk failed at %d, hash=%s", pindex->nHeight, pindex->GetBlockHash().ToString()); @@ -4717,7 +4720,7 @@ void CChainState::UnloadBlockIndex() { void UnloadBlockIndex() { LOCK(cs_main); - chainActive.SetTip(nullptr); + ::ChainActive().SetTip(nullptr); pindexBestInvalid = nullptr; pindexBestHeader = nullptr; mempool.clear(); @@ -4789,7 +4792,7 @@ bool CChainState::LoadGenesisBlock(const CChainParams& chainparams) LOCK(cs_main); // Check whether we're already initialized by checking for genesis in - // mapBlockIndex. Note that we can't use chainActive here, since it is + // mapBlockIndex. Note that we can't use m_chain here, since it is // set based on the coins db, not the block index db, which is the only // thing loaded at this point. if (mapBlockIndex.count(chainparams.GenesisBlock().GetHash())) @@ -4952,8 +4955,8 @@ void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams) // During a reindex, we read the genesis block and call CheckBlockIndex before ActivateBestChain, // so we have the genesis block in mapBlockIndex but no active chain. (A few of the tests when - // iterating the block tree require that chainActive has been initialized.) - if (chainActive.Height() < 0) { + // iterating the block tree require that m_chain has been initialized.) + if (m_chain.Height() < 0) { assert(mapBlockIndex.size() <= 1); return; } @@ -4999,7 +5002,7 @@ void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams) if (pindex->pprev == nullptr) { // Genesis block checks. assert(pindex->GetBlockHash() == consensusParams.hashGenesisBlock); // Genesis block's hash must match. - assert(pindex == chainActive.Genesis()); // The current active chain's genesis block must be this block. + assert(pindex == m_chain.Genesis()); // The current active chain's genesis block must be this block. } if (!pindex->HaveTxsDownloaded()) assert(pindex->nSequenceId <= 0); // nSequenceId can't be set positive for blocks that aren't linked (negative is used for preciousblock) // VALID_TRANSACTIONS is equivalent to nTx > 0 for all nodes (whether or not pruning has occurred). @@ -5032,13 +5035,13 @@ void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams) // Checks for not-conflciting blocks. assert((pindex->nStatus & BLOCK_CONFLICT_CHAINLOCK) == 0); // The conflicting mask cannot be set for blocks without conflicting parents. } - if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && pindexFirstNeverProcessed == nullptr) { + if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && pindexFirstNeverProcessed == nullptr) { if (pindexFirstInvalid == nullptr && pindexFirstConflicing == nullptr) { // If this block sorts at least as good as the current tip and // is valid and we have all data for its parents, it must be in - // setBlockIndexCandidates. chainActive.Tip() must also be there + // setBlockIndexCandidates. m_chain.Tip() must also be there // even if some data has been pruned. - if (pindexFirstMissing == nullptr || pindex == chainActive.Tip()) { + if (pindexFirstMissing == nullptr || pindex == m_chain.Tip()) { assert(setBlockIndexCandidates.count(pindex)); } // If some parent is missing, then it could be that this block was in @@ -5072,11 +5075,11 @@ void CChainState::CheckBlockIndex(const Consensus::Params& consensusParams) // - it has a descendant that at some point had more work than the // tip, and // - we tried switching to that descendant but were missing - // data for some intermediate block between chainActive and the + // data for some intermediate block between m_chain and the // tip. - // So if this block is itself better than chainActive.Tip() and it wasn't in + // So if this block is itself better than m_chain.Tip() and it wasn't in // setBlockIndexCandidates, then it must be in mapBlocksUnlinked. - if (!CBlockIndexWorkComparator()(pindex, chainActive.Tip()) && setBlockIndexCandidates.count(pindex) == 0) { + if (!CBlockIndexWorkComparator()(pindex, m_chain.Tip()) && setBlockIndexCandidates.count(pindex) == 0) { if (pindexFirstInvalid == nullptr) { assert(foundInUnlinked); } @@ -5147,19 +5150,19 @@ CBlockFileInfo* GetBlockFileInfo(size_t n) ThresholdState VersionBitsTipState(const Consensus::Params& params, Consensus::DeploymentPos pos) { AssertLockHeld(cs_main); - return VersionBitsState(chainActive.Tip(), params, pos, versionbitscache); + return VersionBitsState(::ChainActive().Tip(), params, pos, versionbitscache); } BIP9Stats VersionBitsTipStatistics(const Consensus::Params& params, Consensus::DeploymentPos pos) { LOCK(cs_main); - return VersionBitsStatistics(chainActive.Tip(), params, pos, versionbitscache); + return VersionBitsStatistics(::ChainActive().Tip(), params, pos, versionbitscache); } int VersionBitsTipStateSinceHeight(const Consensus::Params& params, Consensus::DeploymentPos pos) { LOCK(cs_main); - return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, versionbitscache); + return VersionBitsStateSinceHeight(::ChainActive().Tip(), params, pos, versionbitscache); } static const uint64_t MEMPOOL_DUMP_VERSION = 1; diff --git a/src/validation.h b/src/validation.h index cd3b32bcdb..ec5eb61539 100644 --- a/src/validation.h +++ b/src/validation.h @@ -98,7 +98,7 @@ static const bool DEFAULT_SYNC_MEMPOOL = true; /** Default for -stopatheight */ static const int DEFAULT_STOPATHEIGHT = 0; -/** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of chainActive.Tip() will not be pruned. */ +/** Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ::ChainActive().Tip() will not be pruned. */ static const unsigned int MIN_BLOCKS_TO_KEEP = 288; static const signed int DEFAULT_CHECKBLOCKS = 6; static const unsigned int DEFAULT_CHECKLEVEL = 3; @@ -423,8 +423,8 @@ bool MarkConflictingBlock(CValidationState& state, const CChainParams& chainpara /** Remove invalidity status from a block and its descendants. */ void ResetBlockFailureFlags(CBlockIndex* pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main); -/** The currently-connected chain of blocks (protected by cs_main). */ -extern CChain& chainActive; +/** @returns the most-work chain. */ +CChain& ChainActive(); /** Global variable that points to the coins database (protected by cs_main) */ extern std::unique_ptr pcoinsdbview; @@ -450,8 +450,8 @@ extern VersionBitsCache versionbitscache; int32_t ComputeBlockVersion(const CBlockIndex* pindexPrev, const Consensus::Params& params, bool fCheckMasternodesUpgraded = false); /** - * Return true if hash can be found in chainActive at nBlockHeight height. - * Fills hashRet with found hash, if no nBlockHeight is specified - chainActive.Height() is used. + * Return true if hash can be found in ::ChainActive() at nBlockHeight height. + * Fills hashRet with found hash, if no nBlockHeight is specified - ::ChainActive().Height() is used. */ bool GetBlockHash(uint256& hashRet, int nBlockHeight = -1); diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp index aa2d3c2981..b4875643c0 100644 --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -365,7 +365,7 @@ UniValue importprunedfunds(const JSONRPCRequest& request) auto locked_chain = pwallet->chain().lock(); const CBlockIndex* pindex = LookupBlockIndex(merkleBlock.header.GetHash()); - if (!pindex || !chainActive.Contains(pindex)) { + if (!pindex || !::ChainActive().Contains(pindex)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); } @@ -561,7 +561,7 @@ UniValue importwallet(const JSONRPCRequest& request) if (!file.is_open()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); } - nTimeBegin = chainActive.Tip()->GetBlockTime(); + nTimeBegin = ::ChainActive().Tip()->GetBlockTime(); int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); @@ -801,20 +801,20 @@ UniValue importelectrumwallet(const JSONRPCRequest& request) int nStartHeight = 0; if (!request.params[1].isNull()) nStartHeight = request.params[1].get_int(); - if (chainActive.Height() < nStartHeight) - nStartHeight = chainActive.Height(); + if (::ChainActive().Height() < nStartHeight) + nStartHeight = ::ChainActive().Height(); // Assume that electrum wallet was created at that block - int nTimeBegin = chainActive[nStartHeight]->GetBlockTime(); + int nTimeBegin = ::ChainActive()[nStartHeight]->GetBlockTime(); pwallet->UpdateTimeFirstKey(nTimeBegin); - pwallet->WalletLogPrintf("Rescanning %i blocks\n", chainActive.Height() - nStartHeight + 1); + pwallet->WalletLogPrintf("Rescanning %i blocks\n", ::ChainActive().Height() - nStartHeight + 1); WalletRescanReserver reserver(pwallet); if (!reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } const CBlockIndex *stop_block, *failed_block; - pwallet->ScanForWalletTransactions(chainActive[nStartHeight], nullptr, reserver, failed_block, stop_block, true); + pwallet->ScanForWalletTransactions(::ChainActive()[nStartHeight], nullptr, reserver, failed_block, stop_block, true); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); @@ -991,15 +991,15 @@ UniValue dumpwallet(const JSONRPCRequest& request) // produce output file << strprintf("# Wallet dump created by Dash Core %s\n", CLIENT_BUILD); file << strprintf("# * Created on %s\n", FormatISO8601DateTime(GetTime())); - file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); - file << strprintf("# mined on %s\n", FormatISO8601DateTime(chainActive.Tip()->GetBlockTime())); + file << strprintf("# * Best block at time of backup was %i (%s),\n", ::ChainActive().Height(), ::ChainActive().Tip()->GetBlockHash().ToString()); + file << strprintf("# mined on %s\n", FormatISO8601DateTime(::ChainActive().Tip()->GetBlockTime())); file << "\n"; UniValue obj(UniValue::VOBJ); obj.pushKV("dashcoreversion", CLIENT_BUILD); - obj.pushKV("lastblockheight", chainActive.Height()); - obj.pushKV("lastblockhash", chainActive.Tip()->GetBlockHash().ToString()); - obj.pushKV("lastblocktime", FormatISO8601DateTime(chainActive.Tip()->GetBlockTime())); + obj.pushKV("lastblockheight", ::ChainActive().Height()); + obj.pushKV("lastblockhash", ::ChainActive().Tip()->GetBlockHash().ToString()); + obj.pushKV("lastblocktime", FormatISO8601DateTime(::ChainActive().Tip()->GetBlockTime())); // add the base58check encoded extended master if the wallet uses HD CHDChain hdChainCurrent; @@ -1408,15 +1408,15 @@ UniValue importmulti(const JSONRPCRequest& mainRequest) EnsureWalletIsUnlocked(pwallet); // Verify all timestamps are present before importing any keys. - now = chainActive.Tip() ? chainActive.Tip()->GetMedianTimePast() : 0; + now = ::ChainActive().Tip() ? ::ChainActive().Tip()->GetMedianTimePast() : 0; for (const UniValue& data : requests.getValues()) { GetImportTimestamp(data, now); } const int64_t minimumTimestamp = 1; - if (fRescan && chainActive.Tip()) { - nLowestTimestamp = chainActive.Tip()->GetBlockTime(); + if (fRescan && ::ChainActive().Tip()) { + nLowestTimestamp = ::ChainActive().Tip()->GetBlockTime(); } else { fRescan = false; } diff --git a/src/wallet/rpcwallet.cpp b/src/wallet/rpcwallet.cpp index 5dc8c3720b..8d1bafeaf2 100644 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -1728,11 +1728,11 @@ static UniValue listsinceblock(const JSONRPCRequest& request) if (!pindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } - if (chainActive[pindex->nHeight] != pindex) { + if (::ChainActive()[pindex->nHeight] != pindex) { // the block being asked for is a part of a deactivated chain; // we don't want to depend on its perceived height in the block // chain, we want to instead use the last common ancestor - pindex = chainActive.FindFork(pindex); + pindex = ::ChainActive().FindFork(pindex); } } @@ -1750,7 +1750,7 @@ static UniValue listsinceblock(const JSONRPCRequest& request) bool include_removed = (request.params[3].isNull() || request.params[3].get_bool()); - int depth = pindex ? (1 + chainActive.Height() - pindex->nHeight) : -1; + int depth = pindex ? (1 + ::ChainActive().Height() - pindex->nHeight) : -1; UniValue transactions(UniValue::VARR); @@ -1781,7 +1781,7 @@ static UniValue listsinceblock(const JSONRPCRequest& request) paltindex = paltindex->pprev; } - CBlockIndex *pblockLast = chainActive[chainActive.Height() + 1 - target_confirms]; + CBlockIndex *pblockLast = ::ChainActive()[::ChainActive().Height() + 1 - target_confirms]; uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256(); UniValue ret(UniValue::VOBJ); @@ -2895,7 +2895,7 @@ static UniValue upgradetohd(const JSONRPCRequest& request) throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } const CBlockIndex *stop_block, *failed_block; - pwallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver, failed_block, stop_block, true); + pwallet->ScanForWalletTransactions(::ChainActive().Genesis(), nullptr, reserver, failed_block, stop_block, true); } return true; @@ -3770,18 +3770,18 @@ static UniValue rescanblockchain(const JSONRPCRequest& request) CBlockIndex *pChainTip = nullptr; { auto locked_chain = pwallet->chain().lock(); - pindexStart = chainActive.Genesis(); - pChainTip = chainActive.Tip(); + pindexStart = ::ChainActive().Genesis(); + pChainTip = ::ChainActive().Tip(); if (!request.params[0].isNull()) { - pindexStart = chainActive[request.params[0].get_int()]; + pindexStart = ::ChainActive()[request.params[0].get_int()]; if (!pindexStart) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid start_height"); } } if (!request.params[1].isNull()) { - pindexStop = chainActive[request.params[1].get_int()]; + pindexStop = ::ChainActive()[request.params[1].get_int()]; if (!pindexStop) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid stop_height"); } diff --git a/src/wallet/test/coinjoin_tests.cpp b/src/wallet/test/coinjoin_tests.cpp index 173c9b5947..a749c5e481 100644 --- a/src/wallet/test/coinjoin_tests.cpp +++ b/src/wallet/test/coinjoin_tests.cpp @@ -48,7 +48,7 @@ public: WalletRescanReserver reserver(wallet.get()); reserver.reserve(); const CBlockIndex *stop_block, *failed_block; - wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver, failed_block, stop_block); + wallet->ScanForWalletTransactions(::ChainActive().Genesis(), nullptr, reserver, failed_block, stop_block); } ~CTransactionBuilderTestSetup() @@ -71,7 +71,7 @@ public: } CreateAndProcessBlock({blocktx}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); LOCK2(cs_main, wallet->cs_wallet); - it->second.SetMerkleBranch(chainActive.Tip(), 1); + it->second.SetMerkleBranch(::ChainActive().Tip(), 1); return it->second; } CompactTallyItem GetTallyItem(const std::vector& vecAmounts) diff --git a/src/wallet/test/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp index 9efca02b33..0a8088cc12 100644 --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -42,10 +42,10 @@ BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup) // Cap last block file size, and mine new block in a new block file. const CBlockIndex* const null_block = nullptr; - CBlockIndex* oldTip = chainActive.Tip(); + CBlockIndex* oldTip = ::ChainActive().Tip(); GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE; CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); - CBlockIndex* newTip = chainActive.Tip(); + CBlockIndex* newTip = ::ChainActive().Tip(); LockAnnotation lock(::cs_main); // for PruneOneBlockFile auto locked_chain = chain->lock(); @@ -132,7 +132,7 @@ BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) // Create two blocks with same timestamp to verify that importwallet rescan // will pick up both blocks, not just the first. - const int64_t BLOCK_TIME = chainActive.Tip()->GetBlockTimeMax() + 5; + const int64_t BLOCK_TIME = ::ChainActive().Tip()->GetBlockTimeMax() + 5; SetMockTime(BLOCK_TIME); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); m_coinbase_txns.emplace_back(CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); @@ -200,7 +200,7 @@ BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) CWalletTx wtx(&wallet, m_coinbase_txns.back()); auto locked_chain = chain->lock(); LOCK(wallet.cs_wallet); - wtx.hashBlock = chainActive.Tip()->GetBlockHash(); + wtx.hashBlock = ::ChainActive().Tip()->GetBlockHash(); wtx.nIndex = 0; // Call GetImmatureCredit() once before adding the key to the wallet to @@ -299,8 +299,8 @@ public: reserver.reserve(); const CBlockIndex* const null_block = nullptr; const CBlockIndex *stop_block, *failed_block; - BOOST_CHECK_EQUAL(wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver, failed_block, stop_block), CWallet::ScanResult::SUCCESS); - BOOST_CHECK_EQUAL(stop_block, chainActive.Tip()); + BOOST_CHECK_EQUAL(wallet->ScanForWalletTransactions(::ChainActive().Genesis(), nullptr, reserver, failed_block, stop_block), CWallet::ScanResult::SUCCESS); + BOOST_CHECK_EQUAL(stop_block, ::ChainActive().Tip()); BOOST_CHECK_EQUAL(failed_block, null_block); } @@ -330,7 +330,7 @@ public: LOCK(wallet->cs_wallet); auto it = wallet->mapWallet.find(tx->GetHash()); BOOST_CHECK(it != wallet->mapWallet.end()); - it->second.SetMerkleBranch(chainActive.Tip(), 1); + it->second.SetMerkleBranch(::ChainActive().Tip(), 1); return it->second; } @@ -434,7 +434,7 @@ public: WalletRescanReserver reserver(wallet.get()); reserver.reserve(); const CBlockIndex *stop_block, *failed_block; - wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver, failed_block, stop_block); + wallet->ScanForWalletTransactions(::ChainActive().Genesis(), nullptr, reserver, failed_block, stop_block); } std::unique_ptr m_chain = interfaces::MakeChain(); @@ -536,7 +536,7 @@ public: LOCK2(cs_main, wallet->cs_wallet); auto it = wallet->mapWallet.find(tx->GetHash()); BOOST_CHECK(it != wallet->mapWallet.end()); - it->second.SetMerkleBranch(chainActive.Tip(), 1); + it->second.SetMerkleBranch(::ChainActive().Tip(), 1); std::vector vecOutpoints; size_t n; @@ -881,7 +881,7 @@ BOOST_FIXTURE_TEST_CASE(select_coins_grouped_by_addresses, ListCoinsTestingSetup WalletRescanReserver reserver(wallet.get()); reserver.reserve(); const CBlockIndex *stop_block, *failed_block; - BOOST_CHECK_EQUAL(wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver, failed_block, stop_block), CWallet::ScanResult::SUCCESS); + BOOST_CHECK_EQUAL(wallet->ScanForWalletTransactions(::ChainActive().Genesis(), nullptr, reserver, failed_block, stop_block), CWallet::ScanResult::SUCCESS); { LOCK(wallet->cs_wallet); const auto& conflicts = wallet->GetConflicts(tx2->GetHash()); diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp index 80d7d6642b..276f0236aa 100644 --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1316,8 +1316,8 @@ void CWallet::MarkConflicted(const uint256& hashBlock, const uint256& hashTx) int conflictconfirms = 0; CBlockIndex* pindex = LookupBlockIndex(hashBlock); - if (pindex && chainActive.Contains(pindex)) { - conflictconfirms = -(chainActive.Height() - pindex->nHeight + 1); + if (pindex && ::ChainActive().Contains(pindex)) { + conflictconfirms = -(::ChainActive().Height() - pindex->nHeight + 1); } // If number of conflict confirms cannot be determined, this means // that the block is still unknown or not yet part of the main chain, @@ -1479,12 +1479,12 @@ void CWallet::BlockUntilSyncedToCurrentChain() { { // Skip the queue-draining stuff if we know we're caught up with - // chainActive.Tip()... + // ::ChainActive().Tip()... // We could also take cs_wallet here, and call m_last_block_processed // protected by cs_wallet instead of cs_main, but as long as we need // cs_main here anyway, it's easier to just call it cs_main-protected. auto locked_chain = chain().lock(); - const CBlockIndex* initialChainTip = chainActive.Tip(); + const CBlockIndex* initialChainTip = ::ChainActive().Tip(); if (m_last_block_processed && m_last_block_processed->GetAncestor(initialChainTip->nHeight) == initialChainTip) { return; @@ -2111,8 +2111,8 @@ int64_t CWallet::RescanFromTime(int64_t startTime, const WalletRescanReserver& r CBlockIndex* startBlock = nullptr; { auto locked_chain = chain().lock(); - startBlock = chainActive.FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW); - WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? chainActive.Height() - startBlock->nHeight + 1 : 0); + startBlock = ::ChainActive().FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW); + WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, startBlock ? ::ChainActive().Height() - startBlock->nHeight + 1 : 0); } if (startBlock) { @@ -2170,7 +2170,7 @@ CWallet::ScanResult CWallet::ScanForWalletTransactions(const CBlockIndex* const auto locked_chain = chain().lock(); progress_begin = GuessVerificationProgress(chainParams.TxData(), pindex); if (pindexStop == nullptr) { - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); progress_end = GuessVerificationProgress(chainParams.TxData(), tip); } else { progress_end = GuessVerificationProgress(chainParams.TxData(), pindexStop); @@ -2191,7 +2191,7 @@ CWallet::ScanResult CWallet::ScanForWalletTransactions(const CBlockIndex* const if (ReadBlockFromDisk(block, pindex, Params().GetConsensus())) { auto locked_chain = chain().lock(); LOCK(cs_wallet); - if (pindex && !chainActive.Contains(pindex)) { + if (pindex && !::ChainActive().Contains(pindex)) { // Abort scan if current block is no longer active, to prevent // marking transactions as coming from the wrong block. failed_block = pindex; @@ -2211,10 +2211,10 @@ CWallet::ScanResult CWallet::ScanForWalletTransactions(const CBlockIndex* const } { auto locked_chain = chain().lock(); - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); progress_current = GuessVerificationProgress(chainParams.TxData(), pindex); - if (pindexStop == nullptr && tip != chainActive.Tip()) { - tip = chainActive.Tip(); + if (pindexStop == nullptr && tip != ::ChainActive().Tip()) { + tip = ::ChainActive().Tip(); // in case the tip has changed, update progress max progress_end = GuessVerificationProgress(chainParams.TxData(), tip); } @@ -3493,7 +3493,7 @@ bool CWallet::CreateTransaction(interfaces::Chain::Lock& locked_chain, const std // now we ensure code won't be written that makes assumptions about // nLockTime that preclude a fix later. - txNew.nLockTime = chainActive.Height(); + txNew.nLockTime = ::ChainActive().Height(); // Secondly occasionally randomly pick a nLockTime even further back, so // that transactions that are delayed after signing for whatever reason, @@ -3502,7 +3502,7 @@ bool CWallet::CreateTransaction(interfaces::Chain::Lock& locked_chain, const std if (GetRandInt(10) == 0) txNew.nLockTime = std::max(0, (int)txNew.nLockTime - GetRandInt(100)); - assert(txNew.nLockTime <= (unsigned int)chainActive.Height()); + assert(txNew.nLockTime <= (unsigned int)::ChainActive().Height()); assert(txNew.nLockTime < LOCKTIME_THRESHOLD); FeeCalculation feeCalc; CFeeRate discard_rate = coin_control.m_discard_feerate ? *coin_control.m_discard_feerate : GetDiscardRate(*this, ::feeEstimator); @@ -4646,7 +4646,7 @@ void CWallet::GetKeyBirthTimes(interfaces::Chain::Lock& locked_chain, std::map mapKeyFirstBlock; for (const CKeyID &keyid : GetKeys()) { if (mapKeyBirth.count(keyid) == 0) @@ -4663,7 +4663,7 @@ void CWallet::GetKeyBirthTimes(interfaces::Chain::Lock& locked_chain, std::mapnHeight; for (const CTxOut &txout : wtx.tx->vout) { @@ -4979,7 +4979,7 @@ std::shared_ptr CWallet::CreateWalletFromFile(interfaces::Chain& chain, } auto locked_chain = chain.assumeLocked(); // Temporary. Removed in upcoming lock cleanup - walletInstance->ChainStateFlushed(chainActive.GetLocator()); + walletInstance->ChainStateFlushed(::ChainActive().GetLocator()); // Try to create wallet backup right after new wallet was created std::string strBackupWarning; @@ -5089,25 +5089,25 @@ std::shared_ptr CWallet::CreateWalletFromFile(interfaces::Chain& chain, auto locked_chain = chain.lock(); LOCK(walletInstance->cs_wallet); - CBlockIndex *pindexRescan = chainActive.Genesis(); + CBlockIndex *pindexRescan = ::ChainActive().Genesis(); if (!gArgs.GetBoolArg("-rescan", false)) { WalletBatch batch(*walletInstance->database); CBlockLocator locator; if (batch.ReadBestBlock(locator)) - pindexRescan = FindForkInGlobalIndex(chainActive, locator); + pindexRescan = FindForkInGlobalIndex(::ChainActive(), locator); } - walletInstance->m_last_block_processed = chainActive.Tip(); + walletInstance->m_last_block_processed = ::ChainActive().Tip(); - if (chainActive.Tip() && chainActive.Tip() != pindexRescan) + if (::ChainActive().Tip() && ::ChainActive().Tip() != pindexRescan) { //We can't rescan beyond non-pruned blocks, stop and throw an error //this might happen if a user uses an old wallet within a pruned node // or if he ran -disablewallet for a longer time, then decided to re-enable if (fPruneMode) { - CBlockIndex *block = chainActive.Tip(); + CBlockIndex *block = ::ChainActive().Tip(); while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block) block = block->pprev; @@ -5117,14 +5117,14 @@ std::shared_ptr CWallet::CreateWalletFromFile(interfaces::Chain& chain, } uiInterface.InitMessage(_("Rescanning...")); - walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight); + walletInstance->WalletLogPrintf("Rescanning last %i blocks (from block %i)...\n", ::ChainActive().Height() - pindexRescan->nHeight, pindexRescan->nHeight); // No need to read and scan block if block was created before // our wallet birthday (as adjusted for block time variability) // unless a full rescan was requested if (gArgs.GetArg("-rescan", 0) != 2) { while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) { - pindexRescan = chainActive.Next(pindexRescan); + pindexRescan = ::ChainActive().Next(pindexRescan); } } @@ -5137,7 +5137,7 @@ std::shared_ptr CWallet::CreateWalletFromFile(interfaces::Chain& chain, } } walletInstance->WalletLogPrintf("Rescan completed in %15dms\n", GetTimeMillis() - nStart); - walletInstance->ChainStateFlushed(chainActive.GetLocator()); + walletInstance->ChainStateFlushed(::ChainActive().GetLocator()); walletInstance->database->IncrementUpdateCounter(); // Restore wallet transaction metadata after -zapwallettxes=1 @@ -5428,10 +5428,10 @@ int CMerkleTx::GetDepthInMainChain(interfaces::Chain::Lock& locked_chain) const // Find the block it claims to be in CBlockIndex* pindex = LookupBlockIndex(hashBlock); - if (!pindex || !chainActive.Contains(pindex)) + if (!pindex || !::ChainActive().Contains(pindex)) return 0; - return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1); + return ((nIndex == -1) ? (-1) : 1) * (::ChainActive().Height() - pindex->nHeight + 1); } bool CMerkleTx::IsLockedByInstantSend() const