Merge #19704: Net processing: move ProcessMessage() to PeerLogicValidation

daed542a12e0a6a4692aca12a61b84cd55accc33 [net_processing] Move ProcessMessage to PeerLogicValidation (John Newbery)
c556770b5ef4306f10e980daff772bee87daaa30 [net_processing] Change PeerLogicValidation to hold a connman reference (John Newbery)

Pull request description:

  Rather than ProcessMessage() being a static function in net_processing.cpp, make it a private member function of PeerLogicValidation. This is the start of moving static functions and global variables into PeerLogicValidation to make it better encapsulated.

ACKs for top commit:
  jonatack:
    ACK daed542a12e0a6a4692aca12a61b84cd55accc33 code review and debug tested
  promag:
    Code review ACK daed542a12e0a6a4692aca12a61b84cd55accc33.
  MarcoFalke:
    re-ACK daed542a12, only change is removing second commit 🎴
  theStack:
    Code Review ACK daed542a12e0a6a4692aca12a61b84cd55accc33

Tree-SHA512: ddebf410d114d9ad5a9e536950018ff333a347c035d74fcc101fb4a3f20a281782c7eac2b7d1bd1c8f6bc7e59f5b5630fb52c2e1b4c32df454fa584673bd021e
This commit is contained in:
fanquake 2020-08-24 21:28:02 +08:00
commit 4fefd80f08
No known key found for this signature in database
GPG Key ID: 2EEB9F5CC09526C1
6 changed files with 115 additions and 131 deletions

View File

