From cced0f46c9133e0fc6211e987421ad1d9be1a399 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Mon, 5 Apr 2021 11:11:22 -0400 Subject: miner: Pass in previous CBlockIndex to RegenerateCommitments --- src/rpc/mining.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src/rpc') diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 72ad0df199..2eddc731c3 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -369,7 +369,8 @@ static RPCHelpMan generateblock() // Add transactions block.vtx.insert(block.vtx.end(), txs.begin(), txs.end()); - RegenerateCommitments(block, WITH_LOCK(::cs_main, return std::ref(g_chainman.m_blockman))); + CBlockIndex* prev_block = WITH_LOCK(::cs_main, return g_chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock)); + RegenerateCommitments(block, prev_block); { LOCK(cs_main); -- cgit v1.2.3 From d0abf0bf429586e3a5b4c3231fe430dc29695481 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Thu, 15 Oct 2020 13:02:06 -0400 Subject: rpc/*,rest: Add review-only assertion to EnsureChainman --- src/rpc/blockchain.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index e1501d7254..bb668984e9 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -79,6 +79,7 @@ ChainstateManager& EnsureChainman(const std::any& context) if (!node.chainman) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Node chainman not found"); } + WITH_LOCK(::cs_main, CHECK_NONFATAL(std::addressof(g_chainman) == std::addressof(*node.chainman))); return *node.chainman; } -- cgit v1.2.3 From d485e815e2b62dc74a485569d08130dc3ef9ff63 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Wed, 14 Oct 2020 15:40:53 -0400 Subject: rpc/blockchain: Use existing NodeContext Also pass in appropriate object to: - BIP9SoftForkDescPushBack - BuriedForkDescPushBack --- src/rpc/blockchain.cpp | 132 ++++++++++++++++++++++++++++--------------------- 1 file changed, 77 insertions(+), 55 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index bb668984e9..ffabca0aff 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -199,7 +199,7 @@ static RPCHelpMan getblockcount() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - return ::ChainActive().Height(); + return EnsureChainman(request.context).ActiveChain().Height(); }, }; } @@ -218,7 +218,7 @@ static RPCHelpMan getbestblockhash() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - return ::ChainActive().Tip()->GetBlockHash().GetHex(); + return EnsureChainman(request.context).ActiveChain().Tip()->GetBlockHash().GetHex(); }, }; } @@ -399,7 +399,7 @@ static RPCHelpMan getdifficulty() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - return GetDifficulty(::ChainActive().Tip()); + return GetDifficulty(EnsureChainman(request.context).ActiveChain().Tip()); }, }; } @@ -764,12 +764,13 @@ static RPCHelpMan getblockhash() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); + const CChain& active_chain = EnsureChainman(request.context).ActiveChain(); int nHeight = request.params[0].get_int(); - if (nHeight < 0 || nHeight > ::ChainActive().Height()) + if (nHeight < 0 || nHeight > active_chain.Height()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range"); - CBlockIndex* pblockindex = ::ChainActive()[nHeight]; + CBlockIndex* pblockindex = active_chain[nHeight]; return pblockindex->GetBlockHash().GetHex(); }, }; @@ -823,8 +824,9 @@ static RPCHelpMan getblockheader() const CBlockIndex* tip; { LOCK(cs_main); - pblockindex = g_chainman.m_blockman.LookupBlockIndex(hash); - tip = ::ChainActive().Tip(); + ChainstateManager& chainman = EnsureChainman(request.context); + pblockindex = chainman.m_blockman.LookupBlockIndex(hash); + tip = chainman.ActiveChain().Tip(); } if (!pblockindex) { @@ -947,8 +949,9 @@ static RPCHelpMan getblock() const CBlockIndex* tip; { LOCK(cs_main); - pblockindex = g_chainman.m_blockman.LookupBlockIndex(hash); - tip = ::ChainActive().Tip(); + ChainstateManager& chainman = EnsureChainman(request.context); + pblockindex = chainman.m_blockman.LookupBlockIndex(hash); + tip = chainman.ActiveChain().Tip(); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); @@ -989,6 +992,7 @@ static RPCHelpMan pruneblockchain() throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode."); LOCK(cs_main); + ChainstateManager& chainman = EnsureChainman(request.context); int heightParam = request.params[0].get_int(); if (heightParam < 0) @@ -998,7 +1002,7 @@ static RPCHelpMan pruneblockchain() // 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, 0); + CBlockIndex* pindex = chainman.ActiveChain().FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW, 0); if (!pindex) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp."); } @@ -1006,7 +1010,7 @@ static RPCHelpMan pruneblockchain() } unsigned int height = (unsigned int) heightParam; - unsigned int chainHeight = (unsigned int) ::ChainActive().Height(); + unsigned int chainHeight = (unsigned int) chainman.ActiveChain().Height(); if (chainHeight < Params().PruneAfterHeight()) throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning."); else if (height > chainHeight) @@ -1016,8 +1020,8 @@ static RPCHelpMan pruneblockchain() height = chainHeight - MIN_BLOCKS_TO_KEEP; } - PruneBlockFilesManual(::ChainstateActive(), height); - const CBlockIndex* block = ::ChainActive().Tip(); + PruneBlockFilesManual(chainman.ActiveChainstate(), height); + const CBlockIndex* block = chainman.ActiveChain().Tip(); CHECK_NONFATAL(block); while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) { block = block->pprev; @@ -1070,13 +1074,20 @@ static RPCHelpMan gettxoutsetinfo() UniValue ret(UniValue::VOBJ); CCoinsStats stats; - ::ChainstateActive().ForceFlushStateToDisk(); + CChainState& active_chainstate = EnsureChainman(request.context).ActiveChainstate(); + active_chainstate.ForceFlushStateToDisk(); const CoinStatsHashType hash_type{request.params[0].isNull() ? CoinStatsHashType::HASH_SERIALIZED : ParseHashType(request.params[0].get_str())}; - CCoinsView* coins_view = WITH_LOCK(::cs_main, return &::ChainstateActive().CoinsDB()); + CCoinsView* coins_view; + BlockManager* blockman; + { + LOCK(::cs_main); + coins_view = &active_chainstate.CoinsDB(); + blockman = &active_chainstate.m_blockman; + } NodeContext& node = EnsureNodeContext(request.context); - if (GetUTXOStats(coins_view, WITH_LOCK(::cs_main, return std::ref(g_chainman.m_blockman)), stats, hash_type, node.rpc_interruption_point)) { + if (GetUTXOStats(coins_view, *blockman, stats, hash_type, node.rpc_interruption_point)) { ret.pushKV("height", (int64_t)stats.nHeight); ret.pushKV("bestblock", stats.hashBlock.GetHex()); ret.pushKV("transactions", (int64_t)stats.nTransactions); @@ -1147,7 +1158,8 @@ static RPCHelpMan gettxout() fMempool = request.params[2].get_bool(); Coin coin; - CCoinsViewCache* coins_view = &::ChainstateActive().CoinsTip(); + CChainState& active_chainstate = EnsureChainman(request.context).ActiveChainstate(); + CCoinsViewCache* coins_view = &active_chainstate.CoinsTip(); if (fMempool) { const CTxMemPool& mempool = EnsureMemPool(request.context); @@ -1162,7 +1174,7 @@ static RPCHelpMan gettxout() } } - const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(coins_view->GetBestBlock()); + const CBlockIndex* pindex = active_chainstate.m_blockman.LookupBlockIndex(coins_view->GetBestBlock()); ret.pushKV("bestblock", pindex->GetBlockHash().GetHex()); if (coin.nHeight == MEMPOOL_HEIGHT) { ret.pushKV("confirmations", 0); @@ -1202,12 +1214,13 @@ static RPCHelpMan verifychain() LOCK(cs_main); - return CVerifyDB().VerifyDB(Params(), ::ChainstateActive(), &::ChainstateActive().CoinsTip(), check_level, check_depth); + CChainState& active_chainstate = EnsureChainman(request.context).ActiveChainstate(); + return CVerifyDB().VerifyDB(Params(), active_chainstate, &active_chainstate.CoinsTip(), check_level, check_depth); }, }; } -static void BuriedForkDescPushBack(UniValue& softforks, const std::string &name, int height) EXCLUSIVE_LOCKS_REQUIRED(cs_main) +static void BuriedForkDescPushBack(UniValue& softforks, const std::string &name, int height, int active_tip_nheight) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { // For buried deployments. // A buried deployment is one where the height of the activation has been hardcoded into @@ -1220,12 +1233,12 @@ static void BuriedForkDescPushBack(UniValue& softforks, const std::string &name, rv.pushKV("type", "buried"); // getblockchaininfo reports the softfork as active from when the chain height is // one below the activation height - rv.pushKV("active", ::ChainActive().Tip()->nHeight + 1 >= height); + rv.pushKV("active", active_tip_nheight + 1 >= height); rv.pushKV("height", height); softforks.pushKV(name, rv); } -static void BIP9SoftForkDescPushBack(UniValue& softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) EXCLUSIVE_LOCKS_REQUIRED(cs_main) +static void BIP9SoftForkDescPushBack(const CBlockIndex* active_chain_tip, UniValue& softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { // For BIP9 deployments. // Deployments (e.g. testdummy) with timeout value before Jan 1, 2009 are hidden. @@ -1234,7 +1247,7 @@ static void BIP9SoftForkDescPushBack(UniValue& softforks, const std::string &nam if (consensusParams.vDeployments[id].nTimeout <= 1230768000) return; UniValue bip9(UniValue::VOBJ); - const ThresholdState thresholdState = VersionBitsState(::ChainActive().Tip(), consensusParams, id, versionbitscache); + const ThresholdState thresholdState = VersionBitsState(active_chain_tip, consensusParams, id, versionbitscache); switch (thresholdState) { case ThresholdState::DEFINED: bip9.pushKV("status", "defined"); break; case ThresholdState::STARTED: bip9.pushKV("status", "started"); break; @@ -1248,12 +1261,12 @@ static void BIP9SoftForkDescPushBack(UniValue& softforks, const std::string &nam } bip9.pushKV("start_time", consensusParams.vDeployments[id].nStartTime); bip9.pushKV("timeout", consensusParams.vDeployments[id].nTimeout); - int64_t since_height = VersionBitsStateSinceHeight(::ChainActive().Tip(), consensusParams, id, versionbitscache); + int64_t since_height = VersionBitsStateSinceHeight(active_chain_tip, consensusParams, id, versionbitscache); bip9.pushKV("since", since_height); if (ThresholdState::STARTED == thresholdState) { UniValue statsUV(UniValue::VOBJ); - BIP9Stats statsStruct = VersionBitsStatistics(::ChainActive().Tip(), consensusParams, id); + BIP9Stats statsStruct = VersionBitsStatistics(active_chain_tip, consensusParams, id); statsUV.pushKV("period", statsStruct.period); statsUV.pushKV("threshold", statsStruct.threshold); statsUV.pushKV("elapsed", statsStruct.elapsed); @@ -1329,17 +1342,20 @@ RPCHelpMan getblockchaininfo() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); + ChainstateManager& chainman = EnsureChainman(request.context); - const CBlockIndex* tip = ::ChainActive().Tip(); + const CBlockIndex* tip = chainman.ActiveChain().Tip(); + CHECK_NONFATAL(tip); + const int height = tip->nHeight; UniValue obj(UniValue::VOBJ); obj.pushKV("chain", Params().NetworkIDString()); - obj.pushKV("blocks", (int)::ChainActive().Height()); + obj.pushKV("blocks", (int)height); obj.pushKV("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1); obj.pushKV("bestblockhash", tip->GetBlockHash().GetHex()); obj.pushKV("difficulty", (double)GetDifficulty(tip)); obj.pushKV("mediantime", (int64_t)tip->GetMedianTimePast()); obj.pushKV("verificationprogress", GuessVerificationProgress(Params().TxData(), tip)); - obj.pushKV("initialblockdownload", ::ChainstateActive().IsInitialBlockDownload()); + obj.pushKV("initialblockdownload", chainman.ActiveChainstate().IsInitialBlockDownload()); obj.pushKV("chainwork", tip->nChainWork.GetHex()); obj.pushKV("size_on_disk", CalculateCurrentUsage()); obj.pushKV("pruned", fPruneMode); @@ -1362,13 +1378,13 @@ RPCHelpMan getblockchaininfo() const Consensus::Params& consensusParams = Params().GetConsensus(); UniValue softforks(UniValue::VOBJ); - BuriedForkDescPushBack(softforks, "bip34", consensusParams.BIP34Height); - BuriedForkDescPushBack(softforks, "bip66", consensusParams.BIP66Height); - BuriedForkDescPushBack(softforks, "bip65", consensusParams.BIP65Height); - BuriedForkDescPushBack(softforks, "csv", consensusParams.CSVHeight); - BuriedForkDescPushBack(softforks, "segwit", consensusParams.SegwitHeight); - BIP9SoftForkDescPushBack(softforks, "testdummy", consensusParams, Consensus::DEPLOYMENT_TESTDUMMY); - BIP9SoftForkDescPushBack(softforks, "taproot", consensusParams, Consensus::DEPLOYMENT_TAPROOT); + BuriedForkDescPushBack(softforks, "bip34", consensusParams.BIP34Height, height); + BuriedForkDescPushBack(softforks, "bip66", consensusParams.BIP66Height, height); + BuriedForkDescPushBack(softforks, "bip65", consensusParams.BIP65Height, height); + BuriedForkDescPushBack(softforks, "csv", consensusParams.CSVHeight, height); + BuriedForkDescPushBack(softforks, "segwit", consensusParams.SegwitHeight, height); + BIP9SoftForkDescPushBack(tip, softforks, "testdummy", consensusParams, Consensus::DEPLOYMENT_TESTDUMMY); + BIP9SoftForkDescPushBack(tip, softforks, "taproot", consensusParams, Consensus::DEPLOYMENT_TAPROOT); obj.pushKV("softforks", softforks); obj.pushKV("warnings", GetWarnings(false).original); @@ -1555,16 +1571,17 @@ static RPCHelpMan preciousblock() uint256 hash(ParseHashV(request.params[0], "blockhash")); CBlockIndex* pblockindex; + ChainstateManager& chainman = EnsureChainman(request.context); { LOCK(cs_main); - pblockindex = g_chainman.m_blockman.LookupBlockIndex(hash); + pblockindex = chainman.m_blockman.LookupBlockIndex(hash); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } } BlockValidationState state; - ::ChainstateActive().PreciousBlock(state, Params(), pblockindex); + chainman.ActiveChainstate().PreciousBlock(state, Params(), pblockindex); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.ToString()); @@ -1592,18 +1609,19 @@ static RPCHelpMan invalidateblock() uint256 hash(ParseHashV(request.params[0], "blockhash")); BlockValidationState state; + ChainstateManager& chainman = EnsureChainman(request.context); CBlockIndex* pblockindex; { LOCK(cs_main); - pblockindex = g_chainman.m_blockman.LookupBlockIndex(hash); + pblockindex = chainman.m_blockman.LookupBlockIndex(hash); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } } - ::ChainstateActive().InvalidateBlock(state, Params(), pblockindex); + chainman.ActiveChainstate().InvalidateBlock(state, Params(), pblockindex); if (state.IsValid()) { - ::ChainstateActive().ActivateBestChain(state, Params()); + chainman.ActiveChainstate().ActivateBestChain(state, Params()); } if (!state.IsValid()) { @@ -1630,20 +1648,21 @@ static RPCHelpMan reconsiderblock() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + ChainstateManager& chainman = EnsureChainman(request.context); uint256 hash(ParseHashV(request.params[0], "blockhash")); { LOCK(cs_main); - CBlockIndex* pblockindex = g_chainman.m_blockman.LookupBlockIndex(hash); + CBlockIndex* pblockindex = chainman.m_blockman.LookupBlockIndex(hash); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } - ::ChainstateActive().ResetBlockFailureFlags(pblockindex); + chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex); } BlockValidationState state; - ::ChainstateActive().ActivateBestChain(state, Params()); + chainman.ActiveChainstate().ActivateBestChain(state, Params()); if (!state.IsValid()) { throw JSONRPCError(RPC_DATABASE_ERROR, state.ToString()); @@ -1680,20 +1699,21 @@ static RPCHelpMan getchaintxstats() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + ChainstateManager& chainman = EnsureChainman(request.context); const CBlockIndex* pindex; int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month if (request.params[1].isNull()) { LOCK(cs_main); - pindex = ::ChainActive().Tip(); + pindex = chainman.ActiveChain().Tip(); } else { uint256 hash(ParseHashV(request.params[1], "blockhash")); LOCK(cs_main); - pindex = g_chainman.m_blockman.LookupBlockIndex(hash); + pindex = chainman.m_blockman.LookupBlockIndex(hash); if (!pindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } - if (!::ChainActive().Contains(pindex)) { + if (!chainman.ActiveChain().Contains(pindex)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Block is not in main chain"); } } @@ -1862,11 +1882,12 @@ static RPCHelpMan getblockstats() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); + ChainstateManager& chainman = EnsureChainman(request.context); 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 = chainman.ActiveChain().Height(); if (height < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height)); } @@ -1874,14 +1895,14 @@ static RPCHelpMan getblockstats() throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip)); } - pindex = ::ChainActive()[height]; + pindex = chainman.ActiveChain()[height]; } else { const uint256 hash(ParseHashV(request.params[0], "hash_or_height")); - pindex = g_chainman.m_blockman.LookupBlockIndex(hash); + pindex = chainman.m_blockman.LookupBlockIndex(hash); if (!pindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } - if (!::ChainActive().Contains(pindex)) { + if (!chainman.ActiveChain().Contains(pindex)) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Block is not in chain %s", Params().NetworkIDString())); } } @@ -2264,10 +2285,11 @@ static RPCHelpMan scantxoutset() CBlockIndex* tip; { LOCK(cs_main); - ::ChainstateActive().ForceFlushStateToDisk(); - pcursor = std::unique_ptr(::ChainstateActive().CoinsDB().Cursor()); + ChainstateManager& chainman = EnsureChainman(request.context); + chainman.ActiveChainstate().ForceFlushStateToDisk(); + pcursor = std::unique_ptr(chainman.ActiveChainstate().CoinsDB().Cursor()); CHECK_NONFATAL(pcursor); - tip = ::ChainActive().Tip(); + tip = chainman.ActiveChain().Tip(); CHECK_NONFATAL(tip); } NodeContext& node = EnsureNodeContext(request.context); @@ -2344,7 +2366,7 @@ static RPCHelpMan getblockfilter() bool block_was_connected; { LOCK(cs_main); - block_index = g_chainman.m_blockman.LookupBlockIndex(block_hash); + block_index = EnsureChainman(request.context).m_blockman.LookupBlockIndex(block_hash); if (!block_index) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } @@ -2465,7 +2487,7 @@ UniValue CreateUTXOSnapshot(NodeContext& node, CChainState& chainstate, CAutoFil } pcursor = std::unique_ptr(chainstate.CoinsDB().Cursor()); - tip = g_chainman.m_blockman.LookupBlockIndex(stats.hashBlock); + tip = chainstate.m_blockman.LookupBlockIndex(stats.hashBlock); CHECK_NONFATAL(tip); } -- cgit v1.2.3 From 60dc05afc6f6388c6f86729a0edd7cb69f1748e0 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Wed, 14 Oct 2020 15:57:17 -0400 Subject: rpc/mining: Use existing NodeContext Also pass in appropriate object to: - GetNetworkHashPS - [gG]enerateBlock{,s} Also: - Misc style/constness changes --- src/rpc/mining.cpp | 65 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 37 insertions(+), 28 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 2eddc731c3..5136a4e3de 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -44,11 +44,12 @@ * or from the last difficulty change if 'lookup' is nonpositive. * 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(); +static UniValue GetNetworkHashPS(int lookup, int height, const CChain& active_chain) { + const CBlockIndex* pb = active_chain.Tip(); - if (height >= 0 && height < ::ChainActive().Height()) - pb = ::ChainActive()[height]; + if (height >= 0 && height < active_chain.Height()) { + pb = active_chain[height]; + } if (pb == nullptr || !pb->nHeight) return 0; @@ -61,7 +62,7 @@ static UniValue GetNetworkHashPS(int lookup, int height) { if (lookup > pb->nHeight) lookup = pb->nHeight; - CBlockIndex *pb0 = pb; + const CBlockIndex* pb0 = pb; int64_t minTime = pb0->GetBlockTime(); int64_t maxTime = minTime; for (int i = 0; i < lookup; i++) { @@ -100,7 +101,8 @@ static RPCHelpMan getnetworkhashps() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1); + const CChain& active_chain = EnsureChainman(request.context).ActiveChain(); + return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1, active_chain); }, }; } @@ -111,7 +113,8 @@ static bool GenerateBlock(ChainstateManager& chainman, CBlock& block, uint64_t& { LOCK(cs_main); - IncrementExtraNonce(&block, ::ChainActive().Tip(), extra_nonce); + CHECK_NONFATAL(std::addressof(::ChainActive()) == std::addressof(chainman.ActiveChain())); + IncrementExtraNonce(&block, chainman.ActiveChain().Tip(), extra_nonce); } CChainParams chainparams(Params()); @@ -143,7 +146,8 @@ static UniValue generateBlocks(ChainstateManager& chainman, const CTxMemPool& me { // Don't keep cs_main locked LOCK(cs_main); - nHeight = ::ChainActive().Height(); + CHECK_NONFATAL(std::addressof(::ChainActive()) == std::addressof(chainman.ActiveChain())); + nHeight = chainman.ActiveChain().Height(); nHeightEnd = nHeight+nGenerate; } unsigned int nExtraNonce = 0; @@ -354,11 +358,12 @@ static RPCHelpMan generateblock() CChainParams chainparams(Params()); CBlock block; + ChainstateManager& chainman = EnsureChainman(request.context); { LOCK(cs_main); CTxMemPool empty_mempool; - std::unique_ptr blocktemplate(BlockAssembler(::ChainstateActive(), empty_mempool, chainparams).CreateNewBlock(coinbase_script)); + std::unique_ptr blocktemplate(BlockAssembler(chainman.ActiveChainstate(), empty_mempool, chainparams).CreateNewBlock(coinbase_script)); if (!blocktemplate) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Couldn't create new block"); } @@ -369,14 +374,14 @@ static RPCHelpMan generateblock() // Add transactions block.vtx.insert(block.vtx.end(), txs.begin(), txs.end()); - CBlockIndex* prev_block = WITH_LOCK(::cs_main, return g_chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock)); + CBlockIndex* prev_block = WITH_LOCK(::cs_main, return chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock)); RegenerateCommitments(block, prev_block); { LOCK(cs_main); BlockValidationState state; - if (!TestBlockValidity(state, chainparams, ::ChainstateActive(), block, g_chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), false, false)) { + if (!TestBlockValidity(state, chainparams, chainman.ActiveChainstate(), block, chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock), false, false)) { throw JSONRPCError(RPC_VERIFY_ERROR, strprintf("TestBlockValidity failed: %s", state.ToString())); } } @@ -385,7 +390,7 @@ static RPCHelpMan generateblock() uint64_t max_tries{DEFAULT_MAX_TRIES}; unsigned int extra_nonce{0}; - if (!GenerateBlock(EnsureChainman(request.context), block, max_tries, extra_nonce, block_hash) || block_hash.IsNull()) { + if (!GenerateBlock(chainman, block, max_tries, extra_nonce, block_hash) || block_hash.IsNull()) { throw JSONRPCError(RPC_MISC_ERROR, "Failed to make block."); } @@ -421,12 +426,13 @@ static RPCHelpMan getmininginfo() { LOCK(cs_main); const CTxMemPool& mempool = EnsureMemPool(request.context); + const CChain& active_chain = EnsureChainman(request.context).ActiveChain(); UniValue obj(UniValue::VOBJ); - obj.pushKV("blocks", (int)::ChainActive().Height()); + obj.pushKV("blocks", (int)active_chain.Height()); if (BlockAssembler::m_last_block_weight) obj.pushKV("currentblockweight", *BlockAssembler::m_last_block_weight); if (BlockAssembler::m_last_block_num_txs) obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs); - obj.pushKV("difficulty", (double)GetDifficulty(::ChainActive().Tip())); + obj.pushKV("difficulty", (double)GetDifficulty(active_chain.Tip())); obj.pushKV("networkhashps", getnetworkhashps().HandleRequest(request)); obj.pushKV("pooledtx", (uint64_t)mempool.size()); obj.pushKV("chain", Params().NetworkIDString()); @@ -590,6 +596,7 @@ static RPCHelpMan getblocktemplate() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); + ChainstateManager& chainman = EnsureChainman(request.context); std::string strMode = "template"; UniValue lpval = NullUniValue; @@ -620,7 +627,7 @@ static RPCHelpMan getblocktemplate() throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); uint256 hash = block.GetHash(); - const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(hash); + const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) return "duplicate"; @@ -629,12 +636,12 @@ static RPCHelpMan getblocktemplate() return "duplicate-inconclusive"; } - CBlockIndex* const pindexPrev = ::ChainActive().Tip(); + CBlockIndex* const pindexPrev = chainman.ActiveChain().Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; BlockValidationState state; - TestBlockValidity(state, Params(), ::ChainstateActive(), block, pindexPrev, false, true); + TestBlockValidity(state, Params(), chainman.ActiveChainstate(), block, pindexPrev, false, true); return BIP22ValidationResult(state); } @@ -665,7 +672,7 @@ static RPCHelpMan getblocktemplate() throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!"); } - if (::ChainstateActive().IsInitialBlockDownload()) { + if (chainman.ActiveChainstate().IsInitialBlockDownload()) { throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME " is in initial sync and waiting for blocks..."); } } @@ -691,7 +698,7 @@ static RPCHelpMan getblocktemplate() else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier - hashWatchedChain = ::ChainActive().Tip()->GetBlockHash(); + hashWatchedChain = chainman.ActiveChain().Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } @@ -736,7 +743,7 @@ static RPCHelpMan getblocktemplate() static CBlockIndex* pindexPrev; static int64_t nStart; static std::unique_ptr pblocktemplate; - if (pindexPrev != ::ChainActive().Tip() || + if (pindexPrev != chainman.ActiveChain().Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on @@ -744,12 +751,12 @@ static RPCHelpMan getblocktemplate() // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); - CBlockIndex* pindexPrevNew = ::ChainActive().Tip(); + CBlockIndex* pindexPrevNew = chainman.ActiveChain().Tip(); nStart = GetTime(); // Create new block CScript scriptDummy = CScript() << OP_TRUE; - pblocktemplate = BlockAssembler(::ChainstateActive(), mempool, Params()).CreateNewBlock(scriptDummy); + pblocktemplate = BlockAssembler(chainman.ActiveChainstate(), mempool, Params()).CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); @@ -885,7 +892,7 @@ static RPCHelpMan getblocktemplate() result.pushKV("transactions", transactions); result.pushKV("coinbaseaux", aux); result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue); - result.pushKV("longpollid", ::ChainActive().Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast)); + result.pushKV("longpollid", chainman.ActiveChain().Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast)); result.pushKV("target", hashTarget.GetHex()); result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1); result.pushKV("mutable", aMutable); @@ -968,10 +975,11 @@ static RPCHelpMan submitblock() throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase"); } + ChainstateManager& chainman = EnsureChainman(request.context); uint256 hash = block.GetHash(); { LOCK(cs_main); - const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(hash); + const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(hash); if (pindex) { if (pindex->IsValid(BLOCK_VALID_SCRIPTS)) { return "duplicate"; @@ -984,7 +992,7 @@ static RPCHelpMan submitblock() { LOCK(cs_main); - const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock); + const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(block.hashPrevBlock); if (pindex) { UpdateUncommittedBlockStructures(block, pindex, Params().GetConsensus()); } @@ -993,7 +1001,7 @@ static RPCHelpMan submitblock() bool new_block; auto sc = std::make_shared(block.GetHash()); RegisterSharedValidationInterface(sc); - bool accepted = EnsureChainman(request.context).ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block); + bool accepted = chainman.ProcessNewBlock(Params(), blockptr, /* fForceProcessing */ true, /* fNewBlock */ &new_block); UnregisterSharedValidationInterface(sc); if (!new_block && accepted) { return "duplicate"; @@ -1026,15 +1034,16 @@ static RPCHelpMan submitheader() if (!DecodeHexBlockHeader(h, request.params[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed"); } + ChainstateManager& chainman = EnsureChainman(request.context); { LOCK(cs_main); - if (!g_chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) { + if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) { throw JSONRPCError(RPC_VERIFY_ERROR, "Must submit previous header (" + h.hashPrevBlock.GetHex() + ") first"); } } BlockValidationState state; - EnsureChainman(request.context).ProcessNewBlockHeaders({h}, state, Params()); + chainman.ProcessNewBlockHeaders({h}, state, Params()); if (state.IsValid()) return NullUniValue; if (state.IsError()) { throw JSONRPCError(RPC_VERIFY_ERROR, state.ToString()); -- cgit v1.2.3 From 7be0671b950842fc3a17641a4a21501de0a800b5 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Wed, 14 Oct 2020 16:05:27 -0400 Subject: rpc/rawtx: Use existing NodeContext Also pass in appropriate object to: - TxToJSON --- src/rpc/rawtransaction.cpp | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 7932bd2915..0ed0af3493 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -40,7 +40,7 @@ #include -static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry) +static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry, CChainState& active_chainstate) { // Call into TxToUniv() in bitcoin-common to decode the transaction hex. // @@ -53,10 +53,10 @@ static void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& LOCK(cs_main); entry.pushKV("blockhash", hashBlock.GetHex()); - CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(hashBlock); + CBlockIndex* pindex = active_chainstate.m_blockman.LookupBlockIndex(hashBlock); if (pindex) { - if (::ChainActive().Contains(pindex)) { - entry.pushKV("confirmations", 1 + ::ChainActive().Height() - pindex->nHeight); + if (active_chainstate.m_chain.Contains(pindex)) { + entry.pushKV("confirmations", 1 + active_chainstate.m_chain.Height() - pindex->nHeight); entry.pushKV("time", pindex->GetBlockTime()); entry.pushKV("blocktime", pindex->GetBlockTime()); } @@ -158,6 +158,7 @@ static RPCHelpMan getrawtransaction() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const NodeContext& node = EnsureNodeContext(request.context); + ChainstateManager& chainman = EnsureChainman(request.context); bool in_active_chain = true; uint256 hash = ParseHashV(request.params[0], "parameter 1"); @@ -178,11 +179,11 @@ static RPCHelpMan getrawtransaction() LOCK(cs_main); uint256 blockhash = ParseHashV(request.params[2], "parameter 3"); - blockindex = g_chainman.m_blockman.LookupBlockIndex(blockhash); + blockindex = chainman.m_blockman.LookupBlockIndex(blockhash); if (!blockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block hash not found"); } - in_active_chain = ::ChainActive().Contains(blockindex); + in_active_chain = chainman.ActiveChain().Contains(blockindex); } bool f_txindex_ready = false; @@ -215,7 +216,7 @@ static RPCHelpMan getrawtransaction() UniValue result(UniValue::VOBJ); if (blockindex) result.pushKV("in_active_chain", in_active_chain); - TxToJSON(*tx, hash_block, result); + TxToJSON(*tx, hash_block, result, chainman.ActiveChainstate()); return result; }, }; @@ -257,10 +258,11 @@ static RPCHelpMan gettxoutproof() CBlockIndex* pblockindex = nullptr; uint256 hashBlock; + ChainstateManager& chainman = EnsureChainman(request.context); if (!request.params[1].isNull()) { LOCK(cs_main); hashBlock = ParseHashV(request.params[1], "blockhash"); - pblockindex = g_chainman.m_blockman.LookupBlockIndex(hashBlock); + pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock); if (!pblockindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } @@ -269,9 +271,9 @@ static RPCHelpMan gettxoutproof() // Loop through txids and try to find which block they're in. Exit loop once a block is found. for (const auto& tx : setTxids) { - const Coin& coin = AccessByTxid(::ChainstateActive().CoinsTip(), tx); + const Coin& coin = AccessByTxid(chainman.ActiveChainstate().CoinsTip(), tx); if (!coin.IsSpent()) { - pblockindex = ::ChainActive()[coin.nHeight]; + pblockindex = chainman.ActiveChain()[coin.nHeight]; break; } } @@ -290,7 +292,7 @@ static RPCHelpMan gettxoutproof() if (!tx || hashBlock.IsNull()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not yet in block"); } - pblockindex = g_chainman.m_blockman.LookupBlockIndex(hashBlock); + pblockindex = chainman.m_blockman.LookupBlockIndex(hashBlock); if (!pblockindex) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Transaction index corrupt"); } @@ -350,8 +352,9 @@ static RPCHelpMan verifytxoutproof() LOCK(cs_main); - const CBlockIndex* pindex = g_chainman.m_blockman.LookupBlockIndex(merkleBlock.header.GetHash()); - if (!pindex || !::ChainActive().Contains(pindex) || pindex->nTx == 0) { + ChainstateManager& chainman = EnsureChainman(request.context); + const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(merkleBlock.header.GetHash()); + if (!pindex || !chainman.ActiveChain().Contains(pindex) || pindex->nTx == 0) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); } @@ -678,7 +681,7 @@ static RPCHelpMan combinerawtransaction() const CTxMemPool& mempool = EnsureMemPool(request.context); LOCK(cs_main); LOCK(mempool.cs); - CCoinsViewCache &viewChain = ::ChainstateActive().CoinsTip(); + CCoinsViewCache &viewChain = EnsureChainman(request.context).ActiveChainstate().CoinsTip(); CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view @@ -949,7 +952,7 @@ static RPCHelpMan testmempoolaccept() result_0.pushKV("txid", tx->GetHash().GetHex()); result_0.pushKV("wtxid", tx->GetWitnessHash().GetHex()); - const MempoolAcceptResult accept_result = WITH_LOCK(cs_main, return AcceptToMemoryPool(::ChainstateActive(), mempool, std::move(tx), + const MempoolAcceptResult accept_result = WITH_LOCK(cs_main, return AcceptToMemoryPool(EnsureChainman(request.context).ActiveChainstate(), mempool, std::move(tx), false /* bypass_limits */, /* test_accept */ true)); // Only return the fee and vsize if the transaction would pass ATMP. @@ -1600,7 +1603,7 @@ static RPCHelpMan utxoupdatepsbt() { const CTxMemPool& mempool = EnsureMemPool(request.context); LOCK2(cs_main, mempool.cs); - CCoinsViewCache &viewChain = ::ChainstateActive().CoinsTip(); + CCoinsViewCache &viewChain = EnsureChainman(request.context).ActiveChainstate().CoinsTip(); CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view -- cgit v1.2.3 From 306b1cd3eeb2502904ed4698646d2c86d028aad2 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Mon, 12 Apr 2021 18:25:13 -0400 Subject: rpc: Add alt Ensure* functions acepting NodeContext --- src/rpc/blockchain.cpp | 24 ++++++++++++++++++------ src/rpc/blockchain.h | 3 +++ 2 files changed, 21 insertions(+), 6 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index ffabca0aff..cc7a29ffdb 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -64,18 +64,21 @@ NodeContext& EnsureNodeContext(const std::any& context) return *node_context; } -CTxMemPool& EnsureMemPool(const std::any& context) +CTxMemPool& EnsureMemPool(const NodeContext& node) { - const NodeContext& node = EnsureNodeContext(context); if (!node.mempool) { throw JSONRPCError(RPC_CLIENT_MEMPOOL_DISABLED, "Mempool disabled or instance not found"); } return *node.mempool; } -ChainstateManager& EnsureChainman(const std::any& context) +CTxMemPool& EnsureMemPool(const std::any& context) +{ + return EnsureMemPool(EnsureNodeContext(context)); +} + +ChainstateManager& EnsureChainman(const NodeContext& node) { - const NodeContext& node = EnsureNodeContext(context); if (!node.chainman) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Node chainman not found"); } @@ -83,15 +86,24 @@ ChainstateManager& EnsureChainman(const std::any& context) return *node.chainman; } -CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& context) +ChainstateManager& EnsureChainman(const std::any& context) +{ + return EnsureChainman(EnsureNodeContext(context)); +} + +CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node) { - NodeContext& node = EnsureNodeContext(context); if (!node.fee_estimator) { throw JSONRPCError(RPC_INTERNAL_ERROR, "Fee estimation disabled"); } return *node.fee_estimator; } +CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& context) +{ + return EnsureFeeEstimator(EnsureNodeContext(context)); +} + /* Calculate the difficulty for a given block index. */ double GetDifficulty(const CBlockIndex* blockindex) diff --git a/src/rpc/blockchain.h b/src/rpc/blockchain.h index cd04c9a10f..17c7060761 100644 --- a/src/rpc/blockchain.h +++ b/src/rpc/blockchain.h @@ -57,8 +57,11 @@ void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fInclud void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, int serialize_flags = 0, const CTxUndo* txundo = nullptr); NodeContext& EnsureNodeContext(const std::any& context); +CTxMemPool& EnsureMemPool(const NodeContext& node); CTxMemPool& EnsureMemPool(const std::any& context); +ChainstateManager& EnsureChainman(const NodeContext& node); ChainstateManager& EnsureChainman(const std::any& context); +CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node); CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& context); /** -- cgit v1.2.3 From 1570c7ee98612366df031bebef9e0468fb57b8a2 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Wed, 14 Apr 2021 10:16:34 -0400 Subject: rpc: Add renamed EnsureAny*() functions - The original Ensure*(const std::any& context) functions are kept and the parameter renamed to ctx so that the scripted-diff in the subsequent commit will work as expected - The renaming avoids overloading mistakes arising out of the untyped std::any argument. --- src/rpc/blockchain.cpp | 24 ++++++++++++++++++++---- src/rpc/blockchain.h | 4 ++++ 2 files changed, 24 insertions(+), 4 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index cc7a29ffdb..074f3e3924 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -55,7 +55,11 @@ static Mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange); -NodeContext& EnsureNodeContext(const std::any& context) +NodeContext& EnsureNodeContext(const std::any& ctx) { + return EnsureAnyNodeContext(ctx); +} + +NodeContext& EnsureAnyNodeContext(const std::any& context) { auto node_context = util::AnyPtr(context); if (!node_context) { @@ -64,6 +68,10 @@ NodeContext& EnsureNodeContext(const std::any& context) return *node_context; } +CTxMemPool& EnsureMemPool(const std::any& ctx) { + return EnsureAnyMemPool(ctx); +} + CTxMemPool& EnsureMemPool(const NodeContext& node) { if (!node.mempool) { @@ -72,11 +80,15 @@ CTxMemPool& EnsureMemPool(const NodeContext& node) return *node.mempool; } -CTxMemPool& EnsureMemPool(const std::any& context) +CTxMemPool& EnsureAnyMemPool(const std::any& context) { return EnsureMemPool(EnsureNodeContext(context)); } +ChainstateManager& EnsureChainman(const std::any& ctx) { + return EnsureAnyChainman(ctx); +} + ChainstateManager& EnsureChainman(const NodeContext& node) { if (!node.chainman) { @@ -86,11 +98,15 @@ ChainstateManager& EnsureChainman(const NodeContext& node) return *node.chainman; } -ChainstateManager& EnsureChainman(const std::any& context) +ChainstateManager& EnsureAnyChainman(const std::any& context) { return EnsureChainman(EnsureNodeContext(context)); } +CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& ctx) { + return EnsureAnyFeeEstimator(ctx); +} + CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node) { if (!node.fee_estimator) { @@ -99,7 +115,7 @@ CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node) return *node.fee_estimator; } -CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& context) +CBlockPolicyEstimator& EnsureAnyFeeEstimator(const std::any& context) { return EnsureFeeEstimator(EnsureNodeContext(context)); } diff --git a/src/rpc/blockchain.h b/src/rpc/blockchain.h index 17c7060761..3ac15c869d 100644 --- a/src/rpc/blockchain.h +++ b/src/rpc/blockchain.h @@ -57,12 +57,16 @@ void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fInclud void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, int serialize_flags = 0, const CTxUndo* txundo = nullptr); NodeContext& EnsureNodeContext(const std::any& context); +NodeContext& EnsureAnyNodeContext(const std::any& context); CTxMemPool& EnsureMemPool(const NodeContext& node); CTxMemPool& EnsureMemPool(const std::any& context); +CTxMemPool& EnsureAnyMemPool(const std::any& context); ChainstateManager& EnsureChainman(const NodeContext& node); ChainstateManager& EnsureChainman(const std::any& context); +ChainstateManager& EnsureAnyChainman(const std::any& context); CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node); CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& context); +CBlockPolicyEstimator& EnsureAnyFeeEstimator(const std::any& context); /** * Helper to create UTXO snapshots given a chainstate and a file handle. -- cgit v1.2.3 From 6fb65b49f4d393b091479be5a5df5a0a160cf986 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Tue, 13 Apr 2021 17:04:43 -0400 Subject: scripted-diff: rest/rpc: Use renamed EnsureAny*() -BEGIN VERIFY SCRIPT- sed -i -E 's@Ensure([^(]+)(\((request\.|)context\))@EnsureAny\1\2@g' \ -- src/rest.cpp src/rpc/*.cpp -END VERIFY SCRIPT- --- src/rpc/blockchain.cpp | 64 +++++++++++++++++++++++----------------------- src/rpc/mining.cpp | 34 ++++++++++++------------ src/rpc/net.cpp | 30 +++++++++++----------- src/rpc/rawtransaction.cpp | 24 ++++++++--------- 4 files changed, 76 insertions(+), 76 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 074f3e3924..9bf03f24b5 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -82,7 +82,7 @@ CTxMemPool& EnsureMemPool(const NodeContext& node) CTxMemPool& EnsureAnyMemPool(const std::any& context) { - return EnsureMemPool(EnsureNodeContext(context)); + return EnsureMemPool(EnsureAnyNodeContext(context)); } ChainstateManager& EnsureChainman(const std::any& ctx) { @@ -100,7 +100,7 @@ ChainstateManager& EnsureChainman(const NodeContext& node) ChainstateManager& EnsureAnyChainman(const std::any& context) { - return EnsureChainman(EnsureNodeContext(context)); + return EnsureChainman(EnsureAnyNodeContext(context)); } CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& ctx) { @@ -117,7 +117,7 @@ CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node) CBlockPolicyEstimator& EnsureAnyFeeEstimator(const std::any& context) { - return EnsureFeeEstimator(EnsureNodeContext(context)); + return EnsureFeeEstimator(EnsureAnyNodeContext(context)); } /* Calculate the difficulty for a given block index. @@ -227,7 +227,7 @@ static RPCHelpMan getblockcount() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - return EnsureChainman(request.context).ActiveChain().Height(); + return EnsureAnyChainman(request.context).ActiveChain().Height(); }, }; } @@ -246,7 +246,7 @@ static RPCHelpMan getbestblockhash() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - return EnsureChainman(request.context).ActiveChain().Tip()->GetBlockHash().GetHex(); + return EnsureAnyChainman(request.context).ActiveChain().Tip()->GetBlockHash().GetHex(); }, }; } @@ -427,7 +427,7 @@ static RPCHelpMan getdifficulty() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - return GetDifficulty(EnsureChainman(request.context).ActiveChain().Tip()); + return GetDifficulty(EnsureAnyChainman(request.context).ActiveChain().Tip()); }, }; } @@ -609,7 +609,7 @@ static RPCHelpMan getrawmempool() include_mempool_sequence = request.params[1].get_bool(); } - return MempoolToJSON(EnsureMemPool(request.context), fVerbose, include_mempool_sequence); + return MempoolToJSON(EnsureAnyMemPool(request.context), fVerbose, include_mempool_sequence); }, }; } @@ -644,7 +644,7 @@ static RPCHelpMan getmempoolancestors() uint256 hash = ParseHashV(request.params[0], "parameter 1"); - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); @@ -708,7 +708,7 @@ static RPCHelpMan getmempooldescendants() uint256 hash = ParseHashV(request.params[0], "parameter 1"); - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); @@ -760,7 +760,7 @@ static RPCHelpMan getmempoolentry() { uint256 hash = ParseHashV(request.params[0], "parameter 1"); - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); LOCK(mempool.cs); CTxMemPool::txiter it = mempool.mapTx.find(hash); @@ -792,7 +792,7 @@ static RPCHelpMan getblockhash() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - const CChain& active_chain = EnsureChainman(request.context).ActiveChain(); + const CChain& active_chain = EnsureAnyChainman(request.context).ActiveChain(); int nHeight = request.params[0].get_int(); if (nHeight < 0 || nHeight > active_chain.Height()) @@ -852,7 +852,7 @@ static RPCHelpMan getblockheader() const CBlockIndex* tip; { LOCK(cs_main); - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); pblockindex = chainman.m_blockman.LookupBlockIndex(hash); tip = chainman.ActiveChain().Tip(); } @@ -977,7 +977,7 @@ static RPCHelpMan getblock() const CBlockIndex* tip; { LOCK(cs_main); - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); pblockindex = chainman.m_blockman.LookupBlockIndex(hash); tip = chainman.ActiveChain().Tip(); @@ -1020,7 +1020,7 @@ static RPCHelpMan pruneblockchain() throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode."); LOCK(cs_main); - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); int heightParam = request.params[0].get_int(); if (heightParam < 0) @@ -1102,7 +1102,7 @@ static RPCHelpMan gettxoutsetinfo() UniValue ret(UniValue::VOBJ); CCoinsStats stats; - CChainState& active_chainstate = EnsureChainman(request.context).ActiveChainstate(); + CChainState& active_chainstate = EnsureAnyChainman(request.context).ActiveChainstate(); active_chainstate.ForceFlushStateToDisk(); const CoinStatsHashType hash_type{request.params[0].isNull() ? CoinStatsHashType::HASH_SERIALIZED : ParseHashType(request.params[0].get_str())}; @@ -1114,7 +1114,7 @@ static RPCHelpMan gettxoutsetinfo() coins_view = &active_chainstate.CoinsDB(); blockman = &active_chainstate.m_blockman; } - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (GetUTXOStats(coins_view, *blockman, stats, hash_type, node.rpc_interruption_point)) { ret.pushKV("height", (int64_t)stats.nHeight); ret.pushKV("bestblock", stats.hashBlock.GetHex()); @@ -1186,11 +1186,11 @@ static RPCHelpMan gettxout() fMempool = request.params[2].get_bool(); Coin coin; - CChainState& active_chainstate = EnsureChainman(request.context).ActiveChainstate(); + CChainState& active_chainstate = EnsureAnyChainman(request.context).ActiveChainstate(); CCoinsViewCache* coins_view = &active_chainstate.CoinsTip(); if (fMempool) { - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); LOCK(mempool.cs); CCoinsViewMemPool view(coins_view, mempool); if (!view.GetCoin(out, coin) || mempool.isSpent(out)) { @@ -1242,7 +1242,7 @@ static RPCHelpMan verifychain() LOCK(cs_main); - CChainState& active_chainstate = EnsureChainman(request.context).ActiveChainstate(); + CChainState& active_chainstate = EnsureAnyChainman(request.context).ActiveChainstate(); return CVerifyDB().VerifyDB(Params(), active_chainstate, &active_chainstate.CoinsTip(), check_level, check_depth); }, }; @@ -1370,7 +1370,7 @@ RPCHelpMan getblockchaininfo() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); const CBlockIndex* tip = chainman.ActiveChain().Tip(); CHECK_NONFATAL(tip); @@ -1463,7 +1463,7 @@ static RPCHelpMan getchaintips() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); /* @@ -1575,7 +1575,7 @@ static RPCHelpMan getmempoolinfo() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - return MempoolInfoToJSON(EnsureMemPool(request.context)); + return MempoolInfoToJSON(EnsureAnyMemPool(request.context)); }, }; } @@ -1599,7 +1599,7 @@ static RPCHelpMan preciousblock() uint256 hash(ParseHashV(request.params[0], "blockhash")); CBlockIndex* pblockindex; - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); { LOCK(cs_main); pblockindex = chainman.m_blockman.LookupBlockIndex(hash); @@ -1637,7 +1637,7 @@ static RPCHelpMan invalidateblock() uint256 hash(ParseHashV(request.params[0], "blockhash")); BlockValidationState state; - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); CBlockIndex* pblockindex; { LOCK(cs_main); @@ -1676,7 +1676,7 @@ static RPCHelpMan reconsiderblock() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); uint256 hash(ParseHashV(request.params[0], "blockhash")); { @@ -1727,7 +1727,7 @@ static RPCHelpMan getchaintxstats() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); const CBlockIndex* pindex; int blockcount = 30 * 24 * 60 * 60 / Params().GetConsensus().nPowTargetSpacing; // By default: 1 month @@ -1910,7 +1910,7 @@ static RPCHelpMan getblockstats() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); CBlockIndex* pindex; if (request.params[0].isNum()) { @@ -2121,7 +2121,7 @@ static RPCHelpMan savemempool() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); if (!mempool.IsLoaded()) { throw JSONRPCError(RPC_MISC_ERROR, "The mempool was not loaded yet"); @@ -2313,14 +2313,14 @@ static RPCHelpMan scantxoutset() CBlockIndex* tip; { LOCK(cs_main); - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); chainman.ActiveChainstate().ForceFlushStateToDisk(); pcursor = std::unique_ptr(chainman.ActiveChainstate().CoinsDB().Cursor()); CHECK_NONFATAL(pcursor); tip = chainman.ActiveChain().Tip(); CHECK_NONFATAL(tip); } - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); bool res = FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins, node.rpc_interruption_point); result.pushKV("success", res); result.pushKV("txouts", count); @@ -2394,7 +2394,7 @@ static RPCHelpMan getblockfilter() bool block_was_connected; { LOCK(cs_main); - block_index = EnsureChainman(request.context).m_blockman.LookupBlockIndex(block_hash); + block_index = EnsureAnyChainman(request.context).m_blockman.LookupBlockIndex(block_hash); if (!block_index) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } @@ -2477,7 +2477,7 @@ static RPCHelpMan dumptxoutset() FILE* file{fsbridge::fopen(temppath, "wb")}; CAutoFile afile{file, SER_DISK, CLIENT_VERSION}; - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); UniValue result = CreateUTXOSnapshot(node, node.chainman->ActiveChainstate(), afile); fs::rename(temppath, path); diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 5136a4e3de..f72a19a8a1 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -101,7 +101,7 @@ static RPCHelpMan getnetworkhashps() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - const CChain& active_chain = EnsureChainman(request.context).ActiveChain(); + const CChain& active_chain = EnsureAnyChainman(request.context).ActiveChain(); return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1, active_chain); }, }; @@ -235,8 +235,8 @@ static RPCHelpMan generatetodescriptor() throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } - const CTxMemPool& mempool = EnsureMemPool(request.context); - ChainstateManager& chainman = EnsureChainman(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries); }, @@ -280,8 +280,8 @@ static RPCHelpMan generatetoaddress() throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address"); } - const CTxMemPool& mempool = EnsureMemPool(request.context); - ChainstateManager& chainman = EnsureChainman(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); CScript coinbase_script = GetScriptForDestination(destination); @@ -329,7 +329,7 @@ static RPCHelpMan generateblock() coinbase_script = GetScriptForDestination(destination); } - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); std::vector txs; const auto raw_txs_or_txids = request.params[1].get_array(); @@ -358,7 +358,7 @@ static RPCHelpMan generateblock() CChainParams chainparams(Params()); CBlock block; - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); { LOCK(cs_main); @@ -425,8 +425,8 @@ static RPCHelpMan getmininginfo() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - const CTxMemPool& mempool = EnsureMemPool(request.context); - const CChain& active_chain = EnsureChainman(request.context).ActiveChain(); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); + const CChain& active_chain = EnsureAnyChainman(request.context).ActiveChain(); UniValue obj(UniValue::VOBJ); obj.pushKV("blocks", (int)active_chain.Height()); @@ -474,7 +474,7 @@ static RPCHelpMan prioritisetransaction() throw JSONRPCError(RPC_INVALID_PARAMETER, "Priority is no longer supported, dummy argument to prioritisetransaction must be 0."); } - EnsureMemPool(request.context).PrioritiseTransaction(hash, nAmount); + EnsureAnyMemPool(request.context).PrioritiseTransaction(hash, nAmount); return true; }, }; @@ -596,7 +596,7 @@ static RPCHelpMan getblocktemplate() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { LOCK(cs_main); - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); std::string strMode = "template"; UniValue lpval = NullUniValue; @@ -663,7 +663,7 @@ static RPCHelpMan getblocktemplate() if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); @@ -678,7 +678,7 @@ static RPCHelpMan getblocktemplate() } static unsigned int nTransactionsUpdatedLast; - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); if (!lpval.isNull()) { @@ -975,7 +975,7 @@ static RPCHelpMan submitblock() throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block does not start with a coinbase"); } - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); uint256 hash = block.GetHash(); { LOCK(cs_main); @@ -1034,7 +1034,7 @@ static RPCHelpMan submitheader() if (!DecodeHexBlockHeader(h, request.params[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block header decode failed"); } - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); { LOCK(cs_main); if (!chainman.m_blockman.LookupBlockIndex(h.hashPrevBlock)) { @@ -1092,7 +1092,7 @@ static RPCHelpMan estimatesmartfee() RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VSTR}); RPCTypeCheckArgument(request.params[0], UniValue::VNUM); - CBlockPolicyEstimator& fee_estimator = EnsureFeeEstimator(request.context); + CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context); unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE); unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target); @@ -1180,7 +1180,7 @@ static RPCHelpMan estimaterawfee() RPCTypeCheck(request.params, {UniValue::VNUM, UniValue::VNUM}, true); RPCTypeCheckArgument(request.params[0], UniValue::VNUM); - CBlockPolicyEstimator& fee_estimator = EnsureFeeEstimator(request.context); + CBlockPolicyEstimator& fee_estimator = EnsureAnyFeeEstimator(request.context); unsigned int max_target = fee_estimator.HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE); unsigned int conf_target = ParseConfirmTarget(request.params[0], max_target); diff --git a/src/rpc/net.cpp b/src/rpc/net.cpp index 96533a50c8..cd354f46c2 100644 --- a/src/rpc/net.cpp +++ b/src/rpc/net.cpp @@ -53,7 +53,7 @@ static RPCHelpMan getconnectioncount() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); @@ -76,7 +76,7 @@ static RPCHelpMan ping() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (!node.peerman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); } @@ -165,7 +165,7 @@ static RPCHelpMan getpeerinfo() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.connman || !node.peerman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); } @@ -285,7 +285,7 @@ static RPCHelpMan addnode() self.ToString()); } - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); @@ -350,7 +350,7 @@ static RPCHelpMan addconnection() throw JSONRPCError(RPC_INVALID_PARAMETER, self.ToString()); } - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (!node.connman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled."); } @@ -388,7 +388,7 @@ static RPCHelpMan disconnectnode() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); @@ -448,7 +448,7 @@ static RPCHelpMan getaddednodeinfo() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); @@ -519,7 +519,7 @@ static RPCHelpMan getnettotals() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); @@ -618,7 +618,7 @@ static RPCHelpMan getnetworkinfo() obj.pushKV("version", CLIENT_VERSION); obj.pushKV("subversion", strSubVersion); obj.pushKV("protocolversion",PROTOCOL_VERSION); - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (node.connman) { ServiceFlags services = node.connman->GetLocalServices(); obj.pushKV("localservices", strprintf("%016x", services)); @@ -680,7 +680,7 @@ static RPCHelpMan setban() if (strCommand != "add" && strCommand != "remove") { throw std::runtime_error(help.ToString()); } - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (!node.banman) { throw JSONRPCError(RPC_DATABASE_ERROR, "Error: Ban database not loaded"); } @@ -760,7 +760,7 @@ static RPCHelpMan listbanned() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.banman) { throw JSONRPCError(RPC_DATABASE_ERROR, "Error: Ban database not loaded"); } @@ -797,7 +797,7 @@ static RPCHelpMan clearbanned() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (!node.banman) { throw JSONRPCError(RPC_DATABASE_ERROR, "Error: Ban database not loaded"); } @@ -820,7 +820,7 @@ static RPCHelpMan setnetworkactive() RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (!node.connman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); } @@ -857,7 +857,7 @@ static RPCHelpMan getnodeaddresses() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (!node.connman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); } @@ -906,7 +906,7 @@ static RPCHelpMan addpeeraddress() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); if (!node.addrman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Address manager functionality missing or disabled"); } diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 0ed0af3493..3e6edde41a 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -157,8 +157,8 @@ static RPCHelpMan getrawtransaction() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - const NodeContext& node = EnsureNodeContext(request.context); - ChainstateManager& chainman = EnsureChainman(request.context); + const NodeContext& node = EnsureAnyNodeContext(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); bool in_active_chain = true; uint256 hash = ParseHashV(request.params[0], "parameter 1"); @@ -258,7 +258,7 @@ static RPCHelpMan gettxoutproof() CBlockIndex* pblockindex = nullptr; uint256 hashBlock; - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); if (!request.params[1].isNull()) { LOCK(cs_main); hashBlock = ParseHashV(request.params[1], "blockhash"); @@ -352,7 +352,7 @@ static RPCHelpMan verifytxoutproof() LOCK(cs_main); - ChainstateManager& chainman = EnsureChainman(request.context); + ChainstateManager& chainman = EnsureAnyChainman(request.context); const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(merkleBlock.header.GetHash()); if (!pindex || !chainman.ActiveChain().Contains(pindex) || pindex->nTx == 0) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); @@ -678,10 +678,10 @@ static RPCHelpMan combinerawtransaction() CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); LOCK(cs_main); LOCK(mempool.cs); - CCoinsViewCache &viewChain = EnsureChainman(request.context).ActiveChainstate().CoinsTip(); + CCoinsViewCache &viewChain = EnsureAnyChainman(request.context).ActiveChainstate().CoinsTip(); CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view @@ -805,7 +805,7 @@ static RPCHelpMan signrawtransactionwithkey() for (const CTxIn& txin : mtx.vin) { coins[txin.prevout]; // Create empty map entry keyed by prevout. } - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); FindCoins(node, coins); // Parse the prevtxs array @@ -868,7 +868,7 @@ static RPCHelpMan sendrawtransaction() std::string err_string; AssertLockNotHeld(cs_main); - NodeContext& node = EnsureNodeContext(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); const TransactionError err = BroadcastTransaction(node, tx, err_string, max_raw_tx_fee, /*relay*/ true, /*wait_callback*/ true); if (TransactionError::OK != err) { throw JSONRPCTransactionError(err, err_string); @@ -943,7 +943,7 @@ static RPCHelpMan testmempoolaccept() DEFAULT_MAX_RAW_TX_FEE_RATE : CFeeRate(AmountFromValue(request.params[1])); - CTxMemPool& mempool = EnsureMemPool(request.context); + CTxMemPool& mempool = EnsureAnyMemPool(request.context); int64_t virtual_size = GetVirtualTransactionSize(*tx); CAmount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size); @@ -952,7 +952,7 @@ static RPCHelpMan testmempoolaccept() result_0.pushKV("txid", tx->GetHash().GetHex()); result_0.pushKV("wtxid", tx->GetWitnessHash().GetHex()); - const MempoolAcceptResult accept_result = WITH_LOCK(cs_main, return AcceptToMemoryPool(EnsureChainman(request.context).ActiveChainstate(), mempool, std::move(tx), + const MempoolAcceptResult accept_result = WITH_LOCK(cs_main, return AcceptToMemoryPool(EnsureAnyChainman(request.context).ActiveChainstate(), mempool, std::move(tx), false /* bypass_limits */, /* test_accept */ true)); // Only return the fee and vsize if the transaction would pass ATMP. @@ -1601,9 +1601,9 @@ static RPCHelpMan utxoupdatepsbt() CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { - const CTxMemPool& mempool = EnsureMemPool(request.context); + const CTxMemPool& mempool = EnsureAnyMemPool(request.context); LOCK2(cs_main, mempool.cs); - CCoinsViewCache &viewChain = EnsureChainman(request.context).ActiveChainstate().CoinsTip(); + CCoinsViewCache &viewChain = EnsureAnyChainman(request.context).ActiveChainstate().CoinsTip(); CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view -- cgit v1.2.3 From 038854f31e3511e8bb6e163305cab0a96783d25b Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Wed, 14 Apr 2021 10:34:50 -0400 Subject: rest/rpc: Remove now-unused old Ensure functions The scripted-diff in the previous commit should have removed all calls to functions like: Ensure(?!Any)\(const std::any& (context|ctx)\), so we can remove them now. --- src/rpc/blockchain.cpp | 16 ---------------- src/rpc/blockchain.h | 4 ---- 2 files changed, 20 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 9bf03f24b5..19df2d8031 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -55,10 +55,6 @@ static Mutex cs_blockchange; static std::condition_variable cond_blockchange; static CUpdatedBlock latestblock GUARDED_BY(cs_blockchange); -NodeContext& EnsureNodeContext(const std::any& ctx) { - return EnsureAnyNodeContext(ctx); -} - NodeContext& EnsureAnyNodeContext(const std::any& context) { auto node_context = util::AnyPtr(context); @@ -68,10 +64,6 @@ NodeContext& EnsureAnyNodeContext(const std::any& context) return *node_context; } -CTxMemPool& EnsureMemPool(const std::any& ctx) { - return EnsureAnyMemPool(ctx); -} - CTxMemPool& EnsureMemPool(const NodeContext& node) { if (!node.mempool) { @@ -85,10 +77,6 @@ CTxMemPool& EnsureAnyMemPool(const std::any& context) return EnsureMemPool(EnsureAnyNodeContext(context)); } -ChainstateManager& EnsureChainman(const std::any& ctx) { - return EnsureAnyChainman(ctx); -} - ChainstateManager& EnsureChainman(const NodeContext& node) { if (!node.chainman) { @@ -103,10 +91,6 @@ ChainstateManager& EnsureAnyChainman(const std::any& context) return EnsureChainman(EnsureAnyNodeContext(context)); } -CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& ctx) { - return EnsureAnyFeeEstimator(ctx); -} - CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node) { if (!node.fee_estimator) { diff --git a/src/rpc/blockchain.h b/src/rpc/blockchain.h index 3ac15c869d..ffb6f03b47 100644 --- a/src/rpc/blockchain.h +++ b/src/rpc/blockchain.h @@ -56,16 +56,12 @@ void CalculatePercentilesByWeight(CAmount result[NUM_GETBLOCKSTATS_PERCENTILES], void ScriptPubKeyToUniv(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex); void TxToUniv(const CTransaction& tx, const uint256& hashBlock, UniValue& entry, bool include_hex = true, int serialize_flags = 0, const CTxUndo* txundo = nullptr); -NodeContext& EnsureNodeContext(const std::any& context); NodeContext& EnsureAnyNodeContext(const std::any& context); CTxMemPool& EnsureMemPool(const NodeContext& node); -CTxMemPool& EnsureMemPool(const std::any& context); CTxMemPool& EnsureAnyMemPool(const std::any& context); ChainstateManager& EnsureChainman(const NodeContext& node); -ChainstateManager& EnsureChainman(const std::any& context); ChainstateManager& EnsureAnyChainman(const std::any& context); CBlockPolicyEstimator& EnsureFeeEstimator(const NodeContext& node); -CBlockPolicyEstimator& EnsureFeeEstimator(const std::any& context); CBlockPolicyEstimator& EnsureAnyFeeEstimator(const std::any& context); /** -- cgit v1.2.3 From 6a3d1920209cded0dae52fb9070a3530d9a4e5fd Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Mon, 12 Apr 2021 18:41:05 -0400 Subject: rpc: Tidy up local references (see commit message) Organize local variables/references such that: 1. There is always a `ChainstateManager` reference before any `LOCK(cs_main)`. 2. NodeContext references are used with Ensure*() functions introduced in previous commit where appropriate to avoid duplicate assertions. --- src/rpc/blockchain.cpp | 43 ++++++++++++++++++++++++++----------------- src/rpc/mining.cpp | 31 ++++++++++++++++++------------- src/rpc/rawtransaction.cpp | 26 ++++++++++++++++---------- 3 files changed, 60 insertions(+), 40 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 19df2d8031..5fd1521e73 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -210,8 +210,9 @@ static RPCHelpMan getblockcount() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); - return EnsureAnyChainman(request.context).ActiveChain().Height(); + return chainman.ActiveChain().Height(); }, }; } @@ -229,8 +230,9 @@ static RPCHelpMan getbestblockhash() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); - return EnsureAnyChainman(request.context).ActiveChain().Tip()->GetBlockHash().GetHex(); + return chainman.ActiveChain().Tip()->GetBlockHash().GetHex(); }, }; } @@ -410,8 +412,9 @@ static RPCHelpMan getdifficulty() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); - return GetDifficulty(EnsureAnyChainman(request.context).ActiveChain().Tip()); + return GetDifficulty(chainman.ActiveChain().Tip()); }, }; } @@ -775,8 +778,9 @@ static RPCHelpMan getblockhash() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); - const CChain& active_chain = EnsureAnyChainman(request.context).ActiveChain(); + const CChain& active_chain = chainman.ActiveChain(); int nHeight = request.params[0].get_int(); if (nHeight < 0 || nHeight > active_chain.Height()) @@ -835,8 +839,8 @@ static RPCHelpMan getblockheader() const CBlockIndex* pblockindex; const CBlockIndex* tip; { - LOCK(cs_main); ChainstateManager& chainman = EnsureAnyChainman(request.context); + LOCK(cs_main); pblockindex = chainman.m_blockman.LookupBlockIndex(hash); tip = chainman.ActiveChain().Tip(); } @@ -960,8 +964,8 @@ static RPCHelpMan getblock() const CBlockIndex* pblockindex; const CBlockIndex* tip; { - LOCK(cs_main); ChainstateManager& chainman = EnsureAnyChainman(request.context); + LOCK(cs_main); pblockindex = chainman.m_blockman.LookupBlockIndex(hash); tip = chainman.ActiveChain().Tip(); @@ -1003,8 +1007,8 @@ static RPCHelpMan pruneblockchain() if (!fPruneMode) throw JSONRPCError(RPC_MISC_ERROR, "Cannot prune blocks because node is not in prune mode."); - LOCK(cs_main); ChainstateManager& chainman = EnsureAnyChainman(request.context); + LOCK(cs_main); int heightParam = request.params[0].get_int(); if (heightParam < 0) @@ -1086,7 +1090,9 @@ static RPCHelpMan gettxoutsetinfo() UniValue ret(UniValue::VOBJ); CCoinsStats stats; - CChainState& active_chainstate = EnsureAnyChainman(request.context).ActiveChainstate(); + NodeContext& node = EnsureAnyNodeContext(request.context); + ChainstateManager& chainman = EnsureChainman(node); + CChainState& active_chainstate = chainman.ActiveChainstate(); active_chainstate.ForceFlushStateToDisk(); const CoinStatsHashType hash_type{request.params[0].isNull() ? CoinStatsHashType::HASH_SERIALIZED : ParseHashType(request.params[0].get_str())}; @@ -1098,7 +1104,6 @@ static RPCHelpMan gettxoutsetinfo() coins_view = &active_chainstate.CoinsDB(); blockman = &active_chainstate.m_blockman; } - NodeContext& node = EnsureAnyNodeContext(request.context); if (GetUTXOStats(coins_view, *blockman, stats, hash_type, node.rpc_interruption_point)) { ret.pushKV("height", (int64_t)stats.nHeight); ret.pushKV("bestblock", stats.hashBlock.GetHex()); @@ -1158,6 +1163,8 @@ static RPCHelpMan gettxout() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + NodeContext& node = EnsureAnyNodeContext(request.context); + ChainstateManager& chainman = EnsureChainman(node); LOCK(cs_main); UniValue ret(UniValue::VOBJ); @@ -1170,11 +1177,11 @@ static RPCHelpMan gettxout() fMempool = request.params[2].get_bool(); Coin coin; - CChainState& active_chainstate = EnsureAnyChainman(request.context).ActiveChainstate(); + CChainState& active_chainstate = chainman.ActiveChainstate(); CCoinsViewCache* coins_view = &active_chainstate.CoinsTip(); if (fMempool) { - const CTxMemPool& mempool = EnsureAnyMemPool(request.context); + const CTxMemPool& mempool = EnsureMemPool(node); LOCK(mempool.cs); CCoinsViewMemPool view(coins_view, mempool); if (!view.GetCoin(out, coin) || mempool.isSpent(out)) { @@ -1224,9 +1231,10 @@ static RPCHelpMan verifychain() const int check_level(request.params[0].isNull() ? DEFAULT_CHECKLEVEL : request.params[0].get_int()); const int check_depth{request.params[1].isNull() ? DEFAULT_CHECKBLOCKS : request.params[1].get_int()}; + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); - CChainState& active_chainstate = EnsureAnyChainman(request.context).ActiveChainstate(); + CChainState& active_chainstate = chainman.ActiveChainstate(); return CVerifyDB().VerifyDB(Params(), active_chainstate, &active_chainstate.CoinsTip(), check_level, check_depth); }, }; @@ -1353,8 +1361,8 @@ RPCHelpMan getblockchaininfo() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - LOCK(cs_main); ChainstateManager& chainman = EnsureAnyChainman(request.context); + LOCK(cs_main); const CBlockIndex* tip = chainman.ActiveChain().Tip(); CHECK_NONFATAL(tip); @@ -1893,8 +1901,8 @@ static RPCHelpMan getblockstats() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { - LOCK(cs_main); ChainstateManager& chainman = EnsureAnyChainman(request.context); + LOCK(cs_main); CBlockIndex* pindex; if (request.params[0].isNum()) { @@ -2295,16 +2303,16 @@ static RPCHelpMan scantxoutset() int64_t count = 0; std::unique_ptr pcursor; CBlockIndex* tip; + NodeContext& node = EnsureAnyNodeContext(request.context); { + ChainstateManager& chainman = EnsureChainman(node); LOCK(cs_main); - ChainstateManager& chainman = EnsureAnyChainman(request.context); chainman.ActiveChainstate().ForceFlushStateToDisk(); pcursor = std::unique_ptr(chainman.ActiveChainstate().CoinsDB().Cursor()); CHECK_NONFATAL(pcursor); tip = chainman.ActiveChain().Tip(); CHECK_NONFATAL(tip); } - NodeContext& node = EnsureAnyNodeContext(request.context); bool res = FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins, node.rpc_interruption_point); result.pushKV("success", res); result.pushKV("txouts", count); @@ -2377,8 +2385,9 @@ static RPCHelpMan getblockfilter() const CBlockIndex* block_index; bool block_was_connected; { + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); - block_index = EnsureAnyChainman(request.context).m_blockman.LookupBlockIndex(block_hash); + block_index = chainman.m_blockman.LookupBlockIndex(block_hash); if (!block_index) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index f72a19a8a1..37c87d7b01 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -100,9 +100,9 @@ static RPCHelpMan getnetworkhashps() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); - const CChain& active_chain = EnsureAnyChainman(request.context).ActiveChain(); - return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1, active_chain); + return GetNetworkHashPS(!request.params[0].isNull() ? request.params[0].get_int() : 120, !request.params[1].isNull() ? request.params[1].get_int() : -1, chainman.ActiveChain()); }, }; } @@ -235,8 +235,9 @@ static RPCHelpMan generatetodescriptor() throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } - const CTxMemPool& mempool = EnsureAnyMemPool(request.context); - ChainstateManager& chainman = EnsureAnyChainman(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); + const CTxMemPool& mempool = EnsureMemPool(node); + ChainstateManager& chainman = EnsureChainman(node); return generateBlocks(chainman, mempool, coinbase_script, num_blocks, max_tries); }, @@ -280,8 +281,9 @@ static RPCHelpMan generatetoaddress() throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Error: Invalid address"); } - const CTxMemPool& mempool = EnsureAnyMemPool(request.context); - ChainstateManager& chainman = EnsureAnyChainman(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); + const CTxMemPool& mempool = EnsureMemPool(node); + ChainstateManager& chainman = EnsureChainman(node); CScript coinbase_script = GetScriptForDestination(destination); @@ -329,7 +331,8 @@ static RPCHelpMan generateblock() coinbase_script = GetScriptForDestination(destination); } - const CTxMemPool& mempool = EnsureAnyMemPool(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); + const CTxMemPool& mempool = EnsureMemPool(node); std::vector txs; const auto raw_txs_or_txids = request.params[1].get_array(); @@ -358,7 +361,7 @@ static RPCHelpMan generateblock() CChainParams chainparams(Params()); CBlock block; - ChainstateManager& chainman = EnsureAnyChainman(request.context); + ChainstateManager& chainman = EnsureChainman(node); { LOCK(cs_main); @@ -424,9 +427,11 @@ static RPCHelpMan getmininginfo() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + NodeContext& node = EnsureAnyNodeContext(request.context); + const CTxMemPool& mempool = EnsureMemPool(node); + ChainstateManager& chainman = EnsureChainman(node); LOCK(cs_main); - const CTxMemPool& mempool = EnsureAnyMemPool(request.context); - const CChain& active_chain = EnsureAnyChainman(request.context).ActiveChain(); + const CChain& active_chain = chainman.ActiveChain(); UniValue obj(UniValue::VOBJ); obj.pushKV("blocks", (int)active_chain.Height()); @@ -595,8 +600,9 @@ static RPCHelpMan getblocktemplate() }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { + NodeContext& node = EnsureAnyNodeContext(request.context); + ChainstateManager& chainman = EnsureChainman(node); LOCK(cs_main); - ChainstateManager& chainman = EnsureAnyChainman(request.context); std::string strMode = "template"; UniValue lpval = NullUniValue; @@ -663,7 +669,6 @@ static RPCHelpMan getblocktemplate() if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); - NodeContext& node = EnsureAnyNodeContext(request.context); if(!node.connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); @@ -678,7 +683,7 @@ static RPCHelpMan getblocktemplate() } static unsigned int nTransactionsUpdatedLast; - const CTxMemPool& mempool = EnsureAnyMemPool(request.context); + const CTxMemPool& mempool = EnsureMemPool(node); if (!lpval.isNull()) { diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 3e6edde41a..5947755819 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -158,7 +158,7 @@ static RPCHelpMan getrawtransaction() [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const NodeContext& node = EnsureAnyNodeContext(request.context); - ChainstateManager& chainman = EnsureAnyChainman(request.context); + ChainstateManager& chainman = EnsureChainman(node); bool in_active_chain = true; uint256 hash = ParseHashV(request.params[0], "parameter 1"); @@ -350,9 +350,9 @@ static RPCHelpMan verifytxoutproof() if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) return res; + ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); - ChainstateManager& chainman = EnsureAnyChainman(request.context); const CBlockIndex* pindex = chainman.m_blockman.LookupBlockIndex(merkleBlock.header.GetHash()); if (!pindex || !chainman.ActiveChain().Contains(pindex) || pindex->nTx == 0) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); @@ -678,10 +678,11 @@ static RPCHelpMan combinerawtransaction() CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { - const CTxMemPool& mempool = EnsureAnyMemPool(request.context); - LOCK(cs_main); - LOCK(mempool.cs); - CCoinsViewCache &viewChain = EnsureAnyChainman(request.context).ActiveChainstate().CoinsTip(); + NodeContext& node = EnsureAnyNodeContext(request.context); + const CTxMemPool& mempool = EnsureMemPool(node); + ChainstateManager& chainman = EnsureChainman(node); + LOCK2(cs_main, mempool.cs); + CCoinsViewCache &viewChain = chainman.ActiveChainstate().CoinsTip(); CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view @@ -943,7 +944,9 @@ static RPCHelpMan testmempoolaccept() DEFAULT_MAX_RAW_TX_FEE_RATE : CFeeRate(AmountFromValue(request.params[1])); - CTxMemPool& mempool = EnsureAnyMemPool(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); + + CTxMemPool& mempool = EnsureMemPool(node); int64_t virtual_size = GetVirtualTransactionSize(*tx); CAmount max_raw_tx_fee = max_raw_tx_fee_rate.GetFee(virtual_size); @@ -952,7 +955,8 @@ static RPCHelpMan testmempoolaccept() result_0.pushKV("txid", tx->GetHash().GetHex()); result_0.pushKV("wtxid", tx->GetWitnessHash().GetHex()); - const MempoolAcceptResult accept_result = WITH_LOCK(cs_main, return AcceptToMemoryPool(EnsureAnyChainman(request.context).ActiveChainstate(), mempool, std::move(tx), + ChainstateManager& chainman = EnsureChainman(node); + const MempoolAcceptResult accept_result = WITH_LOCK(cs_main, return AcceptToMemoryPool(chainman.ActiveChainstate(), mempool, std::move(tx), false /* bypass_limits */, /* test_accept */ true)); // Only return the fee and vsize if the transaction would pass ATMP. @@ -1601,9 +1605,11 @@ static RPCHelpMan utxoupdatepsbt() CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { - const CTxMemPool& mempool = EnsureAnyMemPool(request.context); + NodeContext& node = EnsureAnyNodeContext(request.context); + const CTxMemPool& mempool = EnsureMemPool(node); + ChainstateManager& chainman = EnsureChainman(node); LOCK2(cs_main, mempool.cs); - CCoinsViewCache &viewChain = EnsureAnyChainman(request.context).ActiveChainstate().CoinsTip(); + CCoinsViewCache &viewChain = chainman.ActiveChainstate().CoinsTip(); CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view -- cgit v1.2.3 From f99913969f92b8b9cef1b83f5ee8e6a9267b4af0 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Mon, 12 Apr 2021 18:48:59 -0400 Subject: rpc: Remove unnecessary casting of block height --- src/rpc/blockchain.cpp | 2 +- src/rpc/mining.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 5fd1521e73..53e8c6d5af 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -1369,7 +1369,7 @@ RPCHelpMan getblockchaininfo() const int height = tip->nHeight; UniValue obj(UniValue::VOBJ); obj.pushKV("chain", Params().NetworkIDString()); - obj.pushKV("blocks", (int)height); + obj.pushKV("blocks", height); obj.pushKV("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1); obj.pushKV("bestblockhash", tip->GetBlockHash().GetHex()); obj.pushKV("difficulty", (double)GetDifficulty(tip)); diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 37c87d7b01..15e03194a3 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -434,7 +434,7 @@ static RPCHelpMan getmininginfo() const CChain& active_chain = chainman.ActiveChain(); UniValue obj(UniValue::VOBJ); - obj.pushKV("blocks", (int)active_chain.Height()); + obj.pushKV("blocks", active_chain.Height()); if (BlockAssembler::m_last_block_weight) obj.pushKV("currentblockweight", *BlockAssembler::m_last_block_weight); if (BlockAssembler::m_last_block_num_txs) obj.pushKV("currentblocktx", *BlockAssembler::m_last_block_num_txs); obj.pushKV("difficulty", (double)GetDifficulty(active_chain.Tip())); -- cgit v1.2.3 From bc3bd369027273278a0541f3b991eb71de831aa2 Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Mon, 12 Apr 2021 18:51:12 -0400 Subject: rpc: style: Improve BuriedForkDescPushBack signature --- src/rpc/blockchain.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 53e8c6d5af..4785a272c0 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -1240,21 +1240,21 @@ static RPCHelpMan verifychain() }; } -static void BuriedForkDescPushBack(UniValue& softforks, const std::string &name, int height, int active_tip_nheight) EXCLUSIVE_LOCKS_REQUIRED(cs_main) +static void BuriedForkDescPushBack(UniValue& softforks, const std::string &name, int softfork_height, int tip_height) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { // For buried deployments. // A buried deployment is one where the height of the activation has been hardcoded into // the client implementation long after the consensus change has activated. See BIP 90. // Buried deployments with activation height value of // std::numeric_limits::max() are disabled and thus hidden. - if (height == std::numeric_limits::max()) return; + if (softfork_height == std::numeric_limits::max()) return; UniValue rv(UniValue::VOBJ); rv.pushKV("type", "buried"); // getblockchaininfo reports the softfork as active from when the chain height is // one below the activation height - rv.pushKV("active", active_tip_nheight + 1 >= height); - rv.pushKV("height", height); + rv.pushKV("active", tip_height + 1 >= softfork_height); + rv.pushKV("height", softfork_height); softforks.pushKV(name, rv); } -- cgit v1.2.3 From 586190f0b4740457cb86cba632e3d64e6dfe9b0c Mon Sep 17 00:00:00 2001 From: Carl Dong Date: Mon, 12 Apr 2021 21:34:42 -0400 Subject: rpc/rest: Take and reuse local Chain/ChainState obj In all rest/rpc-related modules, if there are multiple calls to ActiveChain{,State}(), and the calls fall under the same ::cs_main lock, we can simply take a local reference and use/reuse it instead of calling ActiveChain{,State}() again and again. --- src/rpc/blockchain.cpp | 38 ++++++++++++++++++++++---------------- src/rpc/mining.cpp | 18 ++++++++++-------- src/rpc/rawtransaction.cpp | 5 +++-- 3 files changed, 35 insertions(+), 26 deletions(-) (limited to 'src/rpc') diff --git a/src/rpc/blockchain.cpp b/src/rpc/blockchain.cpp index 4785a272c0..053b6913dc 100644 --- a/src/rpc/blockchain.cpp +++ b/src/rpc/blockchain.cpp @@ -1009,6 +1009,8 @@ static RPCHelpMan pruneblockchain() ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); + CChainState& active_chainstate = chainman.ActiveChainstate(); + CChain& active_chain = active_chainstate.m_chain; int heightParam = request.params[0].get_int(); if (heightParam < 0) @@ -1018,7 +1020,7 @@ static RPCHelpMan pruneblockchain() // 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 = chainman.ActiveChain().FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW, 0); + CBlockIndex* pindex = active_chain.FindEarliestAtLeast(heightParam - TIMESTAMP_WINDOW, 0); if (!pindex) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Could not find block with at least the specified timestamp."); } @@ -1026,7 +1028,7 @@ static RPCHelpMan pruneblockchain() } unsigned int height = (unsigned int) heightParam; - unsigned int chainHeight = (unsigned int) chainman.ActiveChain().Height(); + unsigned int chainHeight = (unsigned int) active_chain.Height(); if (chainHeight < Params().PruneAfterHeight()) throw JSONRPCError(RPC_MISC_ERROR, "Blockchain is too short for pruning."); else if (height > chainHeight) @@ -1036,8 +1038,8 @@ static RPCHelpMan pruneblockchain() height = chainHeight - MIN_BLOCKS_TO_KEEP; } - PruneBlockFilesManual(chainman.ActiveChainstate(), height); - const CBlockIndex* block = chainman.ActiveChain().Tip(); + PruneBlockFilesManual(active_chainstate, height); + const CBlockIndex* block = active_chain.Tip(); CHECK_NONFATAL(block); while (block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA)) { block = block->pprev; @@ -1363,8 +1365,9 @@ RPCHelpMan getblockchaininfo() { ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); + CChainState& active_chainstate = chainman.ActiveChainstate(); - const CBlockIndex* tip = chainman.ActiveChain().Tip(); + const CBlockIndex* tip = active_chainstate.m_chain.Tip(); CHECK_NONFATAL(tip); const int height = tip->nHeight; UniValue obj(UniValue::VOBJ); @@ -1375,7 +1378,7 @@ RPCHelpMan getblockchaininfo() obj.pushKV("difficulty", (double)GetDifficulty(tip)); obj.pushKV("mediantime", (int64_t)tip->GetMedianTimePast()); obj.pushKV("verificationprogress", GuessVerificationProgress(Params().TxData(), tip)); - obj.pushKV("initialblockdownload", chainman.ActiveChainstate().IsInitialBlockDownload()); + obj.pushKV("initialblockdownload", active_chainstate.IsInitialBlockDownload()); obj.pushKV("chainwork", tip->nChainWork.GetHex()); obj.pushKV("size_on_disk", CalculateCurrentUsage()); obj.pushKV("pruned", fPruneMode); @@ -1457,6 +1460,7 @@ static RPCHelpMan getchaintips() { ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); + CChain& active_chain = chainman.ActiveChain(); /* * Idea: The set of chain tips is the active chain tip, plus orphan blocks which do not have another orphan building off of them. @@ -1470,7 +1474,7 @@ static RPCHelpMan getchaintips() std::set setPrevs; for (const std::pair& item : chainman.BlockIndex()) { - if (!chainman.ActiveChain().Contains(item.second)) { + if (!active_chain.Contains(item.second)) { setOrphans.insert(item.second); setPrevs.insert(item.second->pprev); } @@ -1483,7 +1487,7 @@ static RPCHelpMan getchaintips() } // Always report the currently active tip. - setTips.insert(chainman.ActiveChain().Tip()); + setTips.insert(active_chain.Tip()); /* Construct the output array. */ UniValue res(UniValue::VARR); @@ -1492,11 +1496,11 @@ static RPCHelpMan getchaintips() obj.pushKV("height", block->nHeight); obj.pushKV("hash", block->phashBlock->GetHex()); - const int branchLen = block->nHeight - chainman.ActiveChain().FindFork(block)->nHeight; + const int branchLen = block->nHeight - active_chain.FindFork(block)->nHeight; obj.pushKV("branchlen", branchLen); std::string status; - if (chainman.ActiveChain().Contains(block)) { + if (active_chain.Contains(block)) { // This block is part of the currently active chain. status = "active"; } else if (block->nStatus & BLOCK_FAILED_MASK) { @@ -1903,11 +1907,12 @@ static RPCHelpMan getblockstats() { ChainstateManager& chainman = EnsureAnyChainman(request.context); LOCK(cs_main); + CChain& active_chain = chainman.ActiveChain(); CBlockIndex* pindex; if (request.params[0].isNum()) { const int height = request.params[0].get_int(); - const int current_tip = chainman.ActiveChain().Height(); + const int current_tip = active_chain.Height(); if (height < 0) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d is negative", height)); } @@ -1915,14 +1920,14 @@ static RPCHelpMan getblockstats() throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Target block height %d after current tip %d", height, current_tip)); } - pindex = chainman.ActiveChain()[height]; + pindex = active_chain[height]; } else { const uint256 hash(ParseHashV(request.params[0], "hash_or_height")); pindex = chainman.m_blockman.LookupBlockIndex(hash); if (!pindex) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found"); } - if (!chainman.ActiveChain().Contains(pindex)) { + if (!active_chain.Contains(pindex)) { throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("Block is not in chain %s", Params().NetworkIDString())); } } @@ -2307,10 +2312,11 @@ static RPCHelpMan scantxoutset() { ChainstateManager& chainman = EnsureChainman(node); LOCK(cs_main); - chainman.ActiveChainstate().ForceFlushStateToDisk(); - pcursor = std::unique_ptr(chainman.ActiveChainstate().CoinsDB().Cursor()); + CChainState& active_chainstate = chainman.ActiveChainstate(); + active_chainstate.ForceFlushStateToDisk(); + pcursor = std::unique_ptr(active_chainstate.CoinsDB().Cursor()); CHECK_NONFATAL(pcursor); - tip = chainman.ActiveChain().Tip(); + tip = active_chainstate.m_chain.Tip(); CHECK_NONFATAL(tip); } bool res = FindScriptPubKey(g_scan_progress, g_should_abort_scan, count, pcursor.get(), needles, coins, node.rpc_interruption_point); diff --git a/src/rpc/mining.cpp b/src/rpc/mining.cpp index 15e03194a3..0cef310c50 100644 --- a/src/rpc/mining.cpp +++ b/src/rpc/mining.cpp @@ -608,6 +608,8 @@ static RPCHelpMan getblocktemplate() UniValue lpval = NullUniValue; std::set setClientRules; int64_t nMaxVersionPreVB = -1; + CChainState& active_chainstate = chainman.ActiveChainstate(); + CChain& active_chain = active_chainstate.m_chain; if (!request.params[0].isNull()) { const UniValue& oparam = request.params[0].get_obj(); @@ -642,12 +644,12 @@ static RPCHelpMan getblocktemplate() return "duplicate-inconclusive"; } - CBlockIndex* const pindexPrev = chainman.ActiveChain().Tip(); + CBlockIndex* const pindexPrev = active_chain.Tip(); // TestBlockValidity only supports blocks built on the current Tip if (block.hashPrevBlock != pindexPrev->GetBlockHash()) return "inconclusive-not-best-prevblk"; BlockValidationState state; - TestBlockValidity(state, Params(), chainman.ActiveChainstate(), block, pindexPrev, false, true); + TestBlockValidity(state, Params(), active_chainstate, block, pindexPrev, false, true); return BIP22ValidationResult(state); } @@ -677,7 +679,7 @@ static RPCHelpMan getblocktemplate() throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, PACKAGE_NAME " is not connected!"); } - if (chainman.ActiveChainstate().IsInitialBlockDownload()) { + if (active_chainstate.IsInitialBlockDownload()) { throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, PACKAGE_NAME " is in initial sync and waiting for blocks..."); } } @@ -703,7 +705,7 @@ static RPCHelpMan getblocktemplate() else { // NOTE: Spec does not specify behaviour for non-string longpollid, but this makes testing easier - hashWatchedChain = chainman.ActiveChain().Tip()->GetBlockHash(); + hashWatchedChain = active_chain.Tip()->GetBlockHash(); nTransactionsUpdatedLastLP = nTransactionsUpdatedLast; } @@ -748,7 +750,7 @@ static RPCHelpMan getblocktemplate() static CBlockIndex* pindexPrev; static int64_t nStart; static std::unique_ptr pblocktemplate; - if (pindexPrev != chainman.ActiveChain().Tip() || + if (pindexPrev != active_chain.Tip() || (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on @@ -756,12 +758,12 @@ static RPCHelpMan getblocktemplate() // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); - CBlockIndex* pindexPrevNew = chainman.ActiveChain().Tip(); + CBlockIndex* pindexPrevNew = active_chain.Tip(); nStart = GetTime(); // Create new block CScript scriptDummy = CScript() << OP_TRUE; - pblocktemplate = BlockAssembler(chainman.ActiveChainstate(), mempool, Params()).CreateNewBlock(scriptDummy); + pblocktemplate = BlockAssembler(active_chainstate, mempool, Params()).CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); @@ -897,7 +899,7 @@ static RPCHelpMan getblocktemplate() result.pushKV("transactions", transactions); result.pushKV("coinbaseaux", aux); result.pushKV("coinbasevalue", (int64_t)pblock->vtx[0]->vout[0].nValue); - result.pushKV("longpollid", chainman.ActiveChain().Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast)); + result.pushKV("longpollid", active_chain.Tip()->GetBlockHash().GetHex() + ToString(nTransactionsUpdatedLast)); result.pushKV("target", hashTarget.GetHex()); result.pushKV("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1); result.pushKV("mutable", aMutable); diff --git a/src/rpc/rawtransaction.cpp b/src/rpc/rawtransaction.cpp index 5947755819..19e9c75e32 100644 --- a/src/rpc/rawtransaction.cpp +++ b/src/rpc/rawtransaction.cpp @@ -268,12 +268,13 @@ static RPCHelpMan gettxoutproof() } } else { LOCK(cs_main); + CChainState& active_chainstate = chainman.ActiveChainstate(); // Loop through txids and try to find which block they're in. Exit loop once a block is found. for (const auto& tx : setTxids) { - const Coin& coin = AccessByTxid(chainman.ActiveChainstate().CoinsTip(), tx); + const Coin& coin = AccessByTxid(active_chainstate.CoinsTip(), tx); if (!coin.IsSpent()) { - pblockindex = chainman.ActiveChain()[coin.nHeight]; + pblockindex = active_chainstate.m_chain[coin.nHeight]; break; } } -- cgit v1.2.3