diff --git a/src/avalanche.cpp b/src/avalanche.cpp --- a/src/avalanche.cpp +++ b/src/avalanche.cpp @@ -139,7 +139,7 @@ return false; } - isAccepted = chainActive.Contains(pindex); + isAccepted = ::ChainActive().Contains(pindex); } return vote_records.getWriteView() diff --git a/src/bench/duplicate_inputs.cpp b/src/bench/duplicate_inputs.cpp --- a/src/bench/duplicate_inputs.cpp +++ b/src/bench/duplicate_inputs.cpp @@ -50,14 +50,14 @@ LoadGenesisBlock(chainparams); CValidationState cvstate; ActivateBestChain(config, cvstate); - assert(::chainActive.Tip() != nullptr); + assert(::ChainActive().Tip() != nullptr); } CBlock block{}; CMutableTransaction coinbaseTx{}; CMutableTransaction naughtyTx{}; - CBlockIndex *pindexPrev = ::chainActive.Tip(); + CBlockIndex *pindexPrev = ::ChainActive().Tip(); assert(pindexPrev != nullptr); block.nBits = GetNextWorkRequired(pindexPrev, &block, chainparams.GetConsensus()); diff --git a/src/index/base.cpp b/src/index/base.cpp --- a/src/index/base.cpp +++ b/src/index/base.cpp @@ -60,9 +60,9 @@ 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; } @@ -71,15 +71,15 @@ 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() { @@ -143,7 +143,7 @@ bool BaseIndex::WriteBestBlock(const CBlockIndex *block_index) { LOCK(cs_main); - if (!GetDB().WriteBestBlock(chainActive.GetLocator(block_index))) { + if (!GetDB().WriteBestBlock(::ChainActive().GetLocator(block_index))) { return error("%s: Failed to write locator to disk", __func__); } return true; @@ -239,9 +239,9 @@ { // 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 --- a/src/index/txindex.cpp +++ b/src/index/txindex.cpp @@ -238,7 +238,7 @@ // 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 --- a/src/init.cpp +++ b/src/init.cpp @@ -712,7 +712,7 @@ true, OptionsCategory::DEBUG_TEST); gArgs.AddArg("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, " - "setBlockIndexCandidates, chainActive and " + "setBlockIndexCandidates, ::ChainActive() and " "mapBlocksUnlinked occasionally. (default: %u)", defaultChainParams->DefaultConsistencyChecks()), true, OptionsCategory::DEBUG_TEST); @@ -2232,13 +2232,13 @@ 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(config)) { strLoadError = _("Error initializing block database"); break; } - assert(chainActive.Tip() != nullptr); + assert(::ChainActive().Tip() != nullptr); uiInterface.InitMessage(_("Verifying blocks...")); if (fHavePruned && @@ -2250,7 +2250,7 @@ MIN_BLOCKS_TO_KEEP); } - CBlockIndex *tip = chainActive.Tip(); + CBlockIndex *tip = ::ChainActive().Tip(); RPCNotifyBlockChange(true, tip); if (tip && tip->nTime > GetAdjustedTime() + MAX_FUTURE_BLOCK_TIME) { @@ -2362,7 +2362,7 @@ // 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; @@ -2404,7 +2404,7 @@ { LOCK(cs_main); LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); - chain_active_height = chainActive.Height(); + chain_active_height = ::ChainActive().Height(); } LogPrintf("nBestHeight = %d\n", chain_active_height); diff --git a/src/interfaces/node.cpp b/src/interfaces/node.cpp --- a/src/interfaces/node.cpp +++ b/src/interfaces/node.cpp @@ -191,12 +191,12 @@ } 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(); } // Genesis block's time of current network return Params().GenesisBlock().GetBlockTime(); @@ -205,7 +205,7 @@ 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 --- a/src/interfaces/wallet.cpp +++ b/src/interfaces/wallet.cpp @@ -316,8 +316,8 @@ if (mi == m_wallet.mapWallet.end()) { return false; } - num_blocks = ::chainActive.Height(); - block_time = ::chainActive.Tip()->GetBlockTime(); + num_blocks = ::ChainActive().Height(); + block_time = ::ChainActive().Tip()->GetBlockTime(); tx_status = MakeWalletTxStatus(*locked_chain, mi->second); return true; } @@ -329,7 +329,7 @@ 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); @@ -364,7 +364,7 @@ return false; } balances = getBalances(); - num_blocks = ::chainActive.Height(); + num_blocks = ::ChainActive().Height(); return true; } Amount getBalance() override { return m_wallet.GetBalance(); } diff --git a/src/miner.cpp b/src/miner.cpp --- a/src/miner.cpp +++ b/src/miner.cpp @@ -145,7 +145,7 @@ pblocktemplate->entries.emplace_back(CTransactionRef(), -SATOSHI, -1); 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 --- a/src/net_processing.cpp +++ b/src/net_processing.cpp @@ -707,7 +707,7 @@ static bool CanDirectFetch(const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { - return chainActive.Tip()->GetBlockTime() > + return ::ChainActive().Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20; } @@ -746,7 +746,7 @@ if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < - chainActive.Tip()->nChainWork || + ::ChainActive().Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) { // This peer has nothing interesting. return; @@ -755,8 +755,8 @@ 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 @@ -803,7 +803,7 @@ // We consider the chain that this peer is on invalid. return; } - if (pindex->nStatus.hasData() || chainActive.Contains(pindex)) { + if (pindex->nStatus.hasData() || ::ChainActive().Contains(pindex)) { if (pindex->HaveTxsDownloaded()) { state->pindexLastCommonBlock = pindex; } @@ -1179,7 +1179,7 @@ const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); - if (chainActive.Contains(pindex)) { + if (::ChainActive().Contains(pindex)) { return true; } return pindex->IsValid(BlockValidity::SCRIPTS) && @@ -1321,7 +1321,7 @@ /** * 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, @@ -1416,13 +1416,14 @@ switch (inv.type) { case MSG_TX: { assert(recentRejects); - if (chainActive.Tip()->GetBlockHash() != + 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(); } @@ -1577,7 +1578,7 @@ ((((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && - (chainActive.Tip()->nHeight - pindex->nHeight > + (::ChainActive().Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2)))) { LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED " @@ -1646,7 +1647,7 @@ int nSendFlags = 0; if (CanDirectFetch(consensusParams) && pindex->nHeight >= - chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) { + ::ChainActive().Height() - MAX_CMPCTBLOCK_DEPTH) { CBlockHeaderAndShortTxIDs cmpctblock(*pblock); connman->PushMessage( pfrom, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, @@ -1665,7 +1666,8 @@ // 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 = BlockHash(); } @@ -1805,9 +1807,10 @@ nCount < MAX_BLOCKS_TO_ANNOUNCE) { nodestate->nUnconnectingHeaders++; connman->PushMessage( - pfrom, msgMaker.Make(NetMsgType::GETHEADERS, - chainActive.GetLocator(pindexBestHeader), - uint256())); + pfrom, + msgMaker.Make(NetMsgType::GETHEADERS, + ::ChainActive().GetLocator(pindexBestHeader), + uint256())); LogPrint( BCLog::NET, "received header %s: missing prev block %s, sending getheaders " @@ -1912,35 +1915,36 @@ // still present, however, as belt-and-suspenders. if (received_new_header && - pindexLast->nChainWork > chainActive.Tip()->nChainWork) { + 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 from there instead. + // 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())); + 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(BlockValidity::TREE) && - chainActive.Tip()->nChainWork <= pindexLast->nChainWork) { + ::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) && + while (pindexWalk && !::ChainActive().Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { if (!pindexWalk->nStatus.hasData() && !mapBlocksInFlight.count(pindexWalk->GetBlockHash())) { @@ -1953,7 +1957,7 @@ // 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); @@ -2005,7 +2009,7 @@ // 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. @@ -2025,7 +2029,7 @@ if (g_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= - chainActive.Tip()->nChainWork && + ::ChainActive().Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) { LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", @@ -2490,10 +2494,10 @@ // 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), - hash)); + pfrom, msgMaker.Make( + NetMsgType::GETHEADERS, + ::ChainActive().GetLocator(pindexBestHeader), + hash)); LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, hash.ToString(), pfrom->GetId()); @@ -2573,18 +2577,19 @@ 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) { LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); @@ -2598,8 +2603,8 @@ 3600 / chainparams.GetConsensus().nPowTargetSpacing; if (fPruneMode && (!pindex->nStatus.hasData() || - pindex->nHeight <= - chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave)) { + pindex->nHeight <= ::ChainActive().Tip()->nHeight - + nPrunedBlocksLikelyToHave)) { LogPrint( BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", @@ -2647,7 +2652,7 @@ 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 @@ -2715,9 +2720,9 @@ } } 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); } } @@ -2729,15 +2734,15 @@ (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 - // headers message). In both cases it's safe to update + // 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. // // It is important that we simply reset the BestHeaderSent value here, @@ -2747,7 +2752,8 @@ // 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; @@ -2997,10 +3003,10 @@ // AcceptBlockHeader, request deeper headers if (!IsInitialBlockDownload()) { connman->PushMessage( - pfrom, - msgMaker.Make(NetMsgType::GETHEADERS, - chainActive.GetLocator(pindexBestHeader), - uint256())); + pfrom, msgMaker.Make( + NetMsgType::GETHEADERS, + ::ChainActive().GetLocator(pindexBestHeader), + uint256())); } return true; } @@ -3058,7 +3064,7 @@ // 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) { + pindex->nChainWork > ::ChainActive().Tip()->nChainWork) { nodestate->m_last_block_announcement = GetTime(); } @@ -3074,7 +3080,9 @@ } if (pindex->nChainWork <= - chainActive.Tip()->nChainWork || // We know something better + ::ChainActive() + .Tip() + ->nChainWork || // We know something better pindex->nTx != 0) { // We had this block at some point, but pruned it if (fAlreadyInFlight) { @@ -3098,7 +3106,7 @@ // 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 && @@ -3868,7 +3876,7 @@ // them elsewhere). if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= - chainActive.Tip()->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; @@ -3884,7 +3892,7 @@ // catch up to some earlier point 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) { @@ -3918,7 +3926,7 @@ connman->PushMessage( pto, msgMaker.Make(NetMsgType::GETHEADERS, - chainActive.GetLocator( + ::ChainActive().GetLocator( state.m_chain_sync.m_work_header->pprev), uint256())); state.m_chain_sync.m_sent_getheaders = true; @@ -4158,7 +4166,7 @@ // Start block sync if (pindexBestHeader == nullptr) { - pindexBestHeader = chainActive.Tip(); + pindexBestHeader = ::ChainActive().Tip(); } // Download if this is a nice peer, or we have no nice peers and this one @@ -4196,9 +4204,9 @@ "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())); + pto, msgMaker.Make(NetMsgType::GETHEADERS, + ::ChainActive().GetLocator(pindexStart), + uint256())); } } @@ -4234,11 +4242,11 @@ 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 an headers that - // aren't on chainActive, give up. + // aren't on ::ChainActive(), give up. for (const BlockHash &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; @@ -4346,11 +4354,11 @@ // 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()); + ::ChainActive().Tip()->GetBlockHash().ToString()); } // If the peer's chain has this block, don't inv it back. diff --git a/src/qt/test/wallettests.cpp b/src/qt/test/wallettests.cpp --- a/src/qt/test/wallettests.cpp +++ b/src/qt/test/wallettests.cpp @@ -130,7 +130,7 @@ auto locked_chain = wallet->chain().lock(); WalletRescanReserver reserver(wallet.get()); reserver.reserve(); - wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, + wallet->ScanForWalletTransactions(::ChainActive().Genesis(), nullptr, reserver, true); } wallet->SetBroadcastTransactions(true); diff --git a/src/rest.cpp b/src/rest.cpp --- a/src/rest.cpp +++ b/src/rest.cpp @@ -156,14 +156,14 @@ 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() == size_t(count)) { break; } - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); } } @@ -225,7 +225,7 @@ 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"); @@ -584,8 +584,8 @@ // serialize data // use exact same output as mentioned in Bip64 CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION); - ssGetUTXOResponse << chainActive.Height() - << chainActive.Tip()->GetBlockHash() << bitmap + ssGetUTXOResponse << ::ChainActive().Height() + << ::ChainActive().Tip()->GetBlockHash() << bitmap << outs; std::string ssGetUTXOResponseString = ssGetUTXOResponse.str(); @@ -596,8 +596,8 @@ case RetFormat::HEX: { CDataStream ssGetUTXOResponse(SER_NETWORK, PROTOCOL_VERSION); - ssGetUTXOResponse << chainActive.Height() - << chainActive.Tip()->GetBlockHash() << bitmap + ssGetUTXOResponse << ::ChainActive().Height() + << ::ChainActive().Tip()->GetBlockHash() << bitmap << outs; std::string strHex = HexStr(ssGetUTXOResponse.begin(), ssGetUTXOResponse.end()) + @@ -613,9 +613,9 @@ // pack in some essentials // use more or less the same output as mentioned in Bip64 - objGetUTXOResponse.pushKV("chainHeight", chainActive.Height()); + objGetUTXOResponse.pushKV("chainHeight", ::ChainActive().Height()); objGetUTXOResponse.pushKV( - "chaintipHash", chainActive.Tip()->GetBlockHash().GetHex()); + "chaintipHash", ::ChainActive().Tip()->GetBlockHash().GetHex()); objGetUTXOResponse.pushKV("bitmap", bitmapStringRepresentation); UniValue utxos(UniValue::VARR); diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -166,7 +166,7 @@ } LOCK(cs_main); - return chainActive.Height(); + return ::ChainActive().Height(); } static UniValue getbestblockhash(const Config &config, @@ -184,7 +184,7 @@ } LOCK(cs_main); - return chainActive.Tip()->GetBlockHash().GetHex(); + return ::ChainActive().Tip()->GetBlockHash().GetHex(); } UniValue getfinalizedblockhash(const Config &config, @@ -407,7 +407,7 @@ } LOCK(cs_main); - return GetDifficulty(chainActive.Tip()); + return GetDifficulty(::ChainActive().Tip()); } static std::string EntryDescriptionString() { @@ -759,11 +759,11 @@ 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(); } @@ -832,7 +832,7 @@ { LOCK(cs_main); pblockindex = LookupBlockIndex(hash); - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); } if (!pblockindex) { @@ -964,7 +964,8 @@ return strHex; } - return blockToJSON(block, chainActive.Tip(), pblockindex, verbosity >= 2); + return blockToJSON(block, ::ChainActive().Tip(), pblockindex, + verbosity >= 2); } struct CCoinsStats { @@ -1078,7 +1079,7 @@ // Add a 2 hour buffer to include blocks which might have had old // timestamps CBlockIndex *pindex = - chainActive.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW); + ::ChainActive().FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW); if (!pindex) { throw JSONRPCError( RPC_INVALID_PARAMETER, @@ -1088,7 +1089,7 @@ } unsigned int height = (unsigned int)heightParam; - unsigned int chainHeight = (unsigned int)chainActive.Height(); + unsigned int chainHeight = (unsigned int)::ChainActive().Height(); if (chainHeight < config.GetChainParams().PruneAfterHeight()) { throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning."); @@ -1384,10 +1385,10 @@ const CChainParams &chainparams = config.GetChainParams(); - const CBlockIndex *tip = chainActive.Tip(); + const CBlockIndex *tip = ::ChainActive().Tip(); UniValue obj(UniValue::VOBJ); obj.pushKV("chain", chainparams.NetworkIDString()); - 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))); @@ -1486,14 +1487,13 @@ 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. - * Algorithm: + * 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; @@ -1501,7 +1501,7 @@ 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); } @@ -1515,7 +1515,7 @@ } // Always report the currently active tip. - setTips.insert(chainActive.Tip()); + setTips.insert(::ChainActive().Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); @@ -1525,11 +1525,11 @@ obj.pushKV("hash", block->phashBlock->GetHex()); const int branchLen = - block->nHeight - chainActive.FindFork(block)->nHeight; + block->nHeight - ::ChainActive().FindFork(block)->nHeight; obj.pushKV("branchlen", branchLen); 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.isInvalid()) { @@ -1894,7 +1894,7 @@ if (request.params[1].isNull()) { LOCK(cs_main); - pindex = chainActive.Tip(); + pindex = ::ChainActive().Tip(); } else { BlockHash hash(ParseHashV(request.params[1], "blockhash")); LOCK(cs_main); @@ -1902,7 +1902,7 @@ 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"); } @@ -2056,7 +2056,7 @@ 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, @@ -2069,14 +2069,14 @@ current_tip)); } - pindex = chainActive[height]; + pindex = ::ChainActive()[height]; } else { const BlockHash hash(ParseHashV(request.params[0], "hash_or_height")); pindex = LookupBlockIndex(hash); 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/mining.cpp b/src/rpc/mining.cpp --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -40,10 +40,10 @@ * 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) { @@ -123,7 +123,7 @@ { // Don't keep cs_main locked. LOCK(cs_main); - nHeight = chainActive.Height(); + nHeight = ::ChainActive().Height(); nHeightEnd = nHeight + nGenerate; } @@ -142,7 +142,7 @@ { LOCK(cs_main); - IncrementExtraNonce(pblock, chainActive.Tip(), + IncrementExtraNonce(pblock, ::ChainActive().Tip(), config.GetMaxBlockSize(), nExtraNonce); } @@ -251,10 +251,10 @@ 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(config, request)); obj.pushKV("pooledtx", uint64_t(g_mempool.size())); obj.pushKV("chain", config.GetChainParams().NetworkIDString()); @@ -486,7 +486,7 @@ 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"; @@ -538,7 +538,7 @@ } 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; } @@ -574,7 +574,7 @@ static CBlockIndex *pindexPrev; static int64_t nStart; static std::unique_ptr pblocktemplate; - if (pindexPrev != chainActive.Tip() || + if (pindexPrev != ::ChainActive().Tip() || (g_mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any @@ -583,7 +583,7 @@ // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = g_mempool.GetTransactionsUpdated(); - CBlockIndex *pindexPrevNew = chainActive.Tip(); + CBlockIndex *pindexPrevNew = ::ChainActive().Tip(); nStart = GetTime(); // Create new block @@ -654,7 +654,7 @@ result.pushKV("coinbaseaux", aux); result.pushKV("coinbasevalue", int64_t(pblock->vtx[0]->vout[0].nValue / SATOSHI)); - result.pushKV("longpollid", chainActive.Tip()->GetBlockHash().GetHex() + + result.pushKV("longpollid", ::ChainActive().Tip()->GetBlockHash().GetHex() + i64tostr(nTransactionsUpdatedLast)); result.pushKV("target", hashTarget.GetHex()); result.pushKV("mintime", int64_t(pindexPrev->GetMedianTimePast()) + 1); diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -53,9 +53,9 @@ entry.pushKV("blockhash", hashBlock.GetHex()); CBlockIndex *pindex = LookupBlockIndex(hashBlock); if (pindex) { - if (chainActive.Contains(pindex)) { + if (::ChainActive().Contains(pindex)) { entry.pushKV("confirmations", - 1 + chainActive.Height() - pindex->nHeight); + 1 + ::ChainActive().Height() - pindex->nHeight); entry.pushKV("time", pindex->GetBlockTime()); entry.pushKV("blocktime", pindex->GetBlockTime()); } else { @@ -196,7 +196,7 @@ 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; @@ -313,7 +313,7 @@ for (const auto &txid : setTxIds) { const Coin &coin = AccessByTxid(*pcoinsTip, txid); if (!coin.IsSpent()) { - pblockindex = chainActive[coin.GetHeight()]; + pblockindex = ::ChainActive()[coin.GetHeight()]; break; } } @@ -401,7 +401,7 @@ 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/test/denialofservice_tests.cpp b/src/test/denialofservice_tests.cpp --- a/src/test/denialofservice_tests.cpp +++ b/src/test/denialofservice_tests.cpp @@ -93,8 +93,8 @@ // 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/finalization_tests.cpp b/src/test/finalization_tests.cpp --- a/src/test/finalization_tests.cpp +++ b/src/test/finalization_tests.cpp @@ -25,7 +25,7 @@ // the test setup are too close to "now"; BOOST_CHECK_MESSAGE(GetFinalizedBlock() == nullptr, "No block finalized (tip at height " - << chainActive.Tip()->nHeight << ")"); + << ::ChainActive().Tip()->nHeight << ")"); } // Create maxreorgdepth blocks. Auto-finalization will not occur because @@ -37,7 +37,7 @@ // These blocks are too recent. BOOST_CHECK_MESSAGE(GetFinalizedBlock() == nullptr, "No block finalized (tip at height " - << chainActive.Tip()->nHeight << ")"); + << ::ChainActive().Tip()->nHeight << ")"); } // Make the finalization time to expire @@ -45,18 +45,18 @@ SetMockTime(mockedTime); // Next maxreorgdepth blocks should cause auto-finalization - CBlockIndex *blockToFinalize = chainActive.Tip()->GetAncestor( - chainActive.Tip()->nHeight - DEFAULT_MAX_REORG_DEPTH); + CBlockIndex *blockToFinalize = ::ChainActive().Tip()->GetAncestor( + ::ChainActive().Tip()->nHeight - DEFAULT_MAX_REORG_DEPTH); for (uint32_t i = 0; i < DEFAULT_MAX_REORG_DEPTH; i++) { - blockToFinalize = chainActive.Next(blockToFinalize); + blockToFinalize = ::ChainActive().Next(blockToFinalize); block = CreateAndProcessBlock({}, p2pk_scriptPubKey); LOCK(cs_main); BOOST_CHECK_MESSAGE(GetFinalizedBlock() == blockToFinalize, "Block finalized at height " << blockToFinalize->nHeight << " (tip at height " - << chainActive.Tip()->nHeight << ")"); + << ::ChainActive().Tip()->nHeight << ")"); } // Next blocks won't cause auto-finalization because the delay is not @@ -69,27 +69,27 @@ "Finalized block remains unchanged at height " << blockToFinalize->nHeight << " (tip at height " - << chainActive.Tip()->nHeight << ")"); + << ::ChainActive().Tip()->nHeight << ")"); } // Make the finalization time to expire mockedTime += DEFAULT_MIN_FINALIZATION_DELAY + 1; SetMockTime(mockedTime); - blockToFinalize = chainActive.Tip()->GetAncestor( - chainActive.Tip()->nHeight - DEFAULT_MAX_REORG_DEPTH); + blockToFinalize = ::ChainActive().Tip()->GetAncestor( + ::ChainActive().Tip()->nHeight - DEFAULT_MAX_REORG_DEPTH); // Create some more blocks. // Finalization should start moving again. for (uint32_t i = 0; i < DEFAULT_MAX_REORG_DEPTH; i++) { - blockToFinalize = chainActive.Next(blockToFinalize); + blockToFinalize = ::ChainActive().Next(blockToFinalize); block = CreateAndProcessBlock({}, p2pk_scriptPubKey); LOCK(cs_main); BOOST_CHECK_MESSAGE(GetFinalizedBlock() == blockToFinalize, "Block finalized at height " << blockToFinalize->nHeight << " (tip at height " - << chainActive.Tip()->nHeight << ")"); + << ::ChainActive().Tip()->nHeight << ")"); } } diff --git a/src/test/miner_tests.cpp b/src/test/miner_tests.cpp --- a/src/test/miner_tests.cpp +++ b/src/test/miner_tests.cpp @@ -88,7 +88,7 @@ static CBlockIndex CreateBlockIndex(int nHeight) { CBlockIndex index; index.nHeight = nHeight; - index.pprev = chainActive.Tip(); + index.pprev = ::ChainActive().Tip(); return index; } @@ -244,9 +244,9 @@ // IncrementExtraNonce creates a valid coinbase and merkleRoot unsigned int extraNonce = 0; - IncrementExtraNonce(pblock, chainActive.Tip(), config.GetMaxBlockSize(), + IncrementExtraNonce(pblock, ::ChainActive().Tip(), config.GetMaxBlockSize(), extraNonce); - unsigned int nHeight = chainActive.Tip()->nHeight + 1; + unsigned int nHeight = ::ChainActive().Tip()->nHeight + 1; std::vector vec(cbmsg.begin(), cbmsg.end()); BOOST_CHECK(pblock->vtx[0]->vin[0].scriptSig == ((CScript() << nHeight << CScriptNum(extraNonce) << vec) + @@ -295,17 +295,17 @@ { LOCK(cs_main); pblock->nVersion = 1; - 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(); 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.resize(1); 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]); @@ -466,30 +466,30 @@ g_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 BlockHash(InsecureRand256()); pcoinsTip->SetBestBlock(next->GetBlockHash()); next->pprev = prev; next->nHeight = prev->nHeight + 1; next->BuildSkip(); - chainActive.SetTip(next); + ::ChainActive().SetTip(next); } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool) .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 BlockHash(InsecureRand256()); pcoinsTip->SetBestBlock(next->GetBlockHash()); next->pprev = prev; next->nHeight = prev->nHeight + 1; next->BuildSkip(); - chainActive.SetTip(next); + ::ChainActive().SetTip(next); } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool) @@ -518,16 +518,16 @@ g_mempool.clear(); // 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); uint32_t flags = LOCKTIME_VERIFY_SEQUENCE | LOCKTIME_MEDIAN_TIME_PAST; // height map std::vector prevheights; @@ -540,7 +540,7 @@ tx.vin[0].prevout = COutPoint(txFirst[0]->GetId(), 0); tx.vin[0].scriptSig = CScript() << OP_1; // txFirst[0] is the 2nd block - tx.vin[0].nSequence = chainActive.Tip()->nHeight + 1; + tx.vin[0].nSequence = ::ChainActive().Tip()->nHeight + 1; prevheights[0] = baseheight + 1; tx.vout.resize(1); tx.vout[0].nValue = BLOCKSUBSIDY - HIGHFEE; @@ -564,14 +564,14 @@ // Sequence locks pass on 2nd block. BOOST_CHECK( SequenceLocks(CTransaction(tx), flags, &prevheights, - CreateBlockIndex(chainActive.Tip()->nHeight + 2))); + CreateBlockIndex(::ChainActive().Tip()->nHeight + 2))); // Relative time locked. tx.vin[0].prevout = COutPoint(txFirst[1]->GetId(), 0); // txFirst[1] is the 3rd block. tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | - (((chainActive.Tip()->GetMedianTimePast() + 1 - - chainActive[1]->GetMedianTimePast()) >> + (((::ChainActive().Tip()->GetMedianTimePast() + 1 - + ::ChainActive()[1]->GetMedianTimePast()) >> CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) + 1); prevheights[0] = baseheight + 2; @@ -590,24 +590,28 @@ for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) { // Trick the MedianTimePast. - chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += - 512; + ::ChainActive() + .Tip() + ->GetAncestor(::ChainActive().Tip()->nHeight - i) + ->nTime += 512; } // Sequence locks pass 512 seconds later. BOOST_CHECK( SequenceLocks(CTransaction(tx), flags, &prevheights, - CreateBlockIndex(chainActive.Tip()->nHeight + 1))); + CreateBlockIndex(::ChainActive().Tip()->nHeight + 1))); for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) { // Undo tricked MTP. - chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime -= - 512; + ::ChainActive() + .Tip() + ->GetAncestor(::ChainActive().Tip()->nHeight - i) + ->nTime -= 512; } // Absolute height locked. tx.vin[0].prevout = COutPoint(txFirst[2]->GetId(), 0); tx.vin[0].nSequence = CTxIn::SEQUENCE_FINAL - 1; prevheights[0] = baseheight + 3; - tx.nLockTime = chainActive.Tip()->nHeight + 1; + tx.nLockTime = ::ChainActive().Tip()->nHeight + 1; txid = tx.GetId(); g_mempool.addUnchecked(entry.Time(GetTime()).FromTx(tx)); @@ -625,15 +629,15 @@ { // Locktime passes on 2nd block. CValidationState state; - int64_t nMedianTimePast = chainActive.Tip()->GetMedianTimePast(); + int64_t nMedianTimePast = ::ChainActive().Tip()->GetMedianTimePast(); BOOST_CHECK(ContextualCheckTransaction( - params, CTransaction(tx), state, chainActive.Tip()->nHeight + 2, + params, CTransaction(tx), state, ::ChainActive().Tip()->nHeight + 2, nMedianTimePast, nMedianTimePast)); } // Absolute time locked. tx.vin[0].prevout = COutPoint(txFirst[3]->GetId(), 0); - tx.nLockTime = chainActive.Tip()->GetMedianTimePast(); + tx.nLockTime = ::ChainActive().Tip()->GetMedianTimePast(); prevheights.resize(1); prevheights[0] = baseheight + 4; txid = tx.GetId(); @@ -653,15 +657,16 @@ { // Locktime passes 1 second later. CValidationState state; - int64_t nMedianTimePast = chainActive.Tip()->GetMedianTimePast() + 1; + int64_t nMedianTimePast = + ::ChainActive().Tip()->GetMedianTimePast() + 1; BOOST_CHECK(ContextualCheckTransaction( - params, CTransaction(tx), state, chainActive.Tip()->nHeight + 1, + params, CTransaction(tx), state, ::ChainActive().Tip()->nHeight + 1, nMedianTimePast, nMedianTimePast)); } // mempool-dependent transactions (not added) tx.vin[0].prevout = COutPoint(txid, 0); - prevheights[0] = chainActive.Tip()->nHeight + 1; + prevheights[0] = ::ChainActive().Tip()->nHeight + 1; tx.nLockTime = 0; tx.vin[0].nSequence = 0; @@ -697,17 +702,19 @@ // mined. for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) { // Trick the MedianTimePast. - chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += - 512; + ::ChainActive() + .Tip() + ->GetAncestor(::ChainActive().Tip()->nHeight - i) + ->nTime += 512; } - chainActive.Tip()->nHeight++; - SetMockTime(chainActive.Tip()->GetMedianTimePast() + 1); + ::ChainActive().Tip()->nHeight++; + SetMockTime(::ChainActive().Tip()->GetMedianTimePast() + 1); BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams, g_mempool) .CreateNewBlock(scriptPubKey)); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 5UL); - chainActive.Tip()->nHeight--; + ::ChainActive().Tip()->nHeight--; SetMockTime(0); g_mempool.clear(); diff --git a/src/test/test_bitcoin.cpp b/src/test/test_bitcoin.cpp --- a/src/test/test_bitcoin.cpp +++ b/src/test/test_bitcoin.cpp @@ -187,8 +187,8 @@ { LOCK(cs_main); unsigned int extraNonce = 0; - IncrementExtraNonce(&block, chainActive.Tip(), config.GetMaxBlockSize(), - extraNonce); + IncrementExtraNonce(&block, ::ChainActive().Tip(), + config.GetMaxBlockSize(), extraNonce); } const Consensus::Params ¶ms = config.GetChainParams().GetConsensus(); diff --git a/src/test/txvalidationcache_tests.cpp b/src/test/txvalidationcache_tests.cpp --- a/src/test/txvalidationcache_tests.cpp +++ b/src/test/txvalidationcache_tests.cpp @@ -68,18 +68,18 @@ // Test 1: block with both of those transactions should be rejected. block = CreateAndProcessBlock(spends, scriptPubKey); - 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 BOOST_CHECK(ToMemPool(spends[0])); block = CreateAndProcessBlock(spends, scriptPubKey); - BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash()); + BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash()); g_mempool.clear(); // Test 3: ... and should be rejected if spend2 is in the memory pool BOOST_CHECK(ToMemPool(spends[1])); block = CreateAndProcessBlock(spends, scriptPubKey); - BOOST_CHECK(chainActive.Tip()->GetBlockHash() != block.GetHash()); + BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() != block.GetHash()); g_mempool.clear(); // Final sanity test: first spend in mempool, second in block, that's OK: @@ -87,7 +87,7 @@ oneSpend.push_back(spends[0]); BOOST_CHECK(ToMemPool(spends[1])); block = CreateAndProcessBlock(oneSpend, scriptPubKey); - 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: BOOST_CHECK_EQUAL(g_mempool.size(), 0U); @@ -227,7 +227,7 @@ // Spend the funding transaction by mining it into a block { CBlock block = CreateAndProcessBlock({funding_tx}, p2pk_scriptPubKey); - BOOST_CHECK(chainActive.Tip()->GetBlockHash() == block.GetHash()); + BOOST_CHECK(::ChainActive().Tip()->GetBlockHash() == block.GetHash()); BOOST_CHECK(pcoinsTip->GetBestBlock() == block.GetHash()); } @@ -300,7 +300,7 @@ 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 then diff --git a/src/test/validation_block_tests.cpp b/src/test/validation_block_tests.cpp --- a/src/test/validation_block_tests.cpp +++ b/src/test/validation_block_tests.cpp @@ -162,7 +162,7 @@ const CBlockIndex *initial_tip = nullptr; { LOCK(cs_main); - initial_tip = chainActive.Tip(); + initial_tip = ::ChainActive().Tip(); } TestSubscriber sub(initial_tip->GetBlockHash()); RegisterValidationInterface(&sub); @@ -202,7 +202,8 @@ 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 --- a/src/txmempool.h +++ b/src/txmempool.h @@ -527,7 +527,7 @@ * 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/txmempool.cpp b/src/txmempool.cpp --- a/src/txmempool.cpp +++ b/src/txmempool.cpp @@ -1413,7 +1413,7 @@ // We also need to remove any now-immature transactions g_mempool.removeForReorg(config, pcoinsTip.get(), - chainActive.Tip()->nHeight + 1, + ::ChainActive().Tip()->nHeight + 1, STANDARD_LOCKTIME_VERIFY_FLAGS); // Re-limit mempool size, in case we added any transactions diff --git a/src/validation.h b/src/validation.h --- a/src/validation.h +++ b/src/validation.h @@ -239,7 +239,7 @@ extern uint64_t nPruneTarget; /** * Block files containing a block-height within MIN_BLOCKS_TO_KEEP of - * chainActive.Tip() will not be pruned. + * ::ChainActive().Tip() will not be pruned. */ static const unsigned int MIN_BLOCKS_TO_KEEP = 288; /** Minimum blocks required to signal NODE_NETWORK_LIMITED */ @@ -761,9 +761,6 @@ bool IsBlockFinalized(const 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(); diff --git a/src/validation.cpp b/src/validation.cpp --- a/src/validation.cpp +++ b/src/validation.cpp @@ -252,7 +252,6 @@ RecursiveMutex cs_main; BlockMap &mapBlockIndex = g_chainstate.mapBlockIndex; -CChain &chainActive = g_chainstate.m_chain; CBlockIndex *pindexBestHeader = nullptr; Mutex g_best_block_mutex; std::condition_variable g_best_block_cv; @@ -368,10 +367,10 @@ // 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 calculation was valid. If not LockPoints are no longer + // 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; } } @@ -385,16 +384,16 @@ 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 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() + // 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() index.nHeight = tip->nHeight + 1; std::pair lockPair; @@ -403,7 +402,7 @@ lockPair.first = lp->height; 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()); @@ -670,7 +669,7 @@ } const uint32_t nextBlockScriptVerifyFlags = - GetNextBlockScriptFlags(consensusParams, chainActive.Tip()); + GetNextBlockScriptFlags(consensusParams, ::ChainActive().Tip()); // Check for non-standard pay-to-script-hash in inputs if (fRequireStandard && @@ -724,7 +723,7 @@ // Validate input scripts against standard script flags. const uint32_t scriptVerifyFlags = - GetStandardScriptFlags(consensusParams, chainActive.Tip()); + GetStandardScriptFlags(consensusParams, ::ChainActive().Tip()); PrecomputedTransactionData txdata(tx); int nSigChecksStandard; if (!CheckInputs(tx, state, view, true, scriptVerifyFlags, true, false, @@ -741,7 +740,7 @@ ? nSigChecksStandard : nSigOpsCount; - CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, chainActive.Height(), + CTxMemPoolEntry entry(ptx, nFees, nAcceptTime, ::ChainActive().Height(), fSpendsCoinbase, nSigChecksOrOps, lp); unsigned int nVirtualSize = entry.GetTxVirtualSize(); @@ -762,13 +761,13 @@ CTxMemPool::setEntries setAncestors; size_t nLimitAncestors = gArgs.GetArg( "-limitancestorcount", - GetDefaultAncestorLimit(consensusParams, chainActive.Tip())); + GetDefaultAncestorLimit(consensusParams, ::ChainActive().Tip())); size_t nLimitAncestorSize = gArgs.GetArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; size_t nLimitDescendants = gArgs.GetArg( "-limitdescendantcount", - GetDefaultDescendantLimit(consensusParams, chainActive.Tip())); + GetDefaultDescendantLimit(consensusParams, ::ChainActive().Tip())); size_t nLimitDescendantSize = gArgs.GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * @@ -904,7 +903,7 @@ if (fAllowSlow) { const Coin &coin = AccessByTxid(*pcoinsTip, txid); if (!coin.IsSpent()) { - pindexSlow = chainActive[coin.GetHeight()]; + pindexSlow = ::ChainActive()[coin.GetHeight()]; } } } @@ -1031,13 +1030,13 @@ 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"); @@ -1080,15 +1079,15 @@ // If our best fork is no longer within 72 blocks (+/- 12 hours if no one // mines it) of our head, drop it if (pindexBestForkTip && - chainActive.Height() - pindexBestForkTip->nHeight >= 72) { + ::ChainActive().Height() - pindexBestForkTip->nHeight >= 72) { pindexBestForkTip = nullptr; } if (pindexBestForkTip || (pindexBestInvalid && pindexBestInvalid->nChainWork > - chainActive.Tip()->nChainWork + - (GetBlockProof(*chainActive.Tip()) * 6))) { + ::ChainActive().Tip()->nChainWork + + (GetBlockProof(*::ChainActive().Tip()) * 6))) { if (!GetfLargeWorkForkFound() && pindexBestForkBase) { std::string warning = std::string("'Warning: Large-work fork detected, forking after " @@ -1123,7 +1122,7 @@ EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); // If we are on a fork that is sufficiently large, set a warning flag. - const CBlockIndex *pfork = chainActive.FindFork(pindexNewForkTip); + const CBlockIndex *pfork = ::ChainActive().FindFork(pindexNewForkTip); // We define a condition where we should warn the user about as a fork of at // least 7 blocks with a tip within 72 blocks (+/- 12 hours if no one mines @@ -1138,7 +1137,7 @@ 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; } @@ -1165,10 +1164,11 @@ 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=%.8g date=%s\n", - __func__, tip->GetBlockHash().ToString(), chainActive.Height(), + __func__, tip->GetBlockHash().ToString(), + ::ChainActive().Height(), log(tip->nChainWork.getdouble()) / log(2.0), FormatISO8601DateTime(tip->GetBlockTime())); } @@ -2270,7 +2270,7 @@ 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: ") + @@ -2396,7 +2396,7 @@ m_chain.SetTip(pindexDelete->pprev); - // Update chainActive and related variables. + // Update ::ChainActive() and related variables. UpdateTip(config, pindexDelete->pprev); // Let wallets know transactions went from 1-confirmed to // 0-confirmed or conflicted: @@ -3318,9 +3318,9 @@ } // If the finalized block is not on the active chain, we may need to rewind. - if (!chainActive.Contains(pindex)) { - const CBlockIndex *pindexFork = chainActive.FindFork(pindex); - CBlockIndex *pindexToInvalidate = chainActive.Next(pindexFork); + if (!::ChainActive().Contains(pindex)) { + const CBlockIndex *pindexFork = ::ChainActive().FindFork(pindex); + CBlockIndex *pindexToInvalidate = ::ChainActive().Next(pindexFork); if (pindexToInvalidate) { return InvalidateBlock(config, state, pindexToInvalidate); } @@ -3354,7 +3354,8 @@ if (pindex->IsValid(BlockValidity::TRANSACTIONS) && pindex->HaveTxsDownloaded() && - setBlockIndexCandidates.value_comp()(chainActive.Tip(), pindex)) { + setBlockIndexCandidates.value_comp()(::ChainActive().Tip(), + pindex)) { setBlockIndexCandidates.insert(pindex); } return true; @@ -3838,13 +3839,13 @@ // soft-forks are scheduled, so no flags are set. flags = std::max(flags, 0); - // ContextualCheckTransactionForCurrentBlock() 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 ContextualCheckTransaction() with one more - // than chainActive.Height(). - const int nBlockHeight = chainActive.Height() + 1; + // ContextualCheckTransactionForCurrentBlock() 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 ContextualCheckTransaction() + // with one more than ::ChainActive().Height(). + const int nBlockHeight = ::ChainActive().Height() + 1; // BIP113 will require that time-locked transactions have nLockTime set to // less than the median time of the previous block they're contained in. @@ -3852,8 +3853,9 @@ // chain tip, so we use that to calculate the median time passed to // ContextualCheckTransaction() if LOCKTIME_MEDIAN_TIME_PAST is set. const int64_t nMedianTimePast = - chainActive.Tip() == nullptr ? 0 - : chainActive.Tip()->GetMedianTimePast(); + ::ChainActive().Tip() == nullptr + ? 0 + : ::ChainActive().Tip()->GetMedianTimePast(); const int64_t nLockTimeCutoff = (flags & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : GetAdjustedTime(); @@ -4353,7 +4355,7 @@ const CBlock &block, CBlockIndex *pindexPrev, BlockValidationOptions validationOptions) { AssertLockHeld(cs_main); - assert(pindexPrev && pindexPrev == chainActive.Tip()); + assert(pindexPrev && pindexPrev == ::ChainActive().Tip()); CCoinsViewCache viewNew(pcoinsTip.get()); BlockHash block_hash(block.GetHash()); CBlockIndex indexDummy(block); @@ -4461,7 +4463,7 @@ assert(fPruneMode && nManualPruneHeight > 0); LOCK2(cs_main, cs_LastBlockFile); - if (chainActive.Tip() == nullptr) { + if (::ChainActive().Tip() == nullptr) { return; } @@ -4469,7 +4471,7 @@ // MIN_BLOCKS_TO_KEEP from the tip) unsigned int nLastBlockWeCanPrune = std::min((unsigned)nManualPruneHeight, - chainActive.Tip()->nHeight - MIN_BLOCKS_TO_KEEP); + ::ChainActive().Tip()->nHeight - MIN_BLOCKS_TO_KEEP); int count = 0; for (int fileNumber = 0; fileNumber < nLastBlockFile; fileNumber++) { if (vinfoBlockFile[fileNumber].nSize == 0 || @@ -4519,15 +4521,15 @@ 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; + ::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 @@ -4769,14 +4771,14 @@ bool LoadChainTip(const Config &config) { AssertLockHeld(cs_main); - if (chainActive.Tip() && - chainActive.Tip()->GetBlockHash() == pcoinsTip->GetBestBlock()) { + 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(config, state)) { @@ -4791,16 +4793,17 @@ 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()), + ::ChainActive().Tip()->GetBlockHash().ToString(), + ::ChainActive().Height(), + FormatISO8601DateTime(::ChainActive().Tip()->GetBlockTime()), GuessVerificationProgress(config.GetChainParams().TxData(), - chainActive.Tip())); + ::ChainActive().Tip())); return true; } @@ -4819,13 +4822,14 @@ const CChainParams ¶ms = config.GetChainParams(); const Consensus::Params &consensusParams = params.GetConsensus(); - if (chainActive.Tip() == nullptr || chainActive.Tip()->pprev == nullptr) { + if (::ChainActive().Tip() == nullptr || + ::ChainActive().Tip()->pprev == nullptr) { return true; } // 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)); @@ -4839,14 +4843,14 @@ CValidationState state; int reportDone = 0; LogPrintfToBeContinued("[0%%]..."); - for (pindex = chainActive.Tip(); pindex && pindex->pprev; + for (pindex = ::ChainActive().Tip(); pindex && pindex->pprev; pindex = pindex->pprev) { boost::this_thread::interruption_point(); - int percentageDone = std::max( - 1, std::min( - 99, - (int)(((double)(chainActive.Height() - pindex->nHeight)) / - (double)nCheckDepth * (nCheckLevel >= 4 ? 50 : 100)))); + 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 @@ -4856,7 +4860,7 @@ uiInterface.ShowProgress(_("Verifying blocks..."), percentageDone, false); - if (pindex->nHeight <= chainActive.Height() - nCheckDepth) { + if (pindex->nHeight <= ::ChainActive().Height() - nCheckDepth) { break; } @@ -4929,25 +4933,26 @@ if (pindexFailure) { return error("VerifyDB(): *** coin database inconsistencies found " "(last %i blocks, %i good transactions before that)\n", - chainActive.Height() - pindexFailure->nHeight + 1, + ::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(); uiInterface.ShowProgress( _("Verifying blocks..."), std::max( - 1, std::min(99, 100 - (int)(((double)(chainActive.Height() - - pindex->nHeight)) / - (double)nCheckDepth * 50))), + 1, std::min(99, + 100 - (int)(((double)(::ChainActive().Height() - + pindex->nHeight)) / + (double)nCheckDepth * 50))), false); - pindex = chainActive.Next(pindex); + pindex = ::ChainActive().Next(pindex); CBlock block; if (!ReadBlockFromDisk(block, pindex, consensusParams)) { return error( @@ -5116,7 +5121,7 @@ // block index state void UnloadBlockIndex() { LOCK(cs_main); - chainActive.SetTip(nullptr); + ::ChainActive().SetTip(nullptr); pindexFinalized = nullptr; pindexBestInvalid = nullptr; pindexBestParked = nullptr; @@ -5699,7 +5704,7 @@ ThresholdState VersionBitsTipState(const Consensus::Params ¶ms, Consensus::DeploymentPos pos) { LOCK(cs_main); - return VersionBitsStateImpl(params, pos, chainActive.Tip()); + return VersionBitsStateImpl(params, pos, ::ChainActive().Tip()); } ThresholdState VersionBitsBlockState(const Consensus::Params ¶ms, @@ -5712,13 +5717,13 @@ BIP9Stats VersionBitsTipStatistics(const Consensus::Params ¶ms, Consensus::DeploymentPos pos) { LOCK(cs_main); - return VersionBitsStatistics(chainActive.Tip(), params, pos); + return VersionBitsStatistics(::ChainActive().Tip(), params, pos); } int VersionBitsTipStateSinceHeight(const Consensus::Params ¶ms, Consensus::DeploymentPos pos) { LOCK(cs_main); - return VersionBitsStateSinceHeight(chainActive.Tip(), params, pos, + return VersionBitsStateSinceHeight(::ChainActive().Tip(), params, pos, versionbitscache); } diff --git a/src/wallet/rpcdump.cpp b/src/wallet/rpcdump.cpp --- a/src/wallet/rpcdump.cpp +++ b/src/wallet/rpcdump.cpp @@ -445,7 +445,7 @@ 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"); } @@ -664,7 +664,7 @@ throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); } - nTimeBegin = chainActive.Tip()->GetBlockTime(); + nTimeBegin = ::ChainActive().Tip()->GetBlockTime(); int64_t nFilesize = std::max(1, file.tellg()); file.seekg(0, file.beg); @@ -943,10 +943,11 @@ file << strprintf("# Wallet dump created by Bitcoin %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())); + ::ChainActive().Height(), + ::ChainActive().Tip()->GetBlockHash().ToString()); + file << strprintf( + "# mined on %s\n", + FormatISO8601DateTime(::ChainActive().Tip()->GetBlockTime())); file << "\n"; // add the base58check encoded extended master if the wallet uses HD @@ -1481,15 +1482,16 @@ 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 --- a/src/wallet/rpcwallet.cpp +++ b/src/wallet/rpcwallet.cpp @@ -2732,11 +2732,11 @@ 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); } } @@ -2755,7 +2755,7 @@ 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); @@ -2793,7 +2793,7 @@ } CBlockIndex *pblockLast = - chainActive[chainActive.Height() + 1 - target_confirms]; + ::ChainActive()[::ChainActive().Height() + 1 - target_confirms]; uint256 lastblock = pblockLast ? pblockLast->GetBlockHash() : uint256(); UniValue ret(UniValue::VOBJ); @@ -4701,11 +4701,11 @@ 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"); @@ -4713,7 +4713,7 @@ } 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/wallet_tests.cpp b/src/wallet/test/wallet_tests.cpp --- a/src/wallet/test/wallet_tests.cpp +++ b/src/wallet/test/wallet_tests.cpp @@ -40,10 +40,10 @@ // Cap last block file size, and mine new block in a new block file. CBlockIndex *const nullBlock = 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); auto locked_chain = chain->lock(); @@ -136,7 +136,7 @@ // 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({}, @@ -217,7 +217,7 @@ 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 @@ -313,7 +313,7 @@ AddKey(*wallet, coinbaseKey); WalletRescanReserver reserver(wallet.get()); reserver.reserve(); - wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, + wallet->ScanForWalletTransactions(::ChainActive().Genesis(), nullptr, reserver); } @@ -343,7 +343,7 @@ LOCK(wallet->cs_wallet); auto it = wallet->mapWallet.find(tx->GetId()); BOOST_CHECK(it != wallet->mapWallet.end()); - it->second.SetMerkleBranch(chainActive.Tip(), 1); + it->second.SetMerkleBranch(::ChainActive().Tip(), 1); return it->second; } diff --git a/src/wallet/wallet.cpp b/src/wallet/wallet.cpp --- a/src/wallet/wallet.cpp +++ b/src/wallet/wallet.cpp @@ -1295,8 +1295,8 @@ 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 @@ -1421,12 +1421,12 @@ { // 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) { @@ -1888,10 +1888,11 @@ { 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); + ::ChainActive().FindEarliestAtLeast(startTime - TIMESTAMP_WINDOW); + WalletLogPrintf("%s: Rescanning last %i blocks\n", __func__, + startBlock + ? ::ChainActive().Height() - startBlock->nHeight + 1 + : 0); } if (startBlock) { @@ -1952,7 +1953,7 @@ progress_begin = GuessVerificationProgress(chainParams.TxData(), pindex); if (pindexStop == nullptr) { - tip = chainActive.Tip(); + tip = ::ChainActive().Tip(); progress_end = GuessVerificationProgress(chainParams.TxData(), tip); } else { @@ -1982,7 +1983,7 @@ if (ReadBlockFromDisk(block, pindex, chainParams.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. @@ -2002,11 +2003,11 @@ } { 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); @@ -3079,7 +3080,7 @@ // that fee sniping isn't a problem yet, but by implementing a fix 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, @@ -3089,7 +3090,7 @@ 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); { @@ -4266,7 +4267,7 @@ // Map in which we'll infer heights of other keys the tip can be // reorganized; use a 144-block safety margin. CBlockIndex *pindexMax = - chainActive[std::max(0, chainActive.Height() - 144)]; + ::ChainActive()[std::max(0, ::ChainActive().Height() - 144)]; std::map mapKeyFirstBlock; for (const CKeyID &keyid : GetKeys()) { if (mapKeyBirth.count(keyid) == 0) { @@ -4285,7 +4286,7 @@ // iterate over all wallet transactions... const CWalletTx &wtx = entry.second; CBlockIndex *pindex = LookupBlockIndex(wtx.hashBlock); - if (pindex && chainActive.Contains(pindex)) { + if (pindex && ::ChainActive().Contains(pindex)) { // ... which are already in a block int nHeight = pindex->nHeight; for (const CTxOut &txout : wtx.tx->vout) { @@ -4687,7 +4688,7 @@ // Temporary. Removed in upcoming lock cleanup auto locked_chain = chain.assumeLocked(); - walletInstance->ChainStateFlushed(chainActive.GetLocator()); + walletInstance->ChainStateFlushed(::ChainActive().GetLocator()); } else if (wallet_creation_flags & WALLET_FLAG_DISABLE_PRIVATE_KEYS) { // Make it impossible to disable private keys after creation InitError(strprintf(_("Error loading %s: Private keys can only be " @@ -4791,24 +4792,24 @@ 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.hasData() && block->pprev->nTx > 0 && pindexRescan != block) { block = block->pprev; @@ -4825,7 +4826,7 @@ uiInterface.InitMessage(_("Rescanning...")); walletInstance->WalletLogPrintf( "Rescanning last %i blocks (from block %i)...\n", - chainActive.Height() - pindexRescan->nHeight, + ::ChainActive().Height() - pindexRescan->nHeight, pindexRescan->nHeight); // No need to read and scan block if block was created before our wallet @@ -4833,7 +4834,7 @@ while (pindexRescan && walletInstance->nTimeFirstKey && (pindexRescan->GetBlockTime() < (walletInstance->nTimeFirstKey - TIMESTAMP_WINDOW))) { - pindexRescan = chainActive.Next(pindexRescan); + pindexRescan = ::ChainActive().Next(pindexRescan); } nStart = GetTimeMillis(); @@ -4849,7 +4850,7 @@ } 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 @@ -4942,12 +4943,12 @@ // 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); + (::ChainActive().Height() - pindex->nHeight + 1); } int CMerkleTx::GetBlocksToMaturity(