@ -1387,7 +1387,7 @@ bool AppInitMain(const util::Ref& context, NodeContext& node, interfaces::BlockA
node.chainman = &g_chainman; node.chainman = &g_chainman;
ChainstateManager& chainman = *Assert(node.chainman); ChainstateManager& chainman = *Assert(node.chainman);
node.peer_logic.reset(new PeerLogicValidation(node.connman.get(), node.banman.get(), *node.scheduler, chainman, *node.mempool)); node.peer_logic.reset(new PeerLogicValidation(*node.connman, node.banman.get(), *node.scheduler, chainman, *node.mempool));
RegisterValidationInterface(node.peer_logic.get()); RegisterValidationInterface(node.peer_logic.get());
// sanitize comments per BIP-0014, format user agent and check total size // sanitize comments per BIP-0014, format user agent and check total size

View File

@ -844,7 +844,7 @@ void PeerLogicValidation::InitializeNode(CNode *pnode) {
mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName), pnode->IsInboundConn(), pnode->IsManualConn())); mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName), pnode->IsInboundConn(), pnode->IsManualConn()));
} }
if(!pnode->IsInboundConn()) if(!pnode->IsInboundConn())
PushNodeVersion(*pnode, *connman, GetTime()); PushNodeVersion(*pnode, m_connman, GetTime());
} }
void PeerLogicValidation::ReattemptInitialBroadcast(CScheduler& scheduler) const void PeerLogicValidation::ReattemptInitialBroadcast(CScheduler& scheduler) const
@ -855,7 +855,7 @@ void PeerLogicValidation::ReattemptInitialBroadcast(CScheduler& scheduler) const
// Sanity check: all unbroadcast txns should exist in the mempool // Sanity check: all unbroadcast txns should exist in the mempool
if (m_mempool.exists(elem.first)) { if (m_mempool.exists(elem.first)) {
LOCK(cs_main); LOCK(cs_main);
RelayTransaction(elem.first, elem.second, *connman); RelayTransaction(elem.first, elem.second, m_connman);
} else { } else {
m_mempool.RemoveUnbroadcastTx(elem.first, true); m_mempool.RemoveUnbroadcastTx(elem.first, true);
} }
@ -1197,8 +1197,8 @@ static bool BlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Para
(GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT); (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT);
} }
PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn, BanMan* banman, CScheduler& scheduler, ChainstateManager& chainman, CTxMemPool& pool) PeerLogicValidation::PeerLogicValidation(CConnman& connman, BanMan* banman, CScheduler& scheduler, ChainstateManager& chainman, CTxMemPool& pool)
: connman(connmanIn), : m_connman(connman),
m_banman(banman), m_banman(banman),
m_chainman(chainman), m_chainman(chainman),
m_mempool(pool), m_mempool(pool),
@ -1326,7 +1326,7 @@ void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std:
fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled; fWitnessesPresentInMostRecentCompactBlock = fWitnessEnabled;
} }
connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) { m_connman.ForEachNode([this, &pcmpctblock, pindex, &msgMaker, fWitnessEnabled, &hashBlock](CNode* pnode) {
AssertLockHeld(cs_main); AssertLockHeld(cs_main);
// TODO: Avoid the repeated-serialization here // TODO: Avoid the repeated-serialization here
@ -1341,7 +1341,7 @@ void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std:
LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock", LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock",
hashBlock.ToString(), pnode->GetId()); hashBlock.ToString(), pnode->GetId());
connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock)); m_connman.PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock));
state.pindexBestHeaderSent = pindex; state.pindexBestHeaderSent = pindex;
} }
}); });
@ -1353,7 +1353,7 @@ void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std:
*/ */
void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) { void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) {
const int nNewHeight = pindexNew->nHeight; const int nNewHeight = pindexNew->nHeight;
connman->SetBestHeight(nNewHeight); m_connman.SetBestHeight(nNewHeight);
SetServiceFlagsIBDCache(!fInitialDownload); SetServiceFlagsIBDCache(!fInitialDownload);
if (!fInitialDownload) { if (!fInitialDownload) {
@ -1370,7 +1370,7 @@ void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CB
} }
} }
// Relay inventory, but don't relay old inventory during initial block download. // Relay inventory, but don't relay old inventory during initial block download.
connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) { m_connman.ForEachNode([nNewHeight, &vHashes](CNode* pnode) {
LOCK(pnode->cs_inventory); LOCK(pnode->cs_inventory);
if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) { if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) {
for (const uint256& hash : reverse_iterate(vHashes)) { for (const uint256& hash : reverse_iterate(vHashes)) {
@ -1378,7 +1378,7 @@ void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CB
} }
} }
}); });
connman->WakeMessageHandler(); m_connman.WakeMessageHandler();
} }
} }
@ -1409,7 +1409,7 @@ void PeerLogicValidation::BlockChecked(const CBlock& block, const BlockValidatio
!::ChainstateActive().IsInitialBlockDownload() && !::ChainstateActive().IsInitialBlockDownload() &&
mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) { mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) {
if (it != mapBlockSource.end()) { if (it != mapBlockSource.end()) {
MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, *connman); MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, m_connman);
} }
} }
if (it != mapBlockSource.end()) if (it != mapBlockSource.end())
@ -2302,17 +2302,9 @@ static void ProcessGetCFCheckPt(CNode& peer, CDataStream& vRecv, const CChainPar
connman.PushMessage(&peer, std::move(msg)); connman.PushMessage(&peer, std::move(msg));
} }
void ProcessMessage( void PeerLogicValidation::ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv,
CNode& pfrom, const std::chrono::microseconds time_received,
const std::string& msg_type, const CChainParams& chainparams, const std::atomic<bool>& interruptMsgProc)
CDataStream& vRecv,
const std::chrono::microseconds time_received,
const CChainParams& chainparams,
ChainstateManager& chainman,
CTxMemPool& mempool,
CConnman& connman,
BanMan* banman,
const std::atomic<bool>& interruptMsgProc)
{ {
LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId()); LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(msg_type), vRecv.size(), pfrom.GetId());
if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0) if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0)
@ -2348,7 +2340,7 @@ void ProcessMessage(
nServices = ServiceFlags(nServiceInt); nServices = ServiceFlags(nServiceInt);
if (!pfrom.IsInboundConn()) if (!pfrom.IsInboundConn())
{ {
connman.SetServices(pfrom.addr, nServices); m_connman.SetServices(pfrom.addr, nServices);
} }
if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices)) if (pfrom.ExpectServicesFromConn() && !HasAllDesirableServiceFlags(nServices))
{ {
@ -2377,7 +2369,7 @@ void ProcessMessage(
if (!vRecv.empty()) if (!vRecv.empty())
vRecv >> fRelay; vRecv >> fRelay;
// Disconnect if we connected to ourself // Disconnect if we connected to ourself
if (pfrom.IsInboundConn() && !connman.CheckIncomingNonce(nNonce)) if (pfrom.IsInboundConn() && !m_connman.CheckIncomingNonce(nNonce))
{ {
LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToString()); LogPrintf("connected to self at %s, disconnecting\n", pfrom.addr.ToString());
pfrom.fDisconnect = true; pfrom.fDisconnect = true;
@ -2391,13 +2383,13 @@ void ProcessMessage(
// Be shy and don't send version until we hear // Be shy and don't send version until we hear
if (pfrom.IsInboundConn()) if (pfrom.IsInboundConn())
PushNodeVersion(pfrom, connman, GetAdjustedTime()); PushNodeVersion(pfrom, m_connman, GetAdjustedTime());
if (nVersion >= WTXID_RELAY_VERSION) { if (nVersion >= WTXID_RELAY_VERSION) {
connman.PushMessage(&pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::WTXIDRELAY)); m_connman.PushMessage(&pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::WTXIDRELAY));
} }
connman.PushMessage(&pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK)); m_connman.PushMessage(&pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK));
pfrom.nServices = nServices; pfrom.nServices = nServices;
pfrom.SetAddrLocal(addrMe); pfrom.SetAddrLocal(addrMe);
@ -2453,9 +2445,9 @@ void ProcessMessage(
} }
// Get recent addresses // Get recent addresses
connman.PushMessage(&pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR)); m_connman.PushMessage(&pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR));
pfrom.fGetAddr = true; pfrom.fGetAddr = true;
connman.MarkAddressGood(pfrom.addr); m_connman.MarkAddressGood(pfrom.addr);
} }
std::string remoteAddr; std::string remoteAddr;
@ -2474,7 +2466,7 @@ void ProcessMessage(
// If the peer is old enough to have the old alert system, send it the final alert. // If the peer is old enough to have the old alert system, send it the final alert.
if (pfrom.nVersion <= 70012) { if (pfrom.nVersion <= 70012) {
CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION); CDataStream finalAlert(ParseHex("60010000000000000000000000ffffff7f00000000ffffff7ffeffff7f01ffffff7f00000000ffffff7f00ffffff7f002f555247454e543a20416c657274206b657920636f6d70726f6d697365642c2075706772616465207265717569726564004630440220653febd6410f470f6bae11cad19c48413becb1ac2c17f908fd0fd53bdc3abd5202206d0e9c96fe88d4a0f01ed9dedae2b6f9e00da94cad0fecaae66ecf689bf71b50"), SER_NETWORK, PROTOCOL_VERSION);
connman.PushMessage(&pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert)); m_connman.PushMessage(&pfrom, CNetMsgMaker(nSendVersion).Make("alert", finalAlert));
} }
// Feeler connections exist only to verify if address is online. // Feeler connections exist only to verify if address is online.
@ -2513,7 +2505,7 @@ void ProcessMessage(
// We send this to non-NODE NETWORK peers as well, because even // We send this to non-NODE NETWORK peers as well, because even
// non-NODE NETWORK peers can announce blocks (such as pruning // non-NODE NETWORK peers can announce blocks (such as pruning
// nodes) // nodes)
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDHEADERS)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDHEADERS));
} }
if (pfrom.nVersion >= SHORT_IDS_BLOCKS_VERSION) { if (pfrom.nVersion >= SHORT_IDS_BLOCKS_VERSION) {
// Tell our peer we are willing to provide version 1 or 2 cmpctblocks // Tell our peer we are willing to provide version 1 or 2 cmpctblocks
@ -2524,9 +2516,9 @@ void ProcessMessage(
bool fAnnounceUsingCMPCTBLOCK = false; bool fAnnounceUsingCMPCTBLOCK = false;
uint64_t nCMPCTBLOCKVersion = 2; uint64_t nCMPCTBLOCKVersion = 2;
if (pfrom.GetLocalServices() & NODE_WITNESS) if (pfrom.GetLocalServices() & NODE_WITNESS)
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
nCMPCTBLOCKVersion = 1; nCMPCTBLOCKVersion = 1;
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion));
} }
pfrom.fSuccessfullyConnected = true; pfrom.fSuccessfullyConnected = true;
return; return;
@ -2590,7 +2582,7 @@ void ProcessMessage(
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60; addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom.AddAddressKnown(addr); pfrom.AddAddressKnown(addr);
if (banman && (banman->IsDiscouraged(addr) || banman->IsBanned(addr))) { if (m_banman && (m_banman->IsDiscouraged(addr) || m_banman->IsBanned(addr))) {
// Do not process banned/discouraged addresses beyond remembering we received them // Do not process banned/discouraged addresses beyond remembering we received them
continue; continue;
} }
@ -2598,13 +2590,13 @@ void ProcessMessage(
if (addr.nTime > nSince && !pfrom.fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) if (addr.nTime > nSince && !pfrom.fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{ {
// Relay to a limited number of other nodes // Relay to a limited number of other nodes
RelayAddress(addr, fReachable, connman); RelayAddress(addr, fReachable, m_connman);
} }
// Do not store addresses outside our network // Do not store addresses outside our network
if (fReachable) if (fReachable)
vAddrOk.push_back(addr); vAddrOk.push_back(addr);
} }
connman.AddNewAddresses(vAddrOk, pfrom.addr, 2 * 60 * 60); m_connman.AddNewAddresses(vAddrOk, pfrom.addr, 2 * 60 * 60);
if (vAddr.size() < 1000) if (vAddr.size() < 1000)
pfrom.fGetAddr = false; pfrom.fGetAddr = false;
if (pfrom.IsAddrFetchConn()) if (pfrom.IsAddrFetchConn())
@ -2680,7 +2672,7 @@ void ProcessMessage(
if (inv.IsMsgWtx()) continue; if (inv.IsMsgWtx()) continue;
} }
bool fAlreadyHave = AlreadyHave(inv, mempool); bool fAlreadyHave = AlreadyHave(inv, m_mempool);
LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId()); LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom.GetId());
if (inv.IsMsgTx()) { if (inv.IsMsgTx()) {
@ -2703,14 +2695,14 @@ void ProcessMessage(
LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId()); LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol, disconnecting peer=%d\n", inv.hash.ToString(), pfrom.GetId());
pfrom.fDisconnect = true; pfrom.fDisconnect = true;
return; return;
} else if (!fAlreadyHave && !chainman.ActiveChainstate().IsInitialBlockDownload()) { } else if (!fAlreadyHave && !m_chainman.ActiveChainstate().IsInitialBlockDownload()) {
RequestTx(State(pfrom.GetId()), ToGenTxid(inv), current_time); RequestTx(State(pfrom.GetId()), ToGenTxid(inv), current_time);
} }
} }
} }
if (best_block != nullptr) { if (best_block != nullptr) {
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), *best_block)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), *best_block));
LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, best_block->ToString(), pfrom.GetId()); LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, best_block->ToString(), pfrom.GetId());
} }
@ -2734,7 +2726,7 @@ void ProcessMessage(
} }
pfrom.vRecvGetData.insert(pfrom.vRecvGetData.end(), vInv.begin(), vInv.end()); pfrom.vRecvGetData.insert(pfrom.vRecvGetData.end(), vInv.begin(), vInv.end());
ProcessGetData(pfrom, chainparams, connman, mempool, interruptMsgProc); ProcessGetData(pfrom, chainparams, m_connman, m_mempool, interruptMsgProc);
return; return;
} }
@ -2818,7 +2810,7 @@ void ProcessMessage(
// Unlock cs_most_recent_block to avoid cs_main lock inversion // Unlock cs_most_recent_block to avoid cs_main lock inversion
} }
if (recent_block) { if (recent_block) {
SendBlockTransactions(*recent_block, req, pfrom, connman); SendBlockTransactions(*recent_block, req, pfrom, m_connman);
return; return;
} }
@ -2851,7 +2843,7 @@ void ProcessMessage(
bool ret = ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()); bool ret = ReadBlockFromDisk(block, pindex, chainparams.GetConsensus());
assert(ret); assert(ret);
SendBlockTransactions(block, req, pfrom, connman); SendBlockTransactions(block, req, pfrom, m_connman);
return; return;
} }
@ -2918,7 +2910,7 @@ void ProcessMessage(
// will re-announce the new block via headers (or compact blocks again) // will re-announce the new block via headers (or compact blocks again)
// in the SendMessages logic. // in the SendMessages logic.
nodestate->pindexBestHeaderSent = pindex ? pindex : ::ChainActive().Tip(); nodestate->pindexBestHeaderSent = pindex ? pindex : ::ChainActive().Tip();
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
return; return;
} }
@ -2977,10 +2969,10 @@ void ProcessMessage(
// already; and an adversary can already relay us old transactions // already; and an adversary can already relay us old transactions
// (older than our recency filter) if trying to DoS us, without any need // (older than our recency filter) if trying to DoS us, without any need
// for witness malleation. // for witness malleation.
if (!AlreadyHave(CInv(MSG_WTX, wtxid), mempool) && if (!AlreadyHave(CInv(MSG_WTX, wtxid), m_mempool) &&
AcceptToMemoryPool(mempool, state, ptx, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) { AcceptToMemoryPool(m_mempool, state, ptx, &lRemovedTxn, false /* bypass_limits */, 0 /* nAbsurdFee */)) {
mempool.check(&::ChainstateActive().CoinsTip()); m_mempool.check(&::ChainstateActive().CoinsTip());
RelayTransaction(tx.GetHash(), tx.GetWitnessHash(), connman); RelayTransaction(tx.GetHash(), tx.GetWitnessHash(), m_connman);
for (unsigned int i = 0; i < tx.vout.size(); i++) { for (unsigned int i = 0; i < tx.vout.size(); i++) {
auto it_by_prev = mapOrphanTransactionsByPrev.find(COutPoint(txid, i)); auto it_by_prev = mapOrphanTransactionsByPrev.find(COutPoint(txid, i));
if (it_by_prev != mapOrphanTransactionsByPrev.end()) { if (it_by_prev != mapOrphanTransactionsByPrev.end()) {
@ -2995,10 +2987,10 @@ void ProcessMessage(
LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n", LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n",
pfrom.GetId(), pfrom.GetId(),
tx.GetHash().ToString(), tx.GetHash().ToString(),
mempool.size(), mempool.DynamicMemoryUsage() / 1000); m_mempool.size(), m_mempool.DynamicMemoryUsage() / 1000);
// Recursively process any orphan transactions that depended on this one // Recursively process any orphan transactions that depended on this one
ProcessOrphanTx(connman, mempool, pfrom.orphan_work_set, lRemovedTxn); ProcessOrphanTx(m_connman, m_mempool, pfrom.orphan_work_set, lRemovedTxn);
} }
else if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS) else if (state.GetResult() == TxValidationResult::TX_MISSING_INPUTS)
{ {
@ -3032,7 +3024,7 @@ void ProcessMessage(
// protocol for getting all unconfirmed parents. // protocol for getting all unconfirmed parents.
CInv _inv(MSG_TX | nFetchFlags, parent_txid); CInv _inv(MSG_TX | nFetchFlags, parent_txid);
pfrom.AddKnownTx(parent_txid); pfrom.AddKnownTx(parent_txid);
if (!AlreadyHave(_inv, mempool)) RequestTx(State(pfrom.GetId()), ToGenTxid(_inv), current_time); if (!AlreadyHave(_inv, m_mempool)) RequestTx(State(pfrom.GetId()), ToGenTxid(_inv), current_time);
} }
AddOrphanTx(ptx, pfrom.GetId()); AddOrphanTx(ptx, pfrom.GetId());
@ -3093,11 +3085,11 @@ void ProcessMessage(
// if they were already in the mempool, // if they were already in the mempool,
// allowing the node to function as a gateway for // allowing the node to function as a gateway for
// nodes hidden behind it. // nodes hidden behind it.
if (!mempool.exists(tx.GetHash())) { if (!m_mempool.exists(tx.GetHash())) {
LogPrintf("Not relaying non-mempool transaction %s from forcerelay peer=%d\n", tx.GetHash().ToString(), pfrom.GetId()); LogPrintf("Not relaying non-mempool transaction %s from forcerelay peer=%d\n", tx.GetHash().ToString(), pfrom.GetId());
} else { } else {
LogPrintf("Force relaying tx %s from peer=%d\n", tx.GetHash().ToString(), pfrom.GetId()); LogPrintf("Force relaying tx %s from peer=%d\n", tx.GetHash().ToString(), pfrom.GetId());
RelayTransaction(tx.GetHash(), tx.GetWitnessHash(), connman); RelayTransaction(tx.GetHash(), tx.GetWitnessHash(), m_connman);
} }
} }
} }
@ -3150,7 +3142,7 @@ void ProcessMessage(
if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) { if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) {
// Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers
if (!::ChainstateActive().IsInitialBlockDownload()) if (!::ChainstateActive().IsInitialBlockDownload())
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), uint256())); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexBestHeader), uint256()));
return; return;
} }
@ -3161,7 +3153,7 @@ void ProcessMessage(
const CBlockIndex *pindex = nullptr; const CBlockIndex *pindex = nullptr;
BlockValidationState state; BlockValidationState state;
if (!chainman.ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) { if (!m_chainman.ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) {
if (state.IsInvalid()) { if (state.IsInvalid()) {
MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block*/ true, "invalid header via cmpctblock"); MaybePunishNodeForBlock(pfrom.GetId(), state, /*via_compact_block*/ true, "invalid header via cmpctblock");
return; return;
@ -3211,7 +3203,7 @@ void ProcessMessage(
// so we just grab the block via normal getdata // so we just grab the block via normal getdata
std::vector<CInv> vInv(1); std::vector<CInv> vInv(1);
vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash()); vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
} }
return; return;
} }
@ -3232,9 +3224,9 @@ void ProcessMessage(
if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) || if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) ||
(fAlreadyInFlight && blockInFlightIt->second.first == pfrom.GetId())) { (fAlreadyInFlight && blockInFlightIt->second.first == pfrom.GetId())) {
std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr; std::list<QueuedBlock>::iterator* queuedBlockIt = nullptr;
if (!MarkBlockAsInFlight(mempool, pfrom.GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) { if (!MarkBlockAsInFlight(m_mempool, pfrom.GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) {
if (!(*queuedBlockIt)->partialBlock) if (!(*queuedBlockIt)->partialBlock)
(*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool)); (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&m_mempool));
else { else {
// The block was already in flight using compact blocks from the same peer // The block was already in flight using compact blocks from the same peer
LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n"); LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n");
@ -3252,7 +3244,7 @@ void ProcessMessage(
// Duplicate txindexes, the block is now in-flight, so just request it // Duplicate txindexes, the block is now in-flight, so just request it
std::vector<CInv> vInv(1); std::vector<CInv> vInv(1);
vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash()); vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
return; return;
} }
@ -3269,7 +3261,7 @@ void ProcessMessage(
fProcessBLOCKTXN = true; fProcessBLOCKTXN = true;
} else { } else {
req.blockhash = pindex->GetBlockHash(); req.blockhash = pindex->GetBlockHash();
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req));
} }
} else { } else {
// This block is either already in flight from a different // This block is either already in flight from a different
@ -3277,7 +3269,7 @@ void ProcessMessage(
// download from. // download from.
// Optimistically try to reconstruct anyway since we might be // Optimistically try to reconstruct anyway since we might be
// able to without any round trips. // able to without any round trips.
PartiallyDownloadedBlock tempBlock(&mempool); PartiallyDownloadedBlock tempBlock(&m_mempool);
ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact); ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact);
if (status != READ_STATUS_OK) { if (status != READ_STATUS_OK) {
// TODO: don't ignore failures // TODO: don't ignore failures
@ -3295,7 +3287,7 @@ void ProcessMessage(
// mempool will probably be useless - request the block normally // mempool will probably be useless - request the block normally
std::vector<CInv> vInv(1); std::vector<CInv> vInv(1);
vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash()); vInv[0] = CInv(MSG_BLOCK | GetFetchFlags(pfrom), cmpctblock.header.GetHash());
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv));
return; return;
} else { } else {
// If this was an announce-cmpctblock, we want the same treatment as a header message // If this was an announce-cmpctblock, we want the same treatment as a header message
@ -3305,7 +3297,7 @@ void ProcessMessage(
} // cs_main } // cs_main
if (fProcessBLOCKTXN) if (fProcessBLOCKTXN)
return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, time_received, chainparams, chainman, mempool, connman, banman, interruptMsgProc); return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, time_received, chainparams, interruptMsgProc);
if (fRevertToHeaderProcessing) { if (fRevertToHeaderProcessing) {
// Headers received from HB compact block peers are permitted to be // Headers received from HB compact block peers are permitted to be
@ -3313,7 +3305,7 @@ void ProcessMessage(
// the peer if the header turns out to be for an invalid block. // the peer if the header turns out to be for an invalid block.
// Note that if a peer tries to build on an invalid chain, that // Note that if a peer tries to build on an invalid chain, that
// will be detected and the peer will be disconnected/discouraged. // will be detected and the peer will be disconnected/discouraged.
return ProcessHeadersMessage(pfrom, connman, chainman, mempool, {cmpctblock.header}, chainparams, /*via_compact_block=*/true); return ProcessHeadersMessage(pfrom, m_connman, m_chainman, m_mempool, {cmpctblock.header}, chainparams, /*via_compact_block=*/true);
} }
if (fBlockReconstructed) { if (fBlockReconstructed) {
@ -3333,7 +3325,7 @@ void ProcessMessage(
// we have a chain with at least nMinimumChainWork), and we ignore // we have a chain with at least nMinimumChainWork), and we ignore
// compact blocks with less work than our tip, it is safe to treat // compact blocks with less work than our tip, it is safe to treat
// reconstructed compact blocks as having been requested. // reconstructed compact blocks as having been requested.
chainman.ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock); m_chainman.ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
if (fNewBlock) { if (fNewBlock) {
pfrom.nLastBlockTime = GetTime(); pfrom.nLastBlockTime = GetTime();
} else { } else {
@ -3385,7 +3377,7 @@ void ProcessMessage(
// Might have collided, fall back to getdata now :( // Might have collided, fall back to getdata now :(
std::vector<CInv> invs; std::vector<CInv> invs;
invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash)); invs.push_back(CInv(MSG_BLOCK | GetFetchFlags(pfrom), resp.blockhash));
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, invs)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::GETDATA, invs));
} else { } else {
// Block is either okay, or possibly we received // Block is either okay, or possibly we received
// READ_STATUS_CHECKBLOCK_FAILED. // READ_STATUS_CHECKBLOCK_FAILED.
@ -3423,7 +3415,7 @@ void ProcessMessage(
// disk-space attacks), but this should be safe due to the // disk-space attacks), but this should be safe due to the
// protections in the compact block handler -- see related comment // protections in the compact block handler -- see related comment
// in compact block optimistic reconstruction handling. // in compact block optimistic reconstruction handling.
chainman.ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock); m_chainman.ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock);
if (fNewBlock) { if (fNewBlock) {
pfrom.nLastBlockTime = GetTime(); pfrom.nLastBlockTime = GetTime();
} else { } else {
@ -3457,7 +3449,7 @@ void ProcessMessage(
ReadCompactSize(vRecv); // ignore tx count; assume it is 0. ReadCompactSize(vRecv); // ignore tx count; assume it is 0.
} }
return ProcessHeadersMessage(pfrom, connman, chainman, mempool, headers, chainparams, /*via_compact_block=*/false); return ProcessHeadersMessage(pfrom, m_connman, m_chainman, m_mempool, headers, chainparams, /*via_compact_block=*/false);
} }
if (msg_type == NetMsgType::BLOCK) if (msg_type == NetMsgType::BLOCK)
@ -3486,7 +3478,7 @@ void ProcessMessage(
mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true)); mapBlockSource.emplace(hash, std::make_pair(pfrom.GetId(), true));
} }
bool fNewBlock = false; bool fNewBlock = false;
chainman.ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock); m_chainman.ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock);
if (fNewBlock) { if (fNewBlock) {
pfrom.nLastBlockTime = GetTime(); pfrom.nLastBlockTime = GetTime();
} else { } else {
@ -3522,9 +3514,9 @@ void ProcessMessage(
pfrom.vAddrToSend.clear(); pfrom.vAddrToSend.clear();
std::vector<CAddress> vAddr; std::vector<CAddress> vAddr;
if (pfrom.HasPermission(PF_ADDR)) { if (pfrom.HasPermission(PF_ADDR)) {
vAddr = connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND); vAddr = m_connman.GetAddresses(MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
} else { } else {
vAddr = connman.GetAddresses(pfrom.addr.GetNetwork(), MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND); vAddr = m_connman.GetAddresses(pfrom.addr.GetNetwork(), MAX_ADDR_TO_SEND, MAX_PCT_ADDR_TO_SEND);
} }
FastRandomContext insecure_rand; FastRandomContext insecure_rand;
for (const CAddress &addr : vAddr) { for (const CAddress &addr : vAddr) {
@ -3544,7 +3536,7 @@ void ProcessMessage(
return; return;
} }
if (connman.OutboundTargetReached(false) && !pfrom.HasPermission(PF_MEMPOOL)) if (m_connman.OutboundTargetReached(false) && !pfrom.HasPermission(PF_MEMPOOL))
{ {
if (!pfrom.HasPermission(PF_NOBAN)) if (!pfrom.HasPermission(PF_NOBAN))
{ {
@ -3577,7 +3569,7 @@ void ProcessMessage(
// it, if the remote node sends a ping once per second and this node takes 5 // it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to // seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly. // return very quickly.
connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::PONG, nonce)); m_connman.PushMessage(&pfrom, msgMaker.Make(NetMsgType::PONG, nonce));
} }
return; return;
} }
@ -3717,17 +3709,17 @@ void ProcessMessage(
} }
if (msg_type == NetMsgType::GETCFILTERS) { if (msg_type == NetMsgType::GETCFILTERS) {
ProcessGetCFilters(pfrom, vRecv, chainparams, connman); ProcessGetCFilters(pfrom, vRecv, chainparams, m_connman);
return; return;
} }
if (msg_type == NetMsgType::GETCFHEADERS) { if (msg_type == NetMsgType::GETCFHEADERS) {
ProcessGetCFHeaders(pfrom, vRecv, chainparams, connman); ProcessGetCFHeaders(pfrom, vRecv, chainparams, m_connman);
return; return;
} }
if (msg_type == NetMsgType::GETCFCHECKPT) { if (msg_type == NetMsgType::GETCFCHECKPT) {
ProcessGetCFCheckPt(pfrom, vRecv, chainparams, connman); ProcessGetCFCheckPt(pfrom, vRecv, chainparams, m_connman);
return; return;
} }
@ -3802,7 +3794,7 @@ bool PeerLogicValidation::MaybeDiscourageAndDisconnect(CNode& pnode)
// Normal case: Disconnect the peer and discourage all nodes sharing the address // Normal case: Disconnect the peer and discourage all nodes sharing the address
LogPrintf("Disconnecting and discouraging peer %d!\n", peer_id); LogPrintf("Disconnecting and discouraging peer %d!\n", peer_id);
if (m_banman) m_banman->Discourage(pnode.addr); if (m_banman) m_banman->Discourage(pnode.addr);
connman->DisconnectNode(pnode.addr); m_connman.DisconnectNode(pnode.addr);
return true; return true;
} }
@ -3820,12 +3812,12 @@ bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& inter
bool fMoreWork = false; bool fMoreWork = false;
if (!pfrom->vRecvGetData.empty()) if (!pfrom->vRecvGetData.empty())
ProcessGetData(*pfrom, chainparams, *connman, m_mempool, interruptMsgProc); ProcessGetData(*pfrom, chainparams, m_connman, m_mempool, interruptMsgProc);
if (!pfrom->orphan_work_set.empty()) { if (!pfrom->orphan_work_set.empty()) {
std::list<CTransactionRef> removed_txn; std::list<CTransactionRef> removed_txn;
LOCK2(cs_main, g_cs_orphans); LOCK2(cs_main, g_cs_orphans);
ProcessOrphanTx(*connman, m_mempool, pfrom->orphan_work_set, removed_txn); ProcessOrphanTx(m_connman, m_mempool, pfrom->orphan_work_set, removed_txn);
for (const CTransactionRef& removedTx : removed_txn) { for (const CTransactionRef& removedTx : removed_txn) {
AddToCompactExtraTransactions(removedTx); AddToCompactExtraTransactions(removedTx);
} }
@ -3851,7 +3843,7 @@ bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& inter
// Just take one message // Just take one message
msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin()); msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin());
pfrom->nProcessQueueSize -= msgs.front().m_raw_message_size; pfrom->nProcessQueueSize -= msgs.front().m_raw_message_size;
pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman->GetReceiveFloodSize(); pfrom->fPauseRecv = pfrom->nProcessQueueSize > m_connman.GetReceiveFloodSize();
fMoreWork = !pfrom->vProcessMsg.empty(); fMoreWork = !pfrom->vProcessMsg.empty();
} }
CNetMessage& msg(msgs.front()); CNetMessage& msg(msgs.front());
@ -3885,7 +3877,7 @@ bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& inter
} }
try { try {
ProcessMessage(*pfrom, msg_type, vRecv, msg.m_time, chainparams, m_chainman, m_mempool, *connman, m_banman, interruptMsgProc); ProcessMessage(*pfrom, msg_type, vRecv, msg.m_time, chainparams, interruptMsgProc);
if (interruptMsgProc) if (interruptMsgProc)
return false; return false;
if (!pfrom->vRecvGetData.empty()) if (!pfrom->vRecvGetData.empty())
@ -3938,7 +3930,7 @@ void PeerLogicValidation::ConsiderEviction(CNode& pto, int64_t time_in_seconds)
} else { } else {
assert(state.m_chain_sync.m_work_header); assert(state.m_chain_sync.m_work_header);
LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString()); LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto.GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString());
connman->PushMessage(&pto, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(state.m_chain_sync.m_work_header->pprev), uint256())); m_connman.PushMessage(&pto, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(state.m_chain_sync.m_work_header->pprev), uint256()));
state.m_chain_sync.m_sent_getheaders = true; state.m_chain_sync.m_sent_getheaders = true;
constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes
// Bump the timeout to allow a response, which could clear the timeout // Bump the timeout to allow a response, which could clear the timeout
@ -3955,7 +3947,7 @@ void PeerLogicValidation::ConsiderEviction(CNode& pto, int64_t time_in_seconds)
void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds) void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
{ {
// Check whether we have too many outbound peers // Check whether we have too many outbound peers
int extra_peers = connman->GetExtraOutboundCount(); int extra_peers = m_connman.GetExtraOutboundCount();
if (extra_peers > 0) { if (extra_peers > 0) {
// If we have more outbound peers than we target, disconnect one. // If we have more outbound peers than we target, disconnect one.
// Pick the outbound peer that least recently announced // Pick the outbound peer that least recently announced
@ -3964,7 +3956,7 @@ void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
NodeId worst_peer = -1; NodeId worst_peer = -1;
int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max(); int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max();
connman->ForEachNode([&](CNode* pnode) { m_connman.ForEachNode([&](CNode* pnode) {
AssertLockHeld(cs_main); AssertLockHeld(cs_main);
// Ignore non-outbound peers, or nodes marked for disconnect already // Ignore non-outbound peers, or nodes marked for disconnect already
@ -3981,7 +3973,7 @@ void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
} }
}); });
if (worst_peer != -1) { if (worst_peer != -1) {
bool disconnected = connman->ForNode(worst_peer, [&](CNode *pnode) { bool disconnected = m_connman.ForNode(worst_peer, [&](CNode *pnode) {
AssertLockHeld(cs_main); AssertLockHeld(cs_main);
// Only disconnect a peer that has been connected to us for // Only disconnect a peer that has been connected to us for
@ -4005,7 +3997,7 @@ void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds)
// detected a stale tip. Don't try any more extra peers until // detected a stale tip. Don't try any more extra peers until
// we next detect a stale tip, to limit the load we put on the // we next detect a stale tip, to limit the load we put on the
// network from these extra connections. // network from these extra connections.
connman->SetTryNewOutboundPeer(false); m_connman.SetTryNewOutboundPeer(false);
} }
} }
} }
@ -4015,8 +4007,6 @@ void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params
{ {
LOCK(cs_main); LOCK(cs_main);
if (connman == nullptr) return;
int64_t time_in_seconds = GetTime(); int64_t time_in_seconds = GetTime();
EvictExtraOutboundPeers(time_in_seconds); EvictExtraOutboundPeers(time_in_seconds);
@ -4024,11 +4014,11 @@ void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params
if (time_in_seconds > m_stale_tip_check_time) { if (time_in_seconds > m_stale_tip_check_time) {
// Check whether our tip is stale, and if so, allow using an extra // Check whether our tip is stale, and if so, allow using an extra
// outbound peer // outbound peer
if (!fImporting && !fReindex && connman->GetNetworkActive() && connman->GetUseAddrmanOutgoing() && TipMayBeStale(consensusParams)) { if (!fImporting && !fReindex && m_connman.GetNetworkActive() && m_connman.GetUseAddrmanOutgoing() && TipMayBeStale(consensusParams)) {
LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds - g_last_tip_update); LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds - g_last_tip_update);
connman->SetTryNewOutboundPeer(true); m_connman.SetTryNewOutboundPeer(true);
} else if (connman->GetTryNewOutboundPeer()) { } else if (m_connman.GetTryNewOutboundPeer()) {
connman->SetTryNewOutboundPeer(false); m_connman.SetTryNewOutboundPeer(false);
} }
m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL; m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL;
} }
@ -4091,11 +4081,11 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
pto->m_ping_start = GetTime<std::chrono::microseconds>(); pto->m_ping_start = GetTime<std::chrono::microseconds>();
if (pto->nVersion > BIP0031_VERSION) { if (pto->nVersion > BIP0031_VERSION) {
pto->nPingNonceSent = nonce; pto->nPingNonceSent = nonce;
connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce));
} else { } else {
// Peer is too old to support ping command with nonce, pong will never arrive. // Peer is too old to support ping command with nonce, pong will never arrive.
pto->nPingNonceSent = 0; pto->nPingNonceSent = 0;
connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::PING));
} }
} }
@ -4130,14 +4120,14 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
// receiver rejects addr messages larger than MAX_ADDR_TO_SEND // receiver rejects addr messages larger than MAX_ADDR_TO_SEND
if (vAddr.size() >= MAX_ADDR_TO_SEND) if (vAddr.size() >= MAX_ADDR_TO_SEND)
{ {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
vAddr.clear(); vAddr.clear();
} }
} }
} }
pto->vAddrToSend.clear(); pto->vAddrToSend.clear();
if (!vAddr.empty()) if (!vAddr.empty())
connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr));
// we only send the big addr message once // we only send the big addr message once
if (pto->vAddrToSend.capacity() > 40) if (pto->vAddrToSend.capacity() > 40)
pto->vAddrToSend.shrink_to_fit(); pto->vAddrToSend.shrink_to_fit();
@ -4164,7 +4154,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
if (pindexStart->pprev) if (pindexStart->pprev)
pindexStart = pindexStart->pprev; pindexStart = pindexStart->pprev;
LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight); LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight);
connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexStart), uint256())); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, ::ChainActive().GetLocator(pindexStart), uint256()));
} }
} }
@ -4248,10 +4238,10 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
LOCK(cs_most_recent_block); LOCK(cs_most_recent_block);
if (most_recent_block_hash == pBestIndex->GetBlockHash()) { if (most_recent_block_hash == pBestIndex->GetBlockHash()) {
if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock) if (state.fWantsCmpctWitness || !fWitnessesPresentInMostRecentCompactBlock)
connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block)); m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, *most_recent_compact_block));
else { else {
CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness); CBlockHeaderAndShortTxIDs cmpctblock(*most_recent_block, state.fWantsCmpctWitness);
connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock)); m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
} }
fGotBlockFromCache = true; fGotBlockFromCache = true;
} }
@ -4261,7 +4251,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams); bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams);
assert(ret); assert(ret);
CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness); CBlockHeaderAndShortTxIDs cmpctblock(block, state.fWantsCmpctWitness);
connman->PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock)); m_connman.PushMessage(pto, msgMaker.Make(nSendFlags, NetMsgType::CMPCTBLOCK, cmpctblock));
} }
state.pindexBestHeaderSent = pBestIndex; state.pindexBestHeaderSent = pBestIndex;
} else if (state.fPreferHeaders) { } else if (state.fPreferHeaders) {
@ -4274,7 +4264,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__, LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__,
vHeaders.front().GetHash().ToString(), pto->GetId()); vHeaders.front().GetHash().ToString(), pto->GetId());
} }
connman->PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders));
state.pindexBestHeaderSent = pBestIndex; state.pindexBestHeaderSent = pBestIndex;
} else } else
fRevertToInv = true; fRevertToInv = true;
@ -4319,7 +4309,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
for (const uint256& hash : pto->vInventoryBlockToSend) { for (const uint256& hash : pto->vInventoryBlockToSend) {
vInv.push_back(CInv(MSG_BLOCK, hash)); vInv.push_back(CInv(MSG_BLOCK, hash));
if (vInv.size() == MAX_INV_SZ) { if (vInv.size() == MAX_INV_SZ) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
vInv.clear(); vInv.clear();
} }
} }
@ -4332,7 +4322,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
if (pto->m_tx_relay->nNextInvSend < current_time) { if (pto->m_tx_relay->nNextInvSend < current_time) {
fSendTrickle = true; fSendTrickle = true;
if (pto->IsInboundConn()) { if (pto->IsInboundConn()) {
pto->m_tx_relay->nNextInvSend = std::chrono::microseconds{connman->PoissonNextSendInbound(nNow, INVENTORY_BROADCAST_INTERVAL)}; pto->m_tx_relay->nNextInvSend = std::chrono::microseconds{m_connman.PoissonNextSendInbound(nNow, INVENTORY_BROADCAST_INTERVAL)};
} else { } else {
// Use half the delay for outbound peers, as there is less privacy concern for them. // Use half the delay for outbound peers, as there is less privacy concern for them.
pto->m_tx_relay->nNextInvSend = PoissonNextSend(current_time, std::chrono::seconds{INVENTORY_BROADCAST_INTERVAL >> 1}); pto->m_tx_relay->nNextInvSend = PoissonNextSend(current_time, std::chrono::seconds{INVENTORY_BROADCAST_INTERVAL >> 1});
@ -4372,7 +4362,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
// Responses to MEMPOOL requests bypass the m_recently_announced_invs filter. // Responses to MEMPOOL requests bypass the m_recently_announced_invs filter.
vInv.push_back(inv); vInv.push_back(inv);
if (vInv.size() == MAX_INV_SZ) { if (vInv.size() == MAX_INV_SZ) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
vInv.clear(); vInv.clear();
} }
} }
@ -4448,7 +4438,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
} }
} }
if (vInv.size() == MAX_INV_SZ) { if (vInv.size() == MAX_INV_SZ) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
vInv.clear(); vInv.clear();
} }
pto->m_tx_relay->filterInventoryKnown.insert(hash); pto->m_tx_relay->filterInventoryKnown.insert(hash);
@ -4465,7 +4455,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
} }
} }
if (!vInv.empty()) if (!vInv.empty())
connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv));
// Detect whether we're stalling // Detect whether we're stalling
current_time = GetTime<std::chrono::microseconds>(); current_time = GetTime<std::chrono::microseconds>();
@ -4593,7 +4583,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId()); LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId());
vGetData.push_back(inv); vGetData.push_back(inv);
if (vGetData.size() >= MAX_GETDATA_SZ) { if (vGetData.size() >= MAX_GETDATA_SZ) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
vGetData.clear(); vGetData.clear();
} }
UpdateTxRequestTime(gtxid, current_time); UpdateTxRequestTime(gtxid, current_time);
@ -4623,7 +4613,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
if (!vGetData.empty()) if (!vGetData.empty())
connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData));
// //
// Message: feefilter // Message: feefilter
@ -4651,7 +4641,7 @@ bool PeerLogicValidation::SendMessages(CNode* pto)
// We always have a fee filter of at least minRelayTxFee // We always have a fee filter of at least minRelayTxFee
filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK()); filterToSend = std::max(filterToSend, ::minRelayTxFee.GetFeePerK());
if (filterToSend != pto->m_tx_relay->lastSentFeeFilter) { if (filterToSend != pto->m_tx_relay->lastSentFeeFilter) {
connman->PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend)); m_connman.PushMessage(pto, msgMaker.Make(NetMsgType::FEEFILTER, filterToSend));
pto->m_tx_relay->lastSentFeeFilter = filterToSend; pto->m_tx_relay->lastSentFeeFilter = filterToSend;
} }
pto->m_tx_relay->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL); pto->m_tx_relay->nextSendTimeFeeFilter = PoissonNextSend(timeNow, AVG_FEEFILTER_BROADCAST_INTERVAL);

