30 #include <condition_variable> 33 #include <arpa/inet.h> 41 static const int PING_INTERVAL = 2 * 60;
43 static const int TIMEOUT_INTERVAL = 20 * 60;
45 static const int FEELER_INTERVAL = 120;
47 static const unsigned int MAX_INV_SZ = 50000;
49 static const unsigned int MAX_LOCATOR_SZ = 101;
51 static const unsigned int MAX_ADDR_TO_SEND = 1000;
53 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 4 * 1000 * 1000;
55 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
57 static const int MAX_OUTBOUND_CONNECTIONS = 8;
59 static const int MAX_ADDNODE_CONNECTIONS = 8;
61 static const bool DEFAULT_LISTEN =
true;
64 static const bool DEFAULT_UPNP =
USE_UPNP;
66 static const bool DEFAULT_UPNP =
false;
69 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
71 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
73 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
75 static const uint64_t DEFAULT_MAX_UPLOAD_TARGET = 0;
77 static const uint64_t MAX_UPLOAD_TIMEFRAME = 60 * 60 * 24;
79 static const bool DEFAULT_BLOCKSONLY =
false;
81 static const bool DEFAULT_FORCEDNSSEED =
false;
82 static const size_t DEFAULT_MAXRECEIVEBUFFER = 5 * 1000;
83 static const size_t DEFAULT_MAXSENDBUFFER = 1 * 1000;
86 static const unsigned int DEFAULT_MISBEHAVING_BANTIME = 60 * 60 * 24;
110 std::vector<unsigned char>
data;
172 CConnman(uint64_t seed0, uint64_t seed1);
180 void OpenNetworkConnection(
const CAddress& addrConnect,
bool fCountFailure,
CSemaphoreGrant *grantOutbound =
nullptr,
const char *strDest =
nullptr,
bool fOneShot =
false,
bool fFeeler =
false,
bool manual_connection =
false);
187 template<
typename Callable>
191 for (
auto&& node :
vNodes) {
197 template<
typename Callable>
201 for (
auto&& node :
vNodes) {
207 template<
typename Callable,
typename CallableAfter>
211 for (
auto&& node :
vNodes) {
218 template<
typename Callable,
typename CallableAfter>
222 for (
auto&& node :
vNodes) {
250 void Ban(
const CNetAddr& netAddr,
const BanReason& reason, int64_t bantimeoffset = 0,
bool sinceUnixEpoch =
false);
251 void Ban(
const CSubNet& subNet,
const BanReason& reason, int64_t bantimeoffset = 0,
bool sinceUnixEpoch =
false);
273 bool AddNode(
const std::string& node);
334 bool InitBinds(
const std::vector<CService>& binds,
const std::vector<CService>& whiteBinds);
458 extern std::unique_ptr<CConnman>
g_connman;
473 while (first != last) {
474 if (!(*first))
return false;
542 extern std::map<CNetAddr, LocalServiceInfo>
mapLocalHost;
620 int readHeader(
const char *pch,
unsigned int nBytes);
621 int readData(
const char *pch,
unsigned int nBytes);
749 CNode(
NodeId id,
ServiceFlags nLocalServicesIn,
int nMyStartingHeightIn,
SOCKET hSocketIn,
const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn,
const CAddress &addrBindIn,
const std::string &addrNameIn =
"",
bool fInboundIn =
false);
789 bool ReceiveMsgBytes(
const char *pch,
unsigned int nBytes,
bool& complete);
888 #endif // BITCOIN_NET_H std::vector< CService > vBinds
std::atomic< bool > flagInterruptMsgProc
uint64_t CalculateKeyedNetGroup(const CAddress &ad) const
std::unique_ptr< CConnman > g_connman
CNode(NodeId id, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress &addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string &addrNameIn="", bool fInboundIn=false)
bool BannedSetIsDirty()
check is the banlist has unwritten changes
std::vector< CSubNet > vWhitelistedRange
std::atomic< uint64_t > nPingNonceSent
bool IsReachable(enum Network net)
check whether a given network is one we can probably connect to
CCriticalSection cs_addrName
std::atomic_bool fPauseSend
void ThreadOpenAddedConnections()
void SetBannedSetDirty(bool dirty=true)
set the "dirty" flag for the banlist
int64_t nextSendTimeFeeFilter
int GetSendVersion() const
mapMsgCmdSize mapRecvBytesPerMsgCmd
void SetBanned(const banmap_t &banmap)
std::atomic< bool > fNetworkActive
bool fMsgProcWake
flag for waking the message processor.
ServiceFlags
nServices flags
CCriticalSection cs_filter
CConnman(uint64_t seed0, uint64_t seed1)
STL-like map container that only keeps the N elements with the highest value.
size_t GetAddressCount() const
std::atomic< int > nBestHeight
void WakeMessageHandler()
void SetServices(const CService &addr, ServiceFlags nServices)
std::list< CNetMessage > vProcessMsg
const uint64_t nKeyedNetGroup
void SweepBanned()
clean unused entries (if bantime has expired)
bool SeenLocal(const CService &addr)
vote for a local address
bool ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool &complete)
CNode & operator=(const CNode &)=delete
int GetRecvVersion() const
mapMsgCmdSize mapSendBytesPerMsgCmd
void insert(const std::vector< unsigned char > &vKey)
std::vector< unsigned char > data
unsigned int nReceiveFloodSize
mapMsgCmdSize mapSendBytesPerMsgCmd
CClientUIInterface * uiInterface
void resize(size_type n, value_type c=0)
std::vector< uint256 > vInventoryBlockToSend
CCriticalSection cs_hSocket
void AskFor(const CInv &inv)
uint64_t randrange(uint64_t range)
Generate a random integer in the range [0..range).
CCriticalSection cs_SubVer
bool GetTryNewOutboundPeer()
std::atomic< int64_t > m_next_send_inv_to_incoming
CCriticalSection cs_addrLocal
RAII-style semaphore lock.
friend struct CConnmanTest
bool Unban(const CNetAddr &ip)
uint64_t GetMaxOutboundTarget()
void PushMessage(CNode *pnode, CSerializedNetMsg &&msg)
std::unique_ptr< CBloomFilter > pfilter
void SetMaxOutboundTimeframe(uint64_t timeframe)
set the timeframe for the max outbound target
Interface for message handling.
void SetVersion(int nVersionIn)
RollingBloomFilter is a probabilistic "keep track of most recently inserted" set. ...
void GetBanned(banmap_t &banmap)
NetEventsInterface * m_msgproc
std::atomic< int64_t > nPingUsecStart
CCriticalSection cs_vNodes
CSerializedNetMsg()=default
CCriticalSection cs_feeFilter
void OpenNetworkConnection(const CAddress &addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound=nullptr, const char *strDest=nullptr, bool fOneShot=false, bool fFeeler=false, bool manual_connection=false)
void AdvertiseLocal(CNode *pnode)
Double ended buffer combining vector and stream-like interfaces.
CCriticalSection cs_vAddedNodes
void SetTryNewOutboundPeer(bool flag)
ListenSocket(SOCKET socket_, bool whitelisted_)
CCriticalSection cs_inventory
uint64_t GetLocalNonce() const
std::map< CNetAddr, LocalServiceInfo > mapLocalHost
std::set< uint256 > setInventoryTxToSend
void ThreadSocketHandler()
std::vector< CAddress > vAddrToSend
std::vector< CService > vWhiteBinds
virtual bool SendMessages(CNode *pnode)=0
size_t GetNodeCount(NumConnections num)
std::atomic< int > nStartingHeight
void PushAddress(const CAddress &_addr, FastRandomContext &insecure_rand)
void SetRecvVersion(int nVersionIn)
std::atomic< int64_t > timeLastMempoolReq
void AddOneShot(const std::string &strDest)
Signals for UI communication.
std::list< CNetMessage > vRecvMsg
CNetMessage(const CMessageHeader::MessageStartChars &pchMessageStartIn, int nTypeIn, int nVersionIn)
void NotifyNumConnectionsChanged()
void PushInventory(const CInv &inv)
void SetMaxOutboundTarget(uint64_t limit)
set the max outbound target in bytes
void RecordBytesSent(uint64_t bytes)
std::atomic< ServiceFlags > nServices
void SetAddrLocal(const CService &addrLocalIn)
May not be called more than once.
int64_t nNextLocalAddrSend
std::deque< CInv > vRecvGetData
uint64_t GetMaxOutboundTimeframe()
bool ForNode(NodeId id, std::function< bool(CNode *pnode)> func)
ServiceFlags nLocalServices
Services this instance offers.
bool contains(const std::vector< unsigned char > &vKey) const
bool IsWhitelistedRange(const CNetAddr &addr)
bool DisconnectNode(const std::string &node)
std::set< uint256 > setKnown
bool operator()(I first, I last) const
Stochastical (IP) address manager.
int64_t CAmount
Amount in satoshis (Can be negative)
std::atomic< int64_t > nLastSend
void RecordBytesRecv(uint64_t bytes)
std::atomic< int64_t > nPingUsecTime
std::atomic< int64_t > nMinPingUsecTime
int GetMyStartingHeight() const
void Ban(const CNetAddr &netAddr, const BanReason &reason, int64_t bantimeoffset=0, bool sinceUnixEpoch=false)
ServiceFlags GetLocalServices() const
std::map< CSubNet, CBanEntry > banmap_t
void CloseSocketDisconnect()
uint64_t GetOutboundTargetBytesLeft()
response the bytes left in the current max outbound cycle
bool GetLocal(CService &addr, const CNetAddr *paddrPeer=nullptr)
static bool NodeFullyConnected(const CNode *pnode)
unsigned int nPrevNodeCount
bool AddNode(const std::string &node)
std::condition_variable condMsgProc
CService GetAddrLocal() const
uint64_t GetMaxOutboundTimeLeftInCycle()
response the time in second left in the current max outbound cycle
void InactivityCheck(CNode *pnode)
std::atomic< int64_t > nLastRecv
const uint64_t nSeed0
SipHasher seeds for deterministic randomness.
bool InitBinds(const std::vector< CService > &binds, const std::vector< CService > &whiteBinds)
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
std::thread threadOpenAddedConnections
CNode * FindNode(const CNetAddr &ip)
std::vector< CNode * > vNodes
ServiceFlags GetLocalServices() const
bool IsPeerAddrLocalGood(CNode *pnode)
std::deque< std::string > vOneShots
NetEventsInterface * m_msgproc
A combination of a network address (CNetAddr) and a (TCP) port.
std::vector< std::string > vSeedNodes
int64_t PoissonNextSendInbound(int64_t now, int average_interval_seconds)
Attempts to obfuscate tx time through exponentially distributed emitting.
bool OutboundTargetReached(bool historicalBlockServingLimit)
check if the outbound target is reached
std::vector< std::string > m_specified_outgoing
std::vector< CAddress > GetAddresses()
CRollingBloomFilter filterInventoryKnown
std::unique_ptr< CSemaphore > semOutbound
void ThreadOpenConnections(std::vector< std::string > connect)
std::thread threadMessageHandler
void ForEachNodeThen(Callable &&pre, CallableAfter &&post)
~NetEventsInterface()=default
Protected destructor so that instances can only be deleted by derived classes.
A CService with information about it as peer.
bool Start(CScheduler &scheduler, const Options &options)
std::vector< unsigned char > GetKey() const
void MaybeSetAddrName(const std::string &addrNameIn)
Sets the addrName only if it was not previously set.
uint64_t GetTotalBytesRecv()
std::vector< uint256 > vBlockHashesToAnnounce
std::atomic_bool m_try_another_outbound_peer
flag for deciding to connect to an extra outbound peer, in excess of nMaxOutbound This takes the plac...
virtual void FinalizeNode(NodeId id, bool &update_connection_time)=0
void SetNetworkActive(bool active)
void AddNewAddresses(const std::vector< CAddress > &vAddr, const CAddress &addrFrom, int64_t nTimePenalty=0)
bool GetNetworkActive() const
CClientUIInterface * clientInterface
void GetNodeStats(std::vector< CNodeStats > &vstats)
CSipHasher GetDeterministicRandomizer(uint64_t id) const
Get a unique deterministic randomizer.
std::atomic_bool fDisconnect
void SetLimited(enum Network net, bool fLimited=true)
Make a particular network entirely off-limits (no automatic connects to it)
void ForEachNode(Callable &&func)
limitedmap< uint256, int64_t > mapAlreadyAskedFor
CCriticalSection cs_vOneShots
CRollingBloomFilter addrKnown
bool IsBanned(CNetAddr ip)
CCriticalSection cs_setBanned
unsigned int GetReceiveFloodSize() const
int readData(const char *pch, unsigned int nBytes)
void DeleteNode(CNode *pnode)
bool CheckIncomingNonce(uint64_t nonce)
std::atomic< int > nRefCount
const int64_t nTimeConnected
uint64_t nMaxOutboundTimeframe
std::atomic< NodeId > nLastNodeId
bool RemoveAddedNode(const std::string &node)
IP address (IPv6, or IPv4 using mapped IPv6 range (::FFFF:0:0/96))
CCriticalSection cs_vRecv
std::list< CNode * > vNodesDisconnected
std::atomic< bool > fPingQueued
void RemoveLocal(const CService &addr)
int GetBestHeight() const
void AddInventoryKnown(const CInv &inv)
bool Bind(const CService &addr, unsigned int flags)
void ForEachNode(Callable &&func) const
std::atomic< int64_t > nLastTXTime
std::vector< CSubNet > vWhitelistedRange
std::thread threadOpenConnections
bool AttemptToEvictConnection()
Try to find a connection to evict when the node is full.
CSemaphoreGrant grantOutbound
std::map< std::string, uint64_t > mapMsgCmdSize
bool fAddressesInitialized
std::thread threadDNSAddressSeed
ServiceFlags nLocalServices
std::deque< std::vector< unsigned char > > vSendMsg
uint64_t nMaxOutboundLimit
size_t SocketSendData(CNode *pnode) const
std::vector< std::string > m_added_nodes
CCriticalSection cs_vProcessMsg
void SetSendVersion(int nVersionIn)
mapMsgCmdSize mapRecvBytesPerMsgCmd
int64_t PoissonNextSend(int64_t now, int average_interval_seconds)
Return a timestamp in the future (in microseconds) for exponentially distributed events.
std::vector< ListenSocket > vhListenSocket
void SetBestHeight(int height)
CAmount lastSentFeeFilter
std::atomic< int64_t > nTimeOffset
void PushBlockHash(const uint256 &hash)
void ForEachNodeThen(Callable &&pre, CallableAfter &&post) const
CCriticalSection cs_totalBytesSent
std::atomic_bool fSuccessfullyConnected
void ThreadMessageHandler()
uint64_t nTotalBytesRecv GUARDED_BY(cs_totalBytesRecv)
std::atomic< int > nVersion
A hasher class for BSHA3's 256-bit hash (double SHA-3).
unsigned int nSendBufferMaxSize
const uint64_t nLocalHostNonce
unsigned int nSendBufferMaxSize
int readHeader(const char *pch, unsigned int nBytes)
const ServiceFlags nLocalServices
int GetExtraOutboundCount()
uint64_t GetTotalBytesSent()
void AcceptConnection(const ListenSocket &hListenSocket)
std::string strSubVersion
Subversion as sent to the P2P network in version messages.
CCriticalSection cs_sendProcessing
void MarkAddressGood(const CAddress &addr)
Information about a peer.
std::thread threadSocketHandler
virtual void InitializeNode(CNode *pnode)=0
std::string GetAddrName() const
CCriticalSection cs_vSend
CNode * ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure, bool manual_connection)
void AddAddressKnown(const CAddress &_addr)
void copyStats(CNodeStats &stats)
CSerializedNetMsg & operator=(CSerializedNetMsg &&)=default
std::atomic_bool fPauseRecv
std::unique_ptr< CSemaphore > semAddnode
void Init(const Options &connOptions)
CThreadInterrupt interruptNet
CCriticalSection cs_totalBytesRecv
CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
bool AddLocal(const CService &addr, int nScore=LOCAL_NONE)
bool m_use_addrman_outgoing
std::atomic< int > nRecvVersion
std::atomic< int64_t > nLastBlockTime
bool IsLocal(const CService &addr)
check whether a given address is potentially local
std::multimap< int64_t, CInv > mapAskFor
CCriticalSection cs_mapLocalHost
bool GetUseAddrmanOutgoing() const
std::vector< AddedNodeInfo > GetAddedNodeInfo()
const uint256 & GetMessageHash() const
unsigned short GetListenPort()
const int nMyStartingHeight
bool m_use_addrman_outgoing
bool IsLimited(enum Network net)
virtual bool ProcessMessages(CNode *pnode, std::atomic< bool > &interrupt)=0
std::set< uint256 > setAskFor
unsigned int nReceiveFloodSize
bool BindListenPort(const CService &bindAddr, std::string &strError, bool fWhitelisted=false)
void ThreadDNSAddressSeed()