View File

@ -11,6 +11,7 @@
#include <sync.h> #include <sync.h>
#include <validationinterface.h> #include <validationinterface.h>
class CChainParams;
class CTxMemPool; class CTxMemPool;
class ChainstateManager; class ChainstateManager;
@ -28,7 +29,7 @@ static const int DISCOURAGEMENT_THRESHOLD{100};
class PeerLogicValidation final : public CValidationInterface, public NetEventsInterface { class PeerLogicValidation final : public CValidationInterface, public NetEventsInterface {
private: private:
CConnman* const connman; CConnman& m_connman;
/** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */ /** Pointer to this node's banman. May be nullptr - check existence before dereferencing. */
BanMan* const m_banman; BanMan* const m_banman;
ChainstateManager& m_chainman; ChainstateManager& m_chainman;
@ -37,7 +38,7 @@ private:
bool MaybeDiscourageAndDisconnect(CNode& pnode); bool MaybeDiscourageAndDisconnect(CNode& pnode);
public: public:
PeerLogicValidation(CConnman* connman, BanMan* banman, CScheduler& scheduler, ChainstateManager& chainman, CTxMemPool& pool); PeerLogicValidation(CConnman& connman, BanMan* banman, CScheduler& scheduler, ChainstateManager& chainman, CTxMemPool& pool);
/** /**
* Overridden from CValidationInterface. * Overridden from CValidationInterface.
@ -85,8 +86,14 @@ public:
/** Retrieve unbroadcast transactions from the mempool and reattempt sending to peers */ /** Retrieve unbroadcast transactions from the mempool and reattempt sending to peers */
void ReattemptInitialBroadcast(CScheduler& scheduler) const; void ReattemptInitialBroadcast(CScheduler& scheduler) const;
/** Process a single message from a peer. Public for fuzz testing */
void ProcessMessage(CNode& pfrom, const std::string& msg_type, CDataStream& vRecv,
const std::chrono::microseconds time_received, const CChainParams& chainparams,
const std::atomic<bool>& interruptMsgProc);
private: private:
int64_t m_stale_tip_check_time; //!< Next time to check for stale tip int64_t m_stale_tip_check_time; //!< Next time to check for stale tip
}; };
struct CNodeStateStats { struct CNodeStateStats {

View File

@ -80,7 +80,7 @@ BOOST_FIXTURE_TEST_SUITE(denialofservice_tests, TestingSetup)
BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction) BOOST_AUTO_TEST_CASE(outbound_slow_chain_eviction)
{ {
auto connman = MakeUnique<CConnman>(0x1337, 0x1337); auto connman = MakeUnique<CConnman>(0x1337, 0x1337);
auto peerLogic = MakeUnique<PeerLogicValidation>(connman.get(), nullptr, *m_node.scheduler, *m_node.chainman, *m_node.mempool); auto peerLogic = MakeUnique<PeerLogicValidation>(*connman, nullptr, *m_node.scheduler, *m_node.chainman, *m_node.mempool);
// Mock an outbound peer // Mock an outbound peer
CAddress addr1(ip(0xa0b0c001), NODE_NONE); CAddress addr1(ip(0xa0b0c001), NODE_NONE);
@ -150,7 +150,7 @@ static void AddRandomOutboundPeer(std::vector<CNode *> &vNodes, PeerLogicValidat
BOOST_AUTO_TEST_CASE(stale_tip_peer_management) BOOST_AUTO_TEST_CASE(stale_tip_peer_management)
{ {
auto connman = MakeUnique<CConnmanTest>(0x1337, 0x1337); auto connman = MakeUnique<CConnmanTest>(0x1337, 0x1337);
auto peerLogic = MakeUnique<PeerLogicValidation>(connman.get(), nullptr, *m_node.scheduler, *m_node.chainman, *m_node.mempool); auto peerLogic = MakeUnique<PeerLogicValidation>(*connman, nullptr, *m_node.scheduler, *m_node.chainman, *m_node.mempool);
const Consensus::Params& consensusParams = Params().GetConsensus(); const Consensus::Params& consensusParams = Params().GetConsensus();
constexpr int max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS; constexpr int max_outbound_full_relay = MAX_OUTBOUND_FULL_RELAY_CONNECTIONS;
@ -223,7 +223,7 @@ BOOST_AUTO_TEST_CASE(peer_discouragement)
{ {
auto banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME); auto banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME);
auto connman = MakeUnique<CConnman>(0x1337, 0x1337); auto connman = MakeUnique<CConnman>(0x1337, 0x1337);
auto peerLogic = MakeUnique<PeerLogicValidation>(connman.get(), banman.get(), *m_node.scheduler, *m_node.chainman, *m_node.mempool); auto peerLogic = MakeUnique<PeerLogicValidation>(*connman, banman.get(), *m_node.scheduler, *m_node.chainman, *m_node.mempool);
banman->ClearBanned(); banman->ClearBanned();
CAddress addr1(ip(0xa0b0c001), NODE_NONE); CAddress addr1(ip(0xa0b0c001), NODE_NONE);
@ -279,7 +279,7 @@ BOOST_AUTO_TEST_CASE(DoS_bantime)
{ {
auto banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME); auto banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME);
auto connman = MakeUnique<CConnman>(0x1337, 0x1337); auto connman = MakeUnique<CConnman>(0x1337, 0x1337);
auto peerLogic = MakeUnique<PeerLogicValidation>(connman.get(), banman.get(), *m_node.scheduler, *m_node.chainman, *m_node.mempool); auto peerLogic = MakeUnique<PeerLogicValidation>(*connman, banman.get(), *m_node.scheduler, *m_node.chainman, *m_node.mempool);
banman->ClearBanned(); banman->ClearBanned();
int64_t nStartTime = GetTime(); int64_t nStartTime = GetTime();

View File

@ -30,18 +30,6 @@
#include <string> #include <string>
#include <vector> #include <vector>
void ProcessMessage(
CNode& pfrom,
const std::string& msg_type,
CDataStream& vRecv,
const std::chrono::microseconds time_received,
const CChainParams& chainparams,
ChainstateManager& chainman,
CTxMemPool& mempool,
CConnman& connman,
BanMan* banman,
const std::atomic<bool>& interruptMsgProc);
namespace { namespace {
#ifdef MESSAGE_TYPE #ifdef MESSAGE_TYPE
@ -87,10 +75,9 @@ void test_one_input(const std::vector<uint8_t>& buffer)
connman.AddTestNode(p2p_node); connman.AddTestNode(p2p_node);
g_setup->m_node.peer_logic->InitializeNode(&p2p_node); g_setup->m_node.peer_logic->InitializeNode(&p2p_node);
try { try {
ProcessMessage(p2p_node, random_message_type, random_bytes_data_stream, GetTime<std::chrono::microseconds>(), g_setup->m_node.peer_logic->ProcessMessage(p2p_node, random_message_type, random_bytes_data_stream,
Params(), *g_setup->m_node.chainman, *g_setup->m_node.mempool, GetTime<std::chrono::microseconds>(), Params(),
*g_setup->m_node.connman, g_setup->m_node.banman.get(), std::atomic<bool>{false});
std::atomic<bool>{false});
} catch (const std::ios_base::failure&) { } catch (const std::ios_base::failure&) {
} }
SyncWithValidationInterfaceQueue(); SyncWithValidationInterfaceQueue();

View File

@ -168,7 +168,7 @@ TestingSetup::TestingSetup(const std::string& chainName, const std::vector<const
m_node.mempool->setSanityCheck(1.0); m_node.mempool->setSanityCheck(1.0);
m_node.banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME); m_node.banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME);
m_node.connman = MakeUnique<CConnman>(0x1337, 0x1337); // Deterministic randomness for tests. m_node.connman = MakeUnique<CConnman>(0x1337, 0x1337); // Deterministic randomness for tests.
m_node.peer_logic = MakeUnique<PeerLogicValidation>(m_node.connman.get(), m_node.banman.get(), *m_node.scheduler, *m_node.chainman, *m_node.mempool); m_node.peer_logic = MakeUnique<PeerLogicValidation>(*m_node.connman, m_node.banman.get(), *m_node.scheduler, *m_node.chainman, *m_node.mempool);
{ {
CConnman::Options options; CConnman::Options options;
options.m_msgproc = m_node.peer_logic.get(); options.m_msgproc = m_node.peer_logic.get();