Merge #11221: Refactor: simpler read
[bitcoinplatinum.git] / src / net.cpp
blob935cb8190171f0dacafbf6cad5dafc4166e24cb0
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
8 #endif
10 #include "net.h"
12 #include "addrman.h"
13 #include "chainparams.h"
14 #include "clientversion.h"
15 #include "consensus/consensus.h"
16 #include "crypto/common.h"
17 #include "crypto/sha256.h"
18 #include "hash.h"
19 #include "primitives/transaction.h"
20 #include "netbase.h"
21 #include "scheduler.h"
22 #include "ui_interface.h"
23 #include "utilstrencodings.h"
25 #ifdef WIN32
26 #include <string.h>
27 #else
28 #include <fcntl.h>
29 #endif
31 #ifdef USE_UPNP
32 #include <miniupnpc/miniupnpc.h>
33 #include <miniupnpc/miniwget.h>
34 #include <miniupnpc/upnpcommands.h>
35 #include <miniupnpc/upnperrors.h>
36 #endif
39 #include <math.h>
41 // Dump addresses to peers.dat and banlist.dat every 15 minutes (900s)
42 #define DUMP_ADDRESSES_INTERVAL 900
44 // We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
45 #define FEELER_SLEEP_WINDOW 1
47 #if !defined(HAVE_MSG_NOSIGNAL)
48 #define MSG_NOSIGNAL 0
49 #endif
51 // MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0
52 #if !defined(HAVE_MSG_DONTWAIT)
53 #define MSG_DONTWAIT 0
54 #endif
56 // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
57 // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
58 #ifdef WIN32
59 #ifndef PROTECTION_LEVEL_UNRESTRICTED
60 #define PROTECTION_LEVEL_UNRESTRICTED 10
61 #endif
62 #ifndef IPV6_PROTECTION_LEVEL
63 #define IPV6_PROTECTION_LEVEL 23
64 #endif
65 #endif
67 /** Used to pass flags to the Bind() function */
68 enum BindFlags {
69 BF_NONE = 0,
70 BF_EXPLICIT = (1U << 0),
71 BF_REPORT_ERROR = (1U << 1),
72 BF_WHITELIST = (1U << 2),
75 const static std::string NET_MESSAGE_COMMAND_OTHER = "*other*";
77 static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
78 static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
80 // Global state variables
82 bool fDiscover = true;
83 bool fListen = true;
84 bool fRelayTxes = true;
85 CCriticalSection cs_mapLocalHost;
86 std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
87 static bool vfLimited[NET_MAX] = {};
88 std::string strSubVersion;
90 limitedmap<uint256, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
92 void CConnman::AddOneShot(const std::string& strDest)
94 LOCK(cs_vOneShots);
95 vOneShots.push_back(strDest);
98 unsigned short GetListenPort()
100 return (unsigned short)(gArgs.GetArg("-port", Params().GetDefaultPort()));
103 // find 'best' local address for a particular peer
104 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
106 if (!fListen)
107 return false;
109 int nBestScore = -1;
110 int nBestReachability = -1;
112 LOCK(cs_mapLocalHost);
113 for (std::map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
115 int nScore = (*it).second.nScore;
116 int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
117 if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
119 addr = CService((*it).first, (*it).second.nPort);
120 nBestReachability = nReachability;
121 nBestScore = nScore;
125 return nBestScore >= 0;
128 //! Convert the pnSeeds6 array into usable address objects.
129 static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn)
131 // It'll only connect to one or two seed nodes because once it connects,
132 // it'll get a pile of addresses with newer timestamps.
133 // Seed nodes are given a random 'last seen time' of between one and two
134 // weeks ago.
135 const int64_t nOneWeek = 7*24*60*60;
136 std::vector<CAddress> vSeedsOut;
137 vSeedsOut.reserve(vSeedsIn.size());
138 for (const auto& seed_in : vSeedsIn) {
139 struct in6_addr ip;
140 memcpy(&ip, seed_in.addr, sizeof(ip));
141 CAddress addr(CService(ip, seed_in.port), NODE_NETWORK);
142 addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
143 vSeedsOut.push_back(addr);
145 return vSeedsOut;
148 // get best local address for a particular peer as a CAddress
149 // Otherwise, return the unroutable 0.0.0.0 but filled in with
150 // the normal parameters, since the IP may be changed to a useful
151 // one by discovery.
152 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
154 CAddress ret(CService(CNetAddr(),GetListenPort()), nLocalServices);
155 CService addr;
156 if (GetLocal(addr, paddrPeer))
158 ret = CAddress(addr, nLocalServices);
160 ret.nTime = GetAdjustedTime();
161 return ret;
164 int GetnScore(const CService& addr)
166 LOCK(cs_mapLocalHost);
167 if (mapLocalHost.count(addr) == LOCAL_NONE)
168 return 0;
169 return mapLocalHost[addr].nScore;
172 // Is our peer's addrLocal potentially useful as an external IP source?
173 bool IsPeerAddrLocalGood(CNode *pnode)
175 CService addrLocal = pnode->GetAddrLocal();
176 return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
177 !IsLimited(addrLocal.GetNetwork());
180 // pushes our own address to a peer
181 void AdvertiseLocal(CNode *pnode)
183 if (fListen && pnode->fSuccessfullyConnected)
185 CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
186 // If discovery is enabled, sometimes give our peer the address it
187 // tells us that it sees us as in case it has a better idea of our
188 // address than we do.
189 if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
190 GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0))
192 addrLocal.SetIP(pnode->GetAddrLocal());
194 if (addrLocal.IsRoutable())
196 LogPrint(BCLog::NET, "AdvertiseLocal: advertising address %s\n", addrLocal.ToString());
197 FastRandomContext insecure_rand;
198 pnode->PushAddress(addrLocal, insecure_rand);
203 // learn a new local address
204 bool AddLocal(const CService& addr, int nScore)
206 if (!addr.IsRoutable())
207 return false;
209 if (!fDiscover && nScore < LOCAL_MANUAL)
210 return false;
212 if (IsLimited(addr))
213 return false;
215 LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
218 LOCK(cs_mapLocalHost);
219 bool fAlready = mapLocalHost.count(addr) > 0;
220 LocalServiceInfo &info = mapLocalHost[addr];
221 if (!fAlready || nScore >= info.nScore) {
222 info.nScore = nScore + (fAlready ? 1 : 0);
223 info.nPort = addr.GetPort();
227 return true;
230 bool AddLocal(const CNetAddr &addr, int nScore)
232 return AddLocal(CService(addr, GetListenPort()), nScore);
235 bool RemoveLocal(const CService& addr)
237 LOCK(cs_mapLocalHost);
238 LogPrintf("RemoveLocal(%s)\n", addr.ToString());
239 mapLocalHost.erase(addr);
240 return true;
243 /** Make a particular network entirely off-limits (no automatic connects to it) */
244 void SetLimited(enum Network net, bool fLimited)
246 if (net == NET_UNROUTABLE || net == NET_INTERNAL)
247 return;
248 LOCK(cs_mapLocalHost);
249 vfLimited[net] = fLimited;
252 bool IsLimited(enum Network net)
254 LOCK(cs_mapLocalHost);
255 return vfLimited[net];
258 bool IsLimited(const CNetAddr &addr)
260 return IsLimited(addr.GetNetwork());
263 /** vote for a local address */
264 bool SeenLocal(const CService& addr)
267 LOCK(cs_mapLocalHost);
268 if (mapLocalHost.count(addr) == 0)
269 return false;
270 mapLocalHost[addr].nScore++;
272 return true;
276 /** check whether a given address is potentially local */
277 bool IsLocal(const CService& addr)
279 LOCK(cs_mapLocalHost);
280 return mapLocalHost.count(addr) > 0;
283 /** check whether a given network is one we can probably connect to */
284 bool IsReachable(enum Network net)
286 LOCK(cs_mapLocalHost);
287 return !vfLimited[net];
290 /** check whether a given address is in a network we can probably connect to */
291 bool IsReachable(const CNetAddr& addr)
293 enum Network net = addr.GetNetwork();
294 return IsReachable(net);
298 CNode* CConnman::FindNode(const CNetAddr& ip)
300 LOCK(cs_vNodes);
301 for (CNode* pnode : vNodes) {
302 if ((CNetAddr)pnode->addr == ip) {
303 return pnode;
306 return nullptr;
309 CNode* CConnman::FindNode(const CSubNet& subNet)
311 LOCK(cs_vNodes);
312 for (CNode* pnode : vNodes) {
313 if (subNet.Match((CNetAddr)pnode->addr)) {
314 return pnode;
317 return nullptr;
320 CNode* CConnman::FindNode(const std::string& addrName)
322 LOCK(cs_vNodes);
323 for (CNode* pnode : vNodes) {
324 if (pnode->GetAddrName() == addrName) {
325 return pnode;
328 return nullptr;
331 CNode* CConnman::FindNode(const CService& addr)
333 LOCK(cs_vNodes);
334 for (CNode* pnode : vNodes) {
335 if ((CService)pnode->addr == addr) {
336 return pnode;
339 return nullptr;
342 bool CConnman::CheckIncomingNonce(uint64_t nonce)
344 LOCK(cs_vNodes);
345 for (CNode* pnode : vNodes) {
346 if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce)
347 return false;
349 return true;
352 /** Get the bind address for a socket as CAddress */
353 static CAddress GetBindAddress(SOCKET sock)
355 CAddress addr_bind;
356 struct sockaddr_storage sockaddr_bind;
357 socklen_t sockaddr_bind_len = sizeof(sockaddr_bind);
358 if (sock != INVALID_SOCKET) {
359 if (!getsockname(sock, (struct sockaddr*)&sockaddr_bind, &sockaddr_bind_len)) {
360 addr_bind.SetSockAddr((const struct sockaddr*)&sockaddr_bind);
361 } else {
362 LogPrint(BCLog::NET, "Warning: getsockname failed\n");
365 return addr_bind;
368 CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure)
370 if (pszDest == nullptr) {
371 if (IsLocal(addrConnect))
372 return nullptr;
374 // Look for an existing connection
375 CNode* pnode = FindNode((CService)addrConnect);
376 if (pnode)
378 LogPrintf("Failed to open new connection, already connected\n");
379 return nullptr;
383 /// debug print
384 LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n",
385 pszDest ? pszDest : addrConnect.ToString(),
386 pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
388 // Resolve
389 const int default_port = Params().GetDefaultPort();
390 if (pszDest) {
391 std::vector<CService> resolved;
392 if (Lookup(pszDest, resolved, default_port, fNameLookup && !HaveNameProxy(), 256) && !resolved.empty()) {
393 addrConnect = CAddress(resolved[GetRand(resolved.size())], NODE_NONE);
394 if (!addrConnect.IsValid()) {
395 LogPrint(BCLog::NET, "Resolver returned invalid address %s for %s", addrConnect.ToString(), pszDest);
396 return nullptr;
398 // It is possible that we already have a connection to the IP/port pszDest resolved to.
399 // In that case, drop the connection that was just created, and return the existing CNode instead.
400 // Also store the name we used to connect in that CNode, so that future FindNode() calls to that
401 // name catch this early.
402 LOCK(cs_vNodes);
403 CNode* pnode = FindNode((CService)addrConnect);
404 if (pnode)
406 pnode->MaybeSetAddrName(std::string(pszDest));
407 LogPrintf("Failed to open new connection, already connected\n");
408 return nullptr;
413 // Connect
414 bool connected = false;
415 SOCKET hSocket;
416 proxyType proxy;
417 if (addrConnect.IsValid()) {
418 bool proxyConnectionFailed = false;
420 if (GetProxy(addrConnect.GetNetwork(), proxy))
421 connected = ConnectThroughProxy(proxy, addrConnect.ToStringIP(), addrConnect.GetPort(), hSocket, nConnectTimeout, &proxyConnectionFailed);
422 else // no proxy needed (none set for target network)
423 connected = ConnectSocketDirectly(addrConnect, hSocket, nConnectTimeout);
424 if (!proxyConnectionFailed) {
425 // If a connection to the node was attempted, and failure (if any) is not caused by a problem connecting to
426 // the proxy, mark this as an attempt.
427 addrman.Attempt(addrConnect, fCountFailure);
429 } else if (pszDest && GetNameProxy(proxy)) {
430 std::string host;
431 int port = default_port;
432 SplitHostPort(std::string(pszDest), port, host);
433 connected = ConnectThroughProxy(proxy, host, port, hSocket, nConnectTimeout, nullptr);
435 if (connected) {
436 if (!IsSelectableSocket(hSocket)) {
437 LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
438 CloseSocket(hSocket);
439 return nullptr;
442 // Add node
443 NodeId id = GetNewNodeId();
444 uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
445 CAddress addr_bind = GetBindAddress(hSocket);
446 CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, addr_bind, pszDest ? pszDest : "", false);
447 pnode->AddRef();
449 return pnode;
452 return nullptr;
455 void CConnman::DumpBanlist()
457 SweepBanned(); // clean unused entries (if bantime has expired)
459 if (!BannedSetIsDirty())
460 return;
462 int64_t nStart = GetTimeMillis();
464 CBanDB bandb;
465 banmap_t banmap;
466 GetBanned(banmap);
467 if (bandb.Write(banmap)) {
468 SetBannedSetDirty(false);
471 LogPrint(BCLog::NET, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
472 banmap.size(), GetTimeMillis() - nStart);
475 void CNode::CloseSocketDisconnect()
477 fDisconnect = true;
478 LOCK(cs_hSocket);
479 if (hSocket != INVALID_SOCKET)
481 LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
482 CloseSocket(hSocket);
486 void CConnman::ClearBanned()
489 LOCK(cs_setBanned);
490 setBanned.clear();
491 setBannedIsDirty = true;
493 DumpBanlist(); //store banlist to disk
494 if(clientInterface)
495 clientInterface->BannedListChanged();
498 bool CConnman::IsBanned(CNetAddr ip)
500 LOCK(cs_setBanned);
501 for (const auto& it : setBanned) {
502 CSubNet subNet = it.first;
503 CBanEntry banEntry = it.second;
505 if (subNet.Match(ip) && GetTime() < banEntry.nBanUntil) {
506 return true;
509 return false;
512 bool CConnman::IsBanned(CSubNet subnet)
514 LOCK(cs_setBanned);
515 banmap_t::iterator i = setBanned.find(subnet);
516 if (i != setBanned.end())
518 CBanEntry banEntry = (*i).second;
519 if (GetTime() < banEntry.nBanUntil) {
520 return true;
523 return false;
526 void CConnman::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
527 CSubNet subNet(addr);
528 Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
531 void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
532 CBanEntry banEntry(GetTime());
533 banEntry.banReason = banReason;
534 if (bantimeoffset <= 0)
536 bantimeoffset = gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
537 sinceUnixEpoch = false;
539 banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
542 LOCK(cs_setBanned);
543 if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
544 setBanned[subNet] = banEntry;
545 setBannedIsDirty = true;
547 else
548 return;
550 if(clientInterface)
551 clientInterface->BannedListChanged();
553 LOCK(cs_vNodes);
554 for (CNode* pnode : vNodes) {
555 if (subNet.Match((CNetAddr)pnode->addr))
556 pnode->fDisconnect = true;
559 if(banReason == BanReasonManuallyAdded)
560 DumpBanlist(); //store banlist to disk immediately if user requested ban
563 bool CConnman::Unban(const CNetAddr &addr) {
564 CSubNet subNet(addr);
565 return Unban(subNet);
568 bool CConnman::Unban(const CSubNet &subNet) {
570 LOCK(cs_setBanned);
571 if (!setBanned.erase(subNet))
572 return false;
573 setBannedIsDirty = true;
575 if(clientInterface)
576 clientInterface->BannedListChanged();
577 DumpBanlist(); //store banlist to disk immediately
578 return true;
581 void CConnman::GetBanned(banmap_t &banMap)
583 LOCK(cs_setBanned);
584 // Sweep the banlist so expired bans are not returned
585 SweepBanned();
586 banMap = setBanned; //create a thread safe copy
589 void CConnman::SetBanned(const banmap_t &banMap)
591 LOCK(cs_setBanned);
592 setBanned = banMap;
593 setBannedIsDirty = true;
596 void CConnman::SweepBanned()
598 int64_t now = GetTime();
600 LOCK(cs_setBanned);
601 banmap_t::iterator it = setBanned.begin();
602 while(it != setBanned.end())
604 CSubNet subNet = (*it).first;
605 CBanEntry banEntry = (*it).second;
606 if(now > banEntry.nBanUntil)
608 setBanned.erase(it++);
609 setBannedIsDirty = true;
610 LogPrint(BCLog::NET, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
612 else
613 ++it;
617 bool CConnman::BannedSetIsDirty()
619 LOCK(cs_setBanned);
620 return setBannedIsDirty;
623 void CConnman::SetBannedSetDirty(bool dirty)
625 LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
626 setBannedIsDirty = dirty;
630 bool CConnman::IsWhitelistedRange(const CNetAddr &addr) {
631 for (const CSubNet& subnet : vWhitelistedRange) {
632 if (subnet.Match(addr))
633 return true;
635 return false;
638 std::string CNode::GetAddrName() const {
639 LOCK(cs_addrName);
640 return addrName;
643 void CNode::MaybeSetAddrName(const std::string& addrNameIn) {
644 LOCK(cs_addrName);
645 if (addrName.empty()) {
646 addrName = addrNameIn;
650 CService CNode::GetAddrLocal() const {
651 LOCK(cs_addrLocal);
652 return addrLocal;
655 void CNode::SetAddrLocal(const CService& addrLocalIn) {
656 LOCK(cs_addrLocal);
657 if (addrLocal.IsValid()) {
658 error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString());
659 } else {
660 addrLocal = addrLocalIn;
664 #undef X
665 #define X(name) stats.name = name
666 void CNode::copyStats(CNodeStats &stats)
668 stats.nodeid = this->GetId();
669 X(nServices);
670 X(addr);
671 X(addrBind);
673 LOCK(cs_filter);
674 X(fRelayTxes);
676 X(nLastSend);
677 X(nLastRecv);
678 X(nTimeConnected);
679 X(nTimeOffset);
680 stats.addrName = GetAddrName();
681 X(nVersion);
683 LOCK(cs_SubVer);
684 X(cleanSubVer);
686 X(fInbound);
687 X(m_manual_connection);
688 X(nStartingHeight);
690 LOCK(cs_vSend);
691 X(mapSendBytesPerMsgCmd);
692 X(nSendBytes);
695 LOCK(cs_vRecv);
696 X(mapRecvBytesPerMsgCmd);
697 X(nRecvBytes);
699 X(fWhitelisted);
701 // It is common for nodes with good ping times to suddenly become lagged,
702 // due to a new block arriving or other large transfer.
703 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
704 // since pingtime does not update until the ping is complete, which might take a while.
705 // So, if a ping is taking an unusually long time in flight,
706 // the caller can immediately detect that this is happening.
707 int64_t nPingUsecWait = 0;
708 if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
709 nPingUsecWait = GetTimeMicros() - nPingUsecStart;
712 // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :)
713 stats.dPingTime = (((double)nPingUsecTime) / 1e6);
714 stats.dMinPing = (((double)nMinPingUsecTime) / 1e6);
715 stats.dPingWait = (((double)nPingUsecWait) / 1e6);
717 // Leave string empty if addrLocal invalid (not filled in yet)
718 CService addrLocalUnlocked = GetAddrLocal();
719 stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
721 #undef X
723 bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete)
725 complete = false;
726 int64_t nTimeMicros = GetTimeMicros();
727 LOCK(cs_vRecv);
728 nLastRecv = nTimeMicros / 1000000;
729 nRecvBytes += nBytes;
730 while (nBytes > 0) {
732 // get current incomplete message, or create a new one
733 if (vRecvMsg.empty() ||
734 vRecvMsg.back().complete())
735 vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION));
737 CNetMessage& msg = vRecvMsg.back();
739 // absorb network data
740 int handled;
741 if (!msg.in_data)
742 handled = msg.readHeader(pch, nBytes);
743 else
744 handled = msg.readData(pch, nBytes);
746 if (handled < 0)
747 return false;
749 if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
750 LogPrint(BCLog::NET, "Oversized message from peer=%i, disconnecting\n", GetId());
751 return false;
754 pch += handled;
755 nBytes -= handled;
757 if (msg.complete()) {
759 //store received bytes per message command
760 //to prevent a memory DOS, only allow valid commands
761 mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand);
762 if (i == mapRecvBytesPerMsgCmd.end())
763 i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
764 assert(i != mapRecvBytesPerMsgCmd.end());
765 i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
767 msg.nTime = nTimeMicros;
768 complete = true;
772 return true;
775 void CNode::SetSendVersion(int nVersionIn)
777 // Send version may only be changed in the version message, and
778 // only one version message is allowed per session. We can therefore
779 // treat this value as const and even atomic as long as it's only used
780 // once a version message has been successfully processed. Any attempt to
781 // set this twice is an error.
782 if (nSendVersion != 0) {
783 error("Send version already set for node: %i. Refusing to change from %i to %i", id, nSendVersion, nVersionIn);
784 } else {
785 nSendVersion = nVersionIn;
789 int CNode::GetSendVersion() const
791 // The send version should always be explicitly set to
792 // INIT_PROTO_VERSION rather than using this value until SetSendVersion
793 // has been called.
794 if (nSendVersion == 0) {
795 error("Requesting unset send version for node: %i. Using %i", id, INIT_PROTO_VERSION);
796 return INIT_PROTO_VERSION;
798 return nSendVersion;
802 int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
804 // copy data to temporary parsing buffer
805 unsigned int nRemaining = 24 - nHdrPos;
806 unsigned int nCopy = std::min(nRemaining, nBytes);
808 memcpy(&hdrbuf[nHdrPos], pch, nCopy);
809 nHdrPos += nCopy;
811 // if header incomplete, exit
812 if (nHdrPos < 24)
813 return nCopy;
815 // deserialize to CMessageHeader
816 try {
817 hdrbuf >> hdr;
819 catch (const std::exception&) {
820 return -1;
823 // reject messages larger than MAX_SIZE
824 if (hdr.nMessageSize > MAX_SIZE)
825 return -1;
827 // switch state to reading message data
828 in_data = true;
830 return nCopy;
833 int CNetMessage::readData(const char *pch, unsigned int nBytes)
835 unsigned int nRemaining = hdr.nMessageSize - nDataPos;
836 unsigned int nCopy = std::min(nRemaining, nBytes);
838 if (vRecv.size() < nDataPos + nCopy) {
839 // Allocate up to 256 KiB ahead, but never more than the total message size.
840 vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
843 hasher.Write((const unsigned char*)pch, nCopy);
844 memcpy(&vRecv[nDataPos], pch, nCopy);
845 nDataPos += nCopy;
847 return nCopy;
850 const uint256& CNetMessage::GetMessageHash() const
852 assert(complete());
853 if (data_hash.IsNull())
854 hasher.Finalize(data_hash.begin());
855 return data_hash;
866 // requires LOCK(cs_vSend)
867 size_t CConnman::SocketSendData(CNode *pnode) const
869 auto it = pnode->vSendMsg.begin();
870 size_t nSentSize = 0;
872 while (it != pnode->vSendMsg.end()) {
873 const auto &data = *it;
874 assert(data.size() > pnode->nSendOffset);
875 int nBytes = 0;
877 LOCK(pnode->cs_hSocket);
878 if (pnode->hSocket == INVALID_SOCKET)
879 break;
880 nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
882 if (nBytes > 0) {
883 pnode->nLastSend = GetSystemTimeInSeconds();
884 pnode->nSendBytes += nBytes;
885 pnode->nSendOffset += nBytes;
886 nSentSize += nBytes;
887 if (pnode->nSendOffset == data.size()) {
888 pnode->nSendOffset = 0;
889 pnode->nSendSize -= data.size();
890 pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
891 it++;
892 } else {
893 // could not send full message; stop sending more
894 break;
896 } else {
897 if (nBytes < 0) {
898 // error
899 int nErr = WSAGetLastError();
900 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
902 LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
903 pnode->CloseSocketDisconnect();
906 // couldn't send anything at all
907 break;
911 if (it == pnode->vSendMsg.end()) {
912 assert(pnode->nSendOffset == 0);
913 assert(pnode->nSendSize == 0);
915 pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
916 return nSentSize;
919 struct NodeEvictionCandidate
921 NodeId id;
922 int64_t nTimeConnected;
923 int64_t nMinPingUsecTime;
924 int64_t nLastBlockTime;
925 int64_t nLastTXTime;
926 bool fRelevantServices;
927 bool fRelayTxes;
928 bool fBloomFilter;
929 CAddress addr;
930 uint64_t nKeyedNetGroup;
933 static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
935 return a.nMinPingUsecTime > b.nMinPingUsecTime;
938 static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
940 return a.nTimeConnected > b.nTimeConnected;
943 static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
944 return a.nKeyedNetGroup < b.nKeyedNetGroup;
947 static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
949 // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
950 if (a.nLastBlockTime != b.nLastBlockTime) return a.nLastBlockTime < b.nLastBlockTime;
951 if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
952 return a.nTimeConnected > b.nTimeConnected;
955 static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
957 // There is a fall-through here because it is common for a node to have more than a few peers that have not yet relayed txn.
958 if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime;
959 if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes;
960 if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
961 return a.nTimeConnected > b.nTimeConnected;
965 //! Sort an array by the specified comparator, then erase the last K elements.
966 template<typename T, typename Comparator>
967 static void EraseLastKElements(std::vector<T> &elements, Comparator comparator, size_t k)
969 std::sort(elements.begin(), elements.end(), comparator);
970 size_t eraseSize = std::min(k, elements.size());
971 elements.erase(elements.end() - eraseSize, elements.end());
974 /** Try to find a connection to evict when the node is full.
975 * Extreme care must be taken to avoid opening the node to attacker
976 * triggered network partitioning.
977 * The strategy used here is to protect a small number of peers
978 * for each of several distinct characteristics which are difficult
979 * to forge. In order to partition a node the attacker must be
980 * simultaneously better at all of them than honest peers.
982 bool CConnman::AttemptToEvictConnection()
984 std::vector<NodeEvictionCandidate> vEvictionCandidates;
986 LOCK(cs_vNodes);
988 for (const CNode* node : vNodes) {
989 if (node->fWhitelisted)
990 continue;
991 if (!node->fInbound)
992 continue;
993 if (node->fDisconnect)
994 continue;
995 NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime,
996 node->nLastBlockTime, node->nLastTXTime,
997 HasAllDesirableServiceFlags(node->nServices),
998 node->fRelayTxes, node->pfilter != nullptr, node->addr, node->nKeyedNetGroup};
999 vEvictionCandidates.push_back(candidate);
1003 // Protect connections with certain characteristics
1005 // Deterministically select 4 peers to protect by netgroup.
1006 // An attacker cannot predict which netgroups will be protected
1007 EraseLastKElements(vEvictionCandidates, CompareNetGroupKeyed, 4);
1008 // Protect the 8 nodes with the lowest minimum ping time.
1009 // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
1010 EraseLastKElements(vEvictionCandidates, ReverseCompareNodeMinPingTime, 8);
1011 // Protect 4 nodes that most recently sent us transactions.
1012 // An attacker cannot manipulate this metric without performing useful work.
1013 EraseLastKElements(vEvictionCandidates, CompareNodeTXTime, 4);
1014 // Protect 4 nodes that most recently sent us blocks.
1015 // An attacker cannot manipulate this metric without performing useful work.
1016 EraseLastKElements(vEvictionCandidates, CompareNodeBlockTime, 4);
1017 // Protect the half of the remaining nodes which have been connected the longest.
1018 // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
1019 EraseLastKElements(vEvictionCandidates, ReverseCompareNodeTimeConnected, vEvictionCandidates.size() / 2);
1021 if (vEvictionCandidates.empty()) return false;
1023 // Identify the network group with the most connections and youngest member.
1024 // (vEvictionCandidates is already sorted by reverse connect time)
1025 uint64_t naMostConnections;
1026 unsigned int nMostConnections = 0;
1027 int64_t nMostConnectionsTime = 0;
1028 std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
1029 for (const NodeEvictionCandidate &node : vEvictionCandidates) {
1030 std::vector<NodeEvictionCandidate> &group = mapNetGroupNodes[node.nKeyedNetGroup];
1031 group.push_back(node);
1032 int64_t grouptime = group[0].nTimeConnected;
1034 if (group.size() > nMostConnections || (group.size() == nMostConnections && grouptime > nMostConnectionsTime)) {
1035 nMostConnections = group.size();
1036 nMostConnectionsTime = grouptime;
1037 naMostConnections = node.nKeyedNetGroup;
1041 // Reduce to the network group with the most connections
1042 vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
1044 // Disconnect from the network group with the most connections
1045 NodeId evicted = vEvictionCandidates.front().id;
1046 LOCK(cs_vNodes);
1047 for (CNode* pnode : vNodes) {
1048 if (pnode->GetId() == evicted) {
1049 pnode->fDisconnect = true;
1050 return true;
1053 return false;
1056 void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
1057 struct sockaddr_storage sockaddr;
1058 socklen_t len = sizeof(sockaddr);
1059 SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
1060 CAddress addr;
1061 int nInbound = 0;
1062 int nMaxInbound = nMaxConnections - (nMaxOutbound + nMaxFeeler);
1064 if (hSocket != INVALID_SOCKET) {
1065 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) {
1066 LogPrintf("Warning: Unknown socket family\n");
1070 bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr);
1072 LOCK(cs_vNodes);
1073 for (const CNode* pnode : vNodes) {
1074 if (pnode->fInbound) nInbound++;
1078 if (hSocket == INVALID_SOCKET)
1080 int nErr = WSAGetLastError();
1081 if (nErr != WSAEWOULDBLOCK)
1082 LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
1083 return;
1086 if (!fNetworkActive) {
1087 LogPrintf("connection from %s dropped: not accepting new connections\n", addr.ToString());
1088 CloseSocket(hSocket);
1089 return;
1092 if (!IsSelectableSocket(hSocket))
1094 LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
1095 CloseSocket(hSocket);
1096 return;
1099 // According to the internet TCP_NODELAY is not carried into accepted sockets
1100 // on all platforms. Set it again here just to be sure.
1101 SetSocketNoDelay(hSocket);
1103 if (IsBanned(addr) && !whitelisted)
1105 LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
1106 CloseSocket(hSocket);
1107 return;
1110 if (nInbound >= nMaxInbound)
1112 if (!AttemptToEvictConnection()) {
1113 // No connection to evict, disconnect the new connection
1114 LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1115 CloseSocket(hSocket);
1116 return;
1120 NodeId id = GetNewNodeId();
1121 uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
1122 CAddress addr_bind = GetBindAddress(hSocket);
1124 CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, addr_bind, "", true);
1125 pnode->AddRef();
1126 pnode->fWhitelisted = whitelisted;
1127 m_msgproc->InitializeNode(pnode);
1129 LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
1132 LOCK(cs_vNodes);
1133 vNodes.push_back(pnode);
1137 void CConnman::ThreadSocketHandler()
1139 unsigned int nPrevNodeCount = 0;
1140 while (!interruptNet)
1143 // Disconnect nodes
1146 LOCK(cs_vNodes);
1147 // Disconnect unused nodes
1148 std::vector<CNode*> vNodesCopy = vNodes;
1149 for (CNode* pnode : vNodesCopy)
1151 if (pnode->fDisconnect)
1153 // remove from vNodes
1154 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
1156 // release outbound grant (if any)
1157 pnode->grantOutbound.Release();
1159 // close socket and cleanup
1160 pnode->CloseSocketDisconnect();
1162 // hold in disconnected pool until all refs are released
1163 pnode->Release();
1164 vNodesDisconnected.push_back(pnode);
1169 // Delete disconnected nodes
1170 std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1171 for (CNode* pnode : vNodesDisconnectedCopy)
1173 // wait until threads are done using it
1174 if (pnode->GetRefCount() <= 0) {
1175 bool fDelete = false;
1177 TRY_LOCK(pnode->cs_inventory, lockInv);
1178 if (lockInv) {
1179 TRY_LOCK(pnode->cs_vSend, lockSend);
1180 if (lockSend) {
1181 fDelete = true;
1185 if (fDelete) {
1186 vNodesDisconnected.remove(pnode);
1187 DeleteNode(pnode);
1192 size_t vNodesSize;
1194 LOCK(cs_vNodes);
1195 vNodesSize = vNodes.size();
1197 if(vNodesSize != nPrevNodeCount) {
1198 nPrevNodeCount = vNodesSize;
1199 if(clientInterface)
1200 clientInterface->NotifyNumConnectionsChanged(nPrevNodeCount);
1204 // Find which sockets have data to receive
1206 struct timeval timeout;
1207 timeout.tv_sec = 0;
1208 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
1210 fd_set fdsetRecv;
1211 fd_set fdsetSend;
1212 fd_set fdsetError;
1213 FD_ZERO(&fdsetRecv);
1214 FD_ZERO(&fdsetSend);
1215 FD_ZERO(&fdsetError);
1216 SOCKET hSocketMax = 0;
1217 bool have_fds = false;
1219 for (const ListenSocket& hListenSocket : vhListenSocket) {
1220 FD_SET(hListenSocket.socket, &fdsetRecv);
1221 hSocketMax = std::max(hSocketMax, hListenSocket.socket);
1222 have_fds = true;
1226 LOCK(cs_vNodes);
1227 for (CNode* pnode : vNodes)
1229 // Implement the following logic:
1230 // * If there is data to send, select() for sending data. As this only
1231 // happens when optimistic write failed, we choose to first drain the
1232 // write buffer in this case before receiving more. This avoids
1233 // needlessly queueing received data, if the remote peer is not themselves
1234 // receiving data. This means properly utilizing TCP flow control signalling.
1235 // * Otherwise, if there is space left in the receive buffer, select() for
1236 // receiving data.
1237 // * Hand off all complete messages to the processor, to be handled without
1238 // blocking here.
1240 bool select_recv = !pnode->fPauseRecv;
1241 bool select_send;
1243 LOCK(pnode->cs_vSend);
1244 select_send = !pnode->vSendMsg.empty();
1247 LOCK(pnode->cs_hSocket);
1248 if (pnode->hSocket == INVALID_SOCKET)
1249 continue;
1251 FD_SET(pnode->hSocket, &fdsetError);
1252 hSocketMax = std::max(hSocketMax, pnode->hSocket);
1253 have_fds = true;
1255 if (select_send) {
1256 FD_SET(pnode->hSocket, &fdsetSend);
1257 continue;
1259 if (select_recv) {
1260 FD_SET(pnode->hSocket, &fdsetRecv);
1265 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
1266 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1267 if (interruptNet)
1268 return;
1270 if (nSelect == SOCKET_ERROR)
1272 if (have_fds)
1274 int nErr = WSAGetLastError();
1275 LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1276 for (unsigned int i = 0; i <= hSocketMax; i++)
1277 FD_SET(i, &fdsetRecv);
1279 FD_ZERO(&fdsetSend);
1280 FD_ZERO(&fdsetError);
1281 if (!interruptNet.sleep_for(std::chrono::milliseconds(timeout.tv_usec/1000)))
1282 return;
1286 // Accept new connections
1288 for (const ListenSocket& hListenSocket : vhListenSocket)
1290 if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
1292 AcceptConnection(hListenSocket);
1297 // Service each socket
1299 std::vector<CNode*> vNodesCopy;
1301 LOCK(cs_vNodes);
1302 vNodesCopy = vNodes;
1303 for (CNode* pnode : vNodesCopy)
1304 pnode->AddRef();
1306 for (CNode* pnode : vNodesCopy)
1308 if (interruptNet)
1309 return;
1312 // Receive
1314 bool recvSet = false;
1315 bool sendSet = false;
1316 bool errorSet = false;
1318 LOCK(pnode->cs_hSocket);
1319 if (pnode->hSocket == INVALID_SOCKET)
1320 continue;
1321 recvSet = FD_ISSET(pnode->hSocket, &fdsetRecv);
1322 sendSet = FD_ISSET(pnode->hSocket, &fdsetSend);
1323 errorSet = FD_ISSET(pnode->hSocket, &fdsetError);
1325 if (recvSet || errorSet)
1327 // typical socket buffer is 8K-64K
1328 char pchBuf[0x10000];
1329 int nBytes = 0;
1331 LOCK(pnode->cs_hSocket);
1332 if (pnode->hSocket == INVALID_SOCKET)
1333 continue;
1334 nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1336 if (nBytes > 0)
1338 bool notify = false;
1339 if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify))
1340 pnode->CloseSocketDisconnect();
1341 RecordBytesRecv(nBytes);
1342 if (notify) {
1343 size_t nSizeAdded = 0;
1344 auto it(pnode->vRecvMsg.begin());
1345 for (; it != pnode->vRecvMsg.end(); ++it) {
1346 if (!it->complete())
1347 break;
1348 nSizeAdded += it->vRecv.size() + CMessageHeader::HEADER_SIZE;
1351 LOCK(pnode->cs_vProcessMsg);
1352 pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
1353 pnode->nProcessQueueSize += nSizeAdded;
1354 pnode->fPauseRecv = pnode->nProcessQueueSize > nReceiveFloodSize;
1356 WakeMessageHandler();
1359 else if (nBytes == 0)
1361 // socket closed gracefully
1362 if (!pnode->fDisconnect) {
1363 LogPrint(BCLog::NET, "socket closed\n");
1365 pnode->CloseSocketDisconnect();
1367 else if (nBytes < 0)
1369 // error
1370 int nErr = WSAGetLastError();
1371 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1373 if (!pnode->fDisconnect)
1374 LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
1375 pnode->CloseSocketDisconnect();
1381 // Send
1383 if (sendSet)
1385 LOCK(pnode->cs_vSend);
1386 size_t nBytes = SocketSendData(pnode);
1387 if (nBytes) {
1388 RecordBytesSent(nBytes);
1393 // Inactivity checking
1395 int64_t nTime = GetSystemTimeInSeconds();
1396 if (nTime - pnode->nTimeConnected > 60)
1398 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1400 LogPrint(BCLog::NET, "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->GetId());
1401 pnode->fDisconnect = true;
1403 else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
1405 LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
1406 pnode->fDisconnect = true;
1408 else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
1410 LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
1411 pnode->fDisconnect = true;
1413 else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
1415 LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
1416 pnode->fDisconnect = true;
1418 else if (!pnode->fSuccessfullyConnected)
1420 LogPrintf("version handshake timeout from %d\n", pnode->GetId());
1421 pnode->fDisconnect = true;
1426 LOCK(cs_vNodes);
1427 for (CNode* pnode : vNodesCopy)
1428 pnode->Release();
1433 void CConnman::WakeMessageHandler()
1436 std::lock_guard<std::mutex> lock(mutexMsgProc);
1437 fMsgProcWake = true;
1439 condMsgProc.notify_one();
1447 #ifdef USE_UPNP
1448 void ThreadMapPort()
1450 std::string port = strprintf("%u", GetListenPort());
1451 const char * multicastif = nullptr;
1452 const char * minissdpdpath = nullptr;
1453 struct UPNPDev * devlist = nullptr;
1454 char lanaddr[64];
1456 #ifndef UPNPDISCOVER_SUCCESS
1457 /* miniupnpc 1.5 */
1458 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1459 #elif MINIUPNPC_API_VERSION < 14
1460 /* miniupnpc 1.6 */
1461 int error = 0;
1462 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1463 #else
1464 /* miniupnpc 1.9.20150730 */
1465 int error = 0;
1466 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
1467 #endif
1469 struct UPNPUrls urls;
1470 struct IGDdatas data;
1471 int r;
1473 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1474 if (r == 1)
1476 if (fDiscover) {
1477 char externalIPAddress[40];
1478 r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1479 if(r != UPNPCOMMAND_SUCCESS)
1480 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
1481 else
1483 if(externalIPAddress[0])
1485 CNetAddr resolved;
1486 if(LookupHost(externalIPAddress, resolved, false)) {
1487 LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToString().c_str());
1488 AddLocal(resolved, LOCAL_UPNP);
1491 else
1492 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1496 std::string strDesc = "Bitcoin " + FormatFullVersion();
1498 try {
1499 while (true) {
1500 #ifndef UPNPDISCOVER_SUCCESS
1501 /* miniupnpc 1.5 */
1502 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1503 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1504 #else
1505 /* miniupnpc 1.6 */
1506 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1507 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1508 #endif
1510 if(r!=UPNPCOMMAND_SUCCESS)
1511 LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1512 port, port, lanaddr, r, strupnperror(r));
1513 else
1514 LogPrintf("UPnP Port Mapping successful.\n");
1516 MilliSleep(20*60*1000); // Refresh every 20 minutes
1519 catch (const boost::thread_interrupted&)
1521 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1522 LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
1523 freeUPNPDevlist(devlist); devlist = nullptr;
1524 FreeUPNPUrls(&urls);
1525 throw;
1527 } else {
1528 LogPrintf("No valid UPnP IGDs found\n");
1529 freeUPNPDevlist(devlist); devlist = nullptr;
1530 if (r != 0)
1531 FreeUPNPUrls(&urls);
1535 void MapPort(bool fUseUPnP)
1537 static boost::thread* upnp_thread = nullptr;
1539 if (fUseUPnP)
1541 if (upnp_thread) {
1542 upnp_thread->interrupt();
1543 upnp_thread->join();
1544 delete upnp_thread;
1546 upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
1548 else if (upnp_thread) {
1549 upnp_thread->interrupt();
1550 upnp_thread->join();
1551 delete upnp_thread;
1552 upnp_thread = nullptr;
1556 #else
1557 void MapPort(bool)
1559 // Intentionally left blank.
1561 #endif
1568 static std::string GetDNSHost(const CDNSSeedData& data, ServiceFlags* requiredServiceBits)
1570 //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
1571 if (!data.supportsServiceBitsFiltering || *requiredServiceBits == NODE_NETWORK) {
1572 *requiredServiceBits = NODE_NETWORK;
1573 return data.host;
1576 // See chainparams.cpp, most dnsseeds only support one or two possible servicebits hostnames
1577 return strprintf("x%x.%s", *requiredServiceBits, data.host);
1581 void CConnman::ThreadDNSAddressSeed()
1583 // goal: only query DNS seeds if address need is acute
1584 // Avoiding DNS seeds when we don't need them improves user privacy by
1585 // creating fewer identifying DNS requests, reduces trust by giving seeds
1586 // less influence on the network topology, and reduces traffic to the seeds.
1587 if ((addrman.size() > 0) &&
1588 (!gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
1589 if (!interruptNet.sleep_for(std::chrono::seconds(11)))
1590 return;
1592 LOCK(cs_vNodes);
1593 int nRelevant = 0;
1594 for (auto pnode : vNodes) {
1595 nRelevant += pnode->fSuccessfullyConnected && !pnode->fFeeler && !pnode->fOneShot && !pnode->m_manual_connection && !pnode->fInbound;
1597 if (nRelevant >= 2) {
1598 LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1599 return;
1603 const std::vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
1604 int found = 0;
1606 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1608 for (const CDNSSeedData &seed : vSeeds) {
1609 if (interruptNet) {
1610 return;
1612 if (HaveNameProxy()) {
1613 AddOneShot(seed.host);
1614 } else {
1615 std::vector<CNetAddr> vIPs;
1616 std::vector<CAddress> vAdd;
1617 ServiceFlags requiredServiceBits = GetDesirableServiceFlags(NODE_NONE);
1618 std::string host = GetDNSHost(seed, &requiredServiceBits);
1619 CNetAddr resolveSource;
1620 if (!resolveSource.SetInternal(host)) {
1621 continue;
1623 if (LookupHost(host.c_str(), vIPs, 0, true))
1625 for (const CNetAddr& ip : vIPs)
1627 int nOneDay = 24*3600;
1628 CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
1629 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1630 vAdd.push_back(addr);
1631 found++;
1633 addrman.Add(vAdd, resolveSource);
1638 LogPrintf("%d addresses found from DNS seeds\n", found);
1652 void CConnman::DumpAddresses()
1654 int64_t nStart = GetTimeMillis();
1656 CAddrDB adb;
1657 adb.Write(addrman);
1659 LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1660 addrman.size(), GetTimeMillis() - nStart);
1663 void CConnman::DumpData()
1665 DumpAddresses();
1666 DumpBanlist();
1669 void CConnman::ProcessOneShot()
1671 std::string strDest;
1673 LOCK(cs_vOneShots);
1674 if (vOneShots.empty())
1675 return;
1676 strDest = vOneShots.front();
1677 vOneShots.pop_front();
1679 CAddress addr;
1680 CSemaphoreGrant grant(*semOutbound, true);
1681 if (grant) {
1682 if (!OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true))
1683 AddOneShot(strDest);
1687 bool CConnman::GetTryNewOutboundPeer()
1689 return m_try_another_outbound_peer;
1692 void CConnman::SetTryNewOutboundPeer(bool flag)
1694 m_try_another_outbound_peer = flag;
1695 LogPrint(BCLog::NET, "net: setting try another outbound peer=%s\n", flag ? "true" : "false");
1698 // Return the number of peers we have over our outbound connection limit
1699 // Exclude peers that are marked for disconnect, or are going to be
1700 // disconnected soon (eg one-shots and feelers)
1701 // Also exclude peers that haven't finished initial connection handshake yet
1702 // (so that we don't decide we're over our desired connection limit, and then
1703 // evict some peer that has finished the handshake)
1704 int CConnman::GetExtraOutboundCount()
1706 int nOutbound = 0;
1708 LOCK(cs_vNodes);
1709 for (CNode* pnode : vNodes) {
1710 if (!pnode->fInbound && !pnode->m_manual_connection && !pnode->fFeeler && !pnode->fDisconnect && !pnode->fOneShot && pnode->fSuccessfullyConnected) {
1711 ++nOutbound;
1715 return std::max(nOutbound - nMaxOutbound, 0);
1718 void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
1720 // Connect to specific addresses
1721 if (!connect.empty())
1723 for (int64_t nLoop = 0;; nLoop++)
1725 ProcessOneShot();
1726 for (const std::string& strAddr : connect)
1728 CAddress addr(CService(), NODE_NONE);
1729 OpenNetworkConnection(addr, false, nullptr, strAddr.c_str(), false, false, true);
1730 for (int i = 0; i < 10 && i < nLoop; i++)
1732 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1733 return;
1736 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1737 return;
1741 // Initiate network connections
1742 int64_t nStart = GetTime();
1744 // Minimum time before next feeler connection (in microseconds).
1745 int64_t nNextFeeler = PoissonNextSend(nStart*1000*1000, FEELER_INTERVAL);
1746 while (!interruptNet)
1748 ProcessOneShot();
1750 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1751 return;
1753 CSemaphoreGrant grant(*semOutbound);
1754 if (interruptNet)
1755 return;
1757 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1758 if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1759 static bool done = false;
1760 if (!done) {
1761 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1762 CNetAddr local;
1763 local.SetInternal("fixedseeds");
1764 addrman.Add(convertSeed6(Params().FixedSeeds()), local);
1765 done = true;
1770 // Choose an address to connect to based on most recently seen
1772 CAddress addrConnect;
1774 // Only connect out to one peer per network group (/16 for IPv4).
1775 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1776 int nOutbound = 0;
1777 std::set<std::vector<unsigned char> > setConnected;
1779 LOCK(cs_vNodes);
1780 for (CNode* pnode : vNodes) {
1781 if (!pnode->fInbound && !pnode->m_manual_connection) {
1782 // Netgroups for inbound and addnode peers are not excluded because our goal here
1783 // is to not use multiple of our limited outbound slots on a single netgroup
1784 // but inbound and addnode peers do not use our outbound slots. Inbound peers
1785 // also have the added issue that they're attacker controlled and could be used
1786 // to prevent us from connecting to particular hosts if we used them here.
1787 setConnected.insert(pnode->addr.GetGroup());
1788 nOutbound++;
1793 // Feeler Connections
1795 // Design goals:
1796 // * Increase the number of connectable addresses in the tried table.
1798 // Method:
1799 // * Choose a random address from new and attempt to connect to it if we can connect
1800 // successfully it is added to tried.
1801 // * Start attempting feeler connections only after node finishes making outbound
1802 // connections.
1803 // * Only make a feeler connection once every few minutes.
1805 bool fFeeler = false;
1807 if (nOutbound >= nMaxOutbound && !GetTryNewOutboundPeer()) {
1808 int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds).
1809 if (nTime > nNextFeeler) {
1810 nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
1811 fFeeler = true;
1812 } else {
1813 continue;
1817 int64_t nANow = GetAdjustedTime();
1818 int nTries = 0;
1819 while (!interruptNet)
1821 CAddrInfo addr = addrman.Select(fFeeler);
1823 // if we selected an invalid address, restart
1824 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1825 break;
1827 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1828 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1829 // already-connected network ranges, ...) before trying new addrman addresses.
1830 nTries++;
1831 if (nTries > 100)
1832 break;
1834 if (IsLimited(addr))
1835 continue;
1837 // only consider very recently tried nodes after 30 failed attempts
1838 if (nANow - addr.nLastTry < 600 && nTries < 30)
1839 continue;
1841 // for non-feelers, require all the services we'll want,
1842 // for feelers, only require they be a full node (only because most
1843 // SPV clients don't have a good address DB available)
1844 if (!fFeeler && !HasAllDesirableServiceFlags(addr.nServices)) {
1845 continue;
1846 } else if (fFeeler && !MayHaveUsefulAddressDB(addr.nServices)) {
1847 continue;
1850 // do not allow non-default ports, unless after 50 invalid addresses selected already
1851 if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1852 continue;
1854 addrConnect = addr;
1855 break;
1858 if (addrConnect.IsValid()) {
1860 if (fFeeler) {
1861 // Add small amount of random noise before connection to avoid synchronization.
1862 int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
1863 if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
1864 return;
1865 LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
1868 OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, false, fFeeler);
1873 std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
1875 std::vector<AddedNodeInfo> ret;
1877 std::list<std::string> lAddresses(0);
1879 LOCK(cs_vAddedNodes);
1880 ret.reserve(vAddedNodes.size());
1881 std::copy(vAddedNodes.cbegin(), vAddedNodes.cend(), std::back_inserter(lAddresses));
1885 // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
1886 std::map<CService, bool> mapConnected;
1887 std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
1889 LOCK(cs_vNodes);
1890 for (const CNode* pnode : vNodes) {
1891 if (pnode->addr.IsValid()) {
1892 mapConnected[pnode->addr] = pnode->fInbound;
1894 std::string addrName = pnode->GetAddrName();
1895 if (!addrName.empty()) {
1896 mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr));
1901 for (const std::string& strAddNode : lAddresses) {
1902 CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort()));
1903 if (service.IsValid()) {
1904 // strAddNode is an IP:port
1905 auto it = mapConnected.find(service);
1906 if (it != mapConnected.end()) {
1907 ret.push_back(AddedNodeInfo{strAddNode, service, true, it->second});
1908 } else {
1909 ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
1911 } else {
1912 // strAddNode is a name
1913 auto it = mapConnectedByName.find(strAddNode);
1914 if (it != mapConnectedByName.end()) {
1915 ret.push_back(AddedNodeInfo{strAddNode, it->second.second, true, it->second.first});
1916 } else {
1917 ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
1922 return ret;
1925 void CConnman::ThreadOpenAddedConnections()
1927 while (true)
1929 CSemaphoreGrant grant(*semAddnode);
1930 std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
1931 bool tried = false;
1932 for (const AddedNodeInfo& info : vInfo) {
1933 if (!info.fConnected) {
1934 if (!grant.TryAcquire()) {
1935 // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
1936 // the addednodeinfo state might change.
1937 break;
1939 tried = true;
1940 CAddress addr(CService(), NODE_NONE);
1941 OpenNetworkConnection(addr, false, &grant, info.strAddedNode.c_str(), false, false, true);
1942 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1943 return;
1946 // Retry every 60 seconds if a connection was attempted, otherwise two seconds
1947 if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
1948 return;
1952 // if successful, this moves the passed grant to the constructed node
1953 bool CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot, bool fFeeler, bool manual_connection)
1956 // Initiate outbound network connection
1958 if (interruptNet) {
1959 return false;
1961 if (!fNetworkActive) {
1962 return false;
1964 if (!pszDest) {
1965 if (IsLocal(addrConnect) ||
1966 FindNode((CNetAddr)addrConnect) || IsBanned(addrConnect) ||
1967 FindNode(addrConnect.ToStringIPPort()))
1968 return false;
1969 } else if (FindNode(std::string(pszDest)))
1970 return false;
1972 CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure);
1974 if (!pnode)
1975 return false;
1976 if (grantOutbound)
1977 grantOutbound->MoveTo(pnode->grantOutbound);
1978 if (fOneShot)
1979 pnode->fOneShot = true;
1980 if (fFeeler)
1981 pnode->fFeeler = true;
1982 if (manual_connection)
1983 pnode->m_manual_connection = true;
1985 m_msgproc->InitializeNode(pnode);
1987 LOCK(cs_vNodes);
1988 vNodes.push_back(pnode);
1991 return true;
1994 void CConnman::ThreadMessageHandler()
1996 while (!flagInterruptMsgProc)
1998 std::vector<CNode*> vNodesCopy;
2000 LOCK(cs_vNodes);
2001 vNodesCopy = vNodes;
2002 for (CNode* pnode : vNodesCopy) {
2003 pnode->AddRef();
2007 bool fMoreWork = false;
2009 for (CNode* pnode : vNodesCopy)
2011 if (pnode->fDisconnect)
2012 continue;
2014 // Receive messages
2015 bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc);
2016 fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2017 if (flagInterruptMsgProc)
2018 return;
2019 // Send messages
2021 LOCK(pnode->cs_sendProcessing);
2022 m_msgproc->SendMessages(pnode, flagInterruptMsgProc);
2025 if (flagInterruptMsgProc)
2026 return;
2030 LOCK(cs_vNodes);
2031 for (CNode* pnode : vNodesCopy)
2032 pnode->Release();
2035 std::unique_lock<std::mutex> lock(mutexMsgProc);
2036 if (!fMoreWork) {
2037 condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; });
2039 fMsgProcWake = false;
2048 bool CConnman::BindListenPort(const CService &addrBind, std::string& strError, bool fWhitelisted)
2050 strError = "";
2051 int nOne = 1;
2053 // Create socket for listening for incoming connections
2054 struct sockaddr_storage sockaddr;
2055 socklen_t len = sizeof(sockaddr);
2056 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
2058 strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
2059 LogPrintf("%s\n", strError);
2060 return false;
2063 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
2064 if (hListenSocket == INVALID_SOCKET)
2066 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2067 LogPrintf("%s\n", strError);
2068 return false;
2070 if (!IsSelectableSocket(hListenSocket))
2072 strError = "Error: Couldn't create a listenable socket for incoming connections";
2073 LogPrintf("%s\n", strError);
2074 return false;
2078 #ifndef WIN32
2079 #ifdef SO_NOSIGPIPE
2080 // Different way of disabling SIGPIPE on BSD
2081 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
2082 #endif
2083 // Allow binding if the port is still in TIME_WAIT state after
2084 // the program was closed and restarted.
2085 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
2086 // Disable Nagle's algorithm
2087 setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int));
2088 #else
2089 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int));
2090 setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int));
2091 #endif
2093 // Set to non-blocking, incoming connections will also inherit this
2094 if (!SetSocketNonBlocking(hListenSocket, true)) {
2095 CloseSocket(hListenSocket);
2096 strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
2097 LogPrintf("%s\n", strError);
2098 return false;
2101 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2102 // and enable it by default or not. Try to enable it, if possible.
2103 if (addrBind.IsIPv6()) {
2104 #ifdef IPV6_V6ONLY
2105 #ifdef WIN32
2106 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
2107 #else
2108 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
2109 #endif
2110 #endif
2111 #ifdef WIN32
2112 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2113 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
2114 #endif
2117 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
2119 int nErr = WSAGetLastError();
2120 if (nErr == WSAEADDRINUSE)
2121 strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), _(PACKAGE_NAME));
2122 else
2123 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
2124 LogPrintf("%s\n", strError);
2125 CloseSocket(hListenSocket);
2126 return false;
2128 LogPrintf("Bound to %s\n", addrBind.ToString());
2130 // Listen for incoming connections
2131 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
2133 strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2134 LogPrintf("%s\n", strError);
2135 CloseSocket(hListenSocket);
2136 return false;
2139 vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
2141 if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
2142 AddLocal(addrBind, LOCAL_BIND);
2144 return true;
2147 void Discover(boost::thread_group& threadGroup)
2149 if (!fDiscover)
2150 return;
2152 #ifdef WIN32
2153 // Get local host IP
2154 char pszHostName[256] = "";
2155 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
2157 std::vector<CNetAddr> vaddr;
2158 if (LookupHost(pszHostName, vaddr, 0, true))
2160 for (const CNetAddr &addr : vaddr)
2162 if (AddLocal(addr, LOCAL_IF))
2163 LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
2167 #else
2168 // Get local host ip
2169 struct ifaddrs* myaddrs;
2170 if (getifaddrs(&myaddrs) == 0)
2172 for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next)
2174 if (ifa->ifa_addr == nullptr) continue;
2175 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
2176 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
2177 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
2178 if (ifa->ifa_addr->sa_family == AF_INET)
2180 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
2181 CNetAddr addr(s4->sin_addr);
2182 if (AddLocal(addr, LOCAL_IF))
2183 LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2185 else if (ifa->ifa_addr->sa_family == AF_INET6)
2187 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
2188 CNetAddr addr(s6->sin6_addr);
2189 if (AddLocal(addr, LOCAL_IF))
2190 LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2193 freeifaddrs(myaddrs);
2195 #endif
2198 void CConnman::SetNetworkActive(bool active)
2200 LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active);
2202 if (fNetworkActive == active) {
2203 return;
2206 fNetworkActive = active;
2208 if (!fNetworkActive) {
2209 LOCK(cs_vNodes);
2210 // Close sockets to all nodes
2211 for (CNode* pnode : vNodes) {
2212 pnode->CloseSocketDisconnect();
2216 uiInterface.NotifyNetworkActiveChanged(fNetworkActive);
2219 CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSeed1(nSeed1In)
2221 fNetworkActive = true;
2222 setBannedIsDirty = false;
2223 fAddressesInitialized = false;
2224 nLastNodeId = 0;
2225 nSendBufferMaxSize = 0;
2226 nReceiveFloodSize = 0;
2227 semOutbound = nullptr;
2228 semAddnode = nullptr;
2229 flagInterruptMsgProc = false;
2230 SetTryNewOutboundPeer(false);
2232 Options connOptions;
2233 Init(connOptions);
2236 NodeId CConnman::GetNewNodeId()
2238 return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
2242 bool CConnman::Bind(const CService &addr, unsigned int flags) {
2243 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
2244 return false;
2245 std::string strError;
2246 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
2247 if ((flags & BF_REPORT_ERROR) && clientInterface) {
2248 clientInterface->ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR);
2250 return false;
2252 return true;
2255 bool CConnman::InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds) {
2256 bool fBound = false;
2257 for (const auto& addrBind : binds) {
2258 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
2260 for (const auto& addrBind : whiteBinds) {
2261 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
2263 if (binds.empty() && whiteBinds.empty()) {
2264 struct in_addr inaddr_any;
2265 inaddr_any.s_addr = INADDR_ANY;
2266 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
2267 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
2269 return fBound;
2272 bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
2274 Init(connOptions);
2276 nTotalBytesRecv = 0;
2277 nTotalBytesSent = 0;
2278 nMaxOutboundTotalBytesSentInCycle = 0;
2279 nMaxOutboundCycleStartTime = 0;
2281 if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds)) {
2282 if (clientInterface) {
2283 clientInterface->ThreadSafeMessageBox(
2284 _("Failed to listen on any port. Use -listen=0 if you want this."),
2285 "", CClientUIInterface::MSG_ERROR);
2287 return false;
2290 for (const auto& strDest : connOptions.vSeedNodes) {
2291 AddOneShot(strDest);
2294 if (clientInterface) {
2295 clientInterface->InitMessage(_("Loading P2P addresses..."));
2297 // Load addresses from peers.dat
2298 int64_t nStart = GetTimeMillis();
2300 CAddrDB adb;
2301 if (adb.Read(addrman))
2302 LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
2303 else {
2304 addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2305 LogPrintf("Invalid or missing peers.dat; recreating\n");
2306 DumpAddresses();
2309 if (clientInterface)
2310 clientInterface->InitMessage(_("Loading banlist..."));
2311 // Load addresses from banlist.dat
2312 nStart = GetTimeMillis();
2313 CBanDB bandb;
2314 banmap_t banmap;
2315 if (bandb.Read(banmap)) {
2316 SetBanned(banmap); // thread save setter
2317 SetBannedSetDirty(false); // no need to write down, just read data
2318 SweepBanned(); // sweep out unused entries
2320 LogPrint(BCLog::NET, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
2321 banmap.size(), GetTimeMillis() - nStart);
2322 } else {
2323 LogPrintf("Invalid or missing banlist.dat; recreating\n");
2324 SetBannedSetDirty(true); // force write
2325 DumpBanlist();
2328 uiInterface.InitMessage(_("Starting network threads..."));
2330 fAddressesInitialized = true;
2332 if (semOutbound == nullptr) {
2333 // initialize semaphore
2334 semOutbound = new CSemaphore(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
2336 if (semAddnode == nullptr) {
2337 // initialize semaphore
2338 semAddnode = new CSemaphore(nMaxAddnode);
2342 // Start threads
2344 assert(m_msgproc);
2345 InterruptSocks5(false);
2346 interruptNet.reset();
2347 flagInterruptMsgProc = false;
2350 std::unique_lock<std::mutex> lock(mutexMsgProc);
2351 fMsgProcWake = false;
2354 // Send and receive from sockets, accept connections
2355 threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
2357 if (!gArgs.GetBoolArg("-dnsseed", true))
2358 LogPrintf("DNS seeding disabled\n");
2359 else
2360 threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
2362 // Initiate outbound connections from -addnode
2363 threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
2365 if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) {
2366 if (clientInterface) {
2367 clientInterface->ThreadSafeMessageBox(
2368 _("Cannot provide specific connections and have addrman find outgoing connections at the same."),
2369 "", CClientUIInterface::MSG_ERROR);
2371 return false;
2373 if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty())
2374 threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this, connOptions.m_specified_outgoing)));
2376 // Process messages
2377 threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this)));
2379 // Dump network addresses
2380 scheduler.scheduleEvery(std::bind(&CConnman::DumpData, this), DUMP_ADDRESSES_INTERVAL * 1000);
2382 return true;
2385 class CNetCleanup
2387 public:
2388 CNetCleanup() {}
2390 ~CNetCleanup()
2392 #ifdef WIN32
2393 // Shutdown Windows Sockets
2394 WSACleanup();
2395 #endif
2398 instance_of_cnetcleanup;
2400 void CConnman::Interrupt()
2403 std::lock_guard<std::mutex> lock(mutexMsgProc);
2404 flagInterruptMsgProc = true;
2406 condMsgProc.notify_all();
2408 interruptNet();
2409 InterruptSocks5(true);
2411 if (semOutbound) {
2412 for (int i=0; i<(nMaxOutbound + nMaxFeeler); i++) {
2413 semOutbound->post();
2417 if (semAddnode) {
2418 for (int i=0; i<nMaxAddnode; i++) {
2419 semAddnode->post();
2424 void CConnman::Stop()
2426 if (threadMessageHandler.joinable())
2427 threadMessageHandler.join();
2428 if (threadOpenConnections.joinable())
2429 threadOpenConnections.join();
2430 if (threadOpenAddedConnections.joinable())
2431 threadOpenAddedConnections.join();
2432 if (threadDNSAddressSeed.joinable())
2433 threadDNSAddressSeed.join();
2434 if (threadSocketHandler.joinable())
2435 threadSocketHandler.join();
2437 if (fAddressesInitialized)
2439 DumpData();
2440 fAddressesInitialized = false;
2443 // Close sockets
2444 for (CNode* pnode : vNodes)
2445 pnode->CloseSocketDisconnect();
2446 for (ListenSocket& hListenSocket : vhListenSocket)
2447 if (hListenSocket.socket != INVALID_SOCKET)
2448 if (!CloseSocket(hListenSocket.socket))
2449 LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2451 // clean up some globals (to help leak detection)
2452 for (CNode *pnode : vNodes) {
2453 DeleteNode(pnode);
2455 for (CNode *pnode : vNodesDisconnected) {
2456 DeleteNode(pnode);
2458 vNodes.clear();
2459 vNodesDisconnected.clear();
2460 vhListenSocket.clear();
2461 delete semOutbound;
2462 semOutbound = nullptr;
2463 delete semAddnode;
2464 semAddnode = nullptr;
2467 void CConnman::DeleteNode(CNode* pnode)
2469 assert(pnode);
2470 bool fUpdateConnectionTime = false;
2471 m_msgproc->FinalizeNode(pnode->GetId(), fUpdateConnectionTime);
2472 if(fUpdateConnectionTime) {
2473 addrman.Connected(pnode->addr);
2475 delete pnode;
2478 CConnman::~CConnman()
2480 Interrupt();
2481 Stop();
2484 size_t CConnman::GetAddressCount() const
2486 return addrman.size();
2489 void CConnman::SetServices(const CService &addr, ServiceFlags nServices)
2491 addrman.SetServices(addr, nServices);
2494 void CConnman::MarkAddressGood(const CAddress& addr)
2496 addrman.Good(addr);
2499 void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
2501 addrman.Add(vAddr, addrFrom, nTimePenalty);
2504 std::vector<CAddress> CConnman::GetAddresses()
2506 return addrman.GetAddr();
2509 bool CConnman::AddNode(const std::string& strNode)
2511 LOCK(cs_vAddedNodes);
2512 for (const std::string& it : vAddedNodes) {
2513 if (strNode == it) return false;
2516 vAddedNodes.push_back(strNode);
2517 return true;
2520 bool CConnman::RemoveAddedNode(const std::string& strNode)
2522 LOCK(cs_vAddedNodes);
2523 for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
2524 if (strNode == *it) {
2525 vAddedNodes.erase(it);
2526 return true;
2529 return false;
2532 size_t CConnman::GetNodeCount(NumConnections flags)
2534 LOCK(cs_vNodes);
2535 if (flags == CConnman::CONNECTIONS_ALL) // Shortcut if we want total
2536 return vNodes.size();
2538 int nNum = 0;
2539 for (const auto& pnode : vNodes) {
2540 if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) {
2541 nNum++;
2545 return nNum;
2548 void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats)
2550 vstats.clear();
2551 LOCK(cs_vNodes);
2552 vstats.reserve(vNodes.size());
2553 for (CNode* pnode : vNodes) {
2554 vstats.emplace_back();
2555 pnode->copyStats(vstats.back());
2559 bool CConnman::DisconnectNode(const std::string& strNode)
2561 LOCK(cs_vNodes);
2562 if (CNode* pnode = FindNode(strNode)) {
2563 pnode->fDisconnect = true;
2564 return true;
2566 return false;
2568 bool CConnman::DisconnectNode(NodeId id)
2570 LOCK(cs_vNodes);
2571 for(CNode* pnode : vNodes) {
2572 if (id == pnode->GetId()) {
2573 pnode->fDisconnect = true;
2574 return true;
2577 return false;
2580 void CConnman::RecordBytesRecv(uint64_t bytes)
2582 LOCK(cs_totalBytesRecv);
2583 nTotalBytesRecv += bytes;
2586 void CConnman::RecordBytesSent(uint64_t bytes)
2588 LOCK(cs_totalBytesSent);
2589 nTotalBytesSent += bytes;
2591 uint64_t now = GetTime();
2592 if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now)
2594 // timeframe expired, reset cycle
2595 nMaxOutboundCycleStartTime = now;
2596 nMaxOutboundTotalBytesSentInCycle = 0;
2599 // TODO, exclude whitebind peers
2600 nMaxOutboundTotalBytesSentInCycle += bytes;
2603 void CConnman::SetMaxOutboundTarget(uint64_t limit)
2605 LOCK(cs_totalBytesSent);
2606 nMaxOutboundLimit = limit;
2609 uint64_t CConnman::GetMaxOutboundTarget()
2611 LOCK(cs_totalBytesSent);
2612 return nMaxOutboundLimit;
2615 uint64_t CConnman::GetMaxOutboundTimeframe()
2617 LOCK(cs_totalBytesSent);
2618 return nMaxOutboundTimeframe;
2621 uint64_t CConnman::GetMaxOutboundTimeLeftInCycle()
2623 LOCK(cs_totalBytesSent);
2624 if (nMaxOutboundLimit == 0)
2625 return 0;
2627 if (nMaxOutboundCycleStartTime == 0)
2628 return nMaxOutboundTimeframe;
2630 uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe;
2631 uint64_t now = GetTime();
2632 return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime();
2635 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe)
2637 LOCK(cs_totalBytesSent);
2638 if (nMaxOutboundTimeframe != timeframe)
2640 // reset measure-cycle in case of changing
2641 // the timeframe
2642 nMaxOutboundCycleStartTime = GetTime();
2644 nMaxOutboundTimeframe = timeframe;
2647 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit)
2649 LOCK(cs_totalBytesSent);
2650 if (nMaxOutboundLimit == 0)
2651 return false;
2653 if (historicalBlockServingLimit)
2655 // keep a large enough buffer to at least relay each block once
2656 uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
2657 uint64_t buffer = timeLeftInCycle / 600 * MAX_BLOCK_SERIALIZED_SIZE;
2658 if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
2659 return true;
2661 else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
2662 return true;
2664 return false;
2667 uint64_t CConnman::GetOutboundTargetBytesLeft()
2669 LOCK(cs_totalBytesSent);
2670 if (nMaxOutboundLimit == 0)
2671 return 0;
2673 return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
2676 uint64_t CConnman::GetTotalBytesRecv()
2678 LOCK(cs_totalBytesRecv);
2679 return nTotalBytesRecv;
2682 uint64_t CConnman::GetTotalBytesSent()
2684 LOCK(cs_totalBytesSent);
2685 return nTotalBytesSent;
2688 ServiceFlags CConnman::GetLocalServices() const
2690 return nLocalServices;
2693 void CConnman::SetBestHeight(int height)
2695 nBestHeight.store(height, std::memory_order_release);
2698 int CConnman::GetBestHeight() const
2700 return nBestHeight.load(std::memory_order_acquire);
2703 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
2705 CNode::CNode(NodeId idIn, ServiceFlags nLocalServicesIn, int nMyStartingHeightIn, SOCKET hSocketIn, const CAddress& addrIn, uint64_t nKeyedNetGroupIn, uint64_t nLocalHostNonceIn, const CAddress &addrBindIn, const std::string& addrNameIn, bool fInboundIn) :
2706 nTimeConnected(GetSystemTimeInSeconds()),
2707 addr(addrIn),
2708 addrBind(addrBindIn),
2709 fInbound(fInboundIn),
2710 nKeyedNetGroup(nKeyedNetGroupIn),
2711 addrKnown(5000, 0.001),
2712 filterInventoryKnown(50000, 0.000001),
2713 id(idIn),
2714 nLocalHostNonce(nLocalHostNonceIn),
2715 nLocalServices(nLocalServicesIn),
2716 nMyStartingHeight(nMyStartingHeightIn),
2717 nSendVersion(0)
2719 nServices = NODE_NONE;
2720 hSocket = hSocketIn;
2721 nRecvVersion = INIT_PROTO_VERSION;
2722 nLastSend = 0;
2723 nLastRecv = 0;
2724 nSendBytes = 0;
2725 nRecvBytes = 0;
2726 nTimeOffset = 0;
2727 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
2728 nVersion = 0;
2729 strSubVer = "";
2730 fWhitelisted = false;
2731 fOneShot = false;
2732 m_manual_connection = false;
2733 fClient = false; // set by version message
2734 fFeeler = false;
2735 fSuccessfullyConnected = false;
2736 fDisconnect = false;
2737 nRefCount = 0;
2738 nSendSize = 0;
2739 nSendOffset = 0;
2740 hashContinue = uint256();
2741 nStartingHeight = -1;
2742 filterInventoryKnown.reset();
2743 fSendMempool = false;
2744 fGetAddr = false;
2745 nNextLocalAddrSend = 0;
2746 nNextAddrSend = 0;
2747 nNextInvSend = 0;
2748 fRelayTxes = false;
2749 fSentAddr = false;
2750 pfilter = new CBloomFilter();
2751 timeLastMempoolReq = 0;
2752 nLastBlockTime = 0;
2753 nLastTXTime = 0;
2754 nPingNonceSent = 0;
2755 nPingUsecStart = 0;
2756 nPingUsecTime = 0;
2757 fPingQueued = false;
2758 nMinPingUsecTime = std::numeric_limits<int64_t>::max();
2759 minFeeFilter = 0;
2760 lastSentFeeFilter = 0;
2761 nextSendTimeFeeFilter = 0;
2762 fPauseRecv = false;
2763 fPauseSend = false;
2764 nProcessQueueSize = 0;
2766 for (const std::string &msg : getAllNetMessageTypes())
2767 mapRecvBytesPerMsgCmd[msg] = 0;
2768 mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
2770 if (fLogIPs) {
2771 LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
2772 } else {
2773 LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
2777 CNode::~CNode()
2779 CloseSocket(hSocket);
2781 if (pfilter)
2782 delete pfilter;
2785 void CNode::AskFor(const CInv& inv)
2787 if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ)
2788 return;
2789 // a peer may not have multiple non-responded queue positions for a single inv item
2790 if (!setAskFor.insert(inv.hash).second)
2791 return;
2793 // We're using mapAskFor as a priority queue,
2794 // the key is the earliest time the request can be sent
2795 int64_t nRequestTime;
2796 limitedmap<uint256, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv.hash);
2797 if (it != mapAlreadyAskedFor.end())
2798 nRequestTime = it->second;
2799 else
2800 nRequestTime = 0;
2801 LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
2803 // Make sure not to reuse time indexes to keep things in the same order
2804 int64_t nNow = GetTimeMicros() - 1000000;
2805 static int64_t nLastTime;
2806 ++nLastTime;
2807 nNow = std::max(nNow, nLastTime);
2808 nLastTime = nNow;
2810 // Each retry is 2 minutes after the last
2811 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
2812 if (it != mapAlreadyAskedFor.end())
2813 mapAlreadyAskedFor.update(it, nRequestTime);
2814 else
2815 mapAlreadyAskedFor.insert(std::make_pair(inv.hash, nRequestTime));
2816 mapAskFor.insert(std::make_pair(nRequestTime, inv));
2819 bool CConnman::NodeFullyConnected(const CNode* pnode)
2821 return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
2824 void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg)
2826 size_t nMessageSize = msg.data.size();
2827 size_t nTotalSize = nMessageSize + CMessageHeader::HEADER_SIZE;
2828 LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command.c_str()), nMessageSize, pnode->GetId());
2830 std::vector<unsigned char> serializedHeader;
2831 serializedHeader.reserve(CMessageHeader::HEADER_SIZE);
2832 uint256 hash = Hash(msg.data.data(), msg.data.data() + nMessageSize);
2833 CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), nMessageSize);
2834 memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
2836 CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, serializedHeader, 0, hdr};
2838 size_t nBytesSent = 0;
2840 LOCK(pnode->cs_vSend);
2841 bool optimisticSend(pnode->vSendMsg.empty());
2843 //log total amount of bytes per command
2844 pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize;
2845 pnode->nSendSize += nTotalSize;
2847 if (pnode->nSendSize > nSendBufferMaxSize)
2848 pnode->fPauseSend = true;
2849 pnode->vSendMsg.push_back(std::move(serializedHeader));
2850 if (nMessageSize)
2851 pnode->vSendMsg.push_back(std::move(msg.data));
2853 // If write queue empty, attempt "optimistic write"
2854 if (optimisticSend == true)
2855 nBytesSent = SocketSendData(pnode);
2857 if (nBytesSent)
2858 RecordBytesSent(nBytesSent);
2861 bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
2863 CNode* found = nullptr;
2864 LOCK(cs_vNodes);
2865 for (auto&& pnode : vNodes) {
2866 if(pnode->GetId() == id) {
2867 found = pnode;
2868 break;
2871 return found != nullptr && NodeFullyConnected(found) && func(found);
2874 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds) {
2875 return nNow + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5);
2878 CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const
2880 return CSipHasher(nSeed0, nSeed1).Write(id);
2883 uint64_t CConnman::CalculateKeyedNetGroup(const CAddress& ad) const
2885 std::vector<unsigned char> vchNetGroup(ad.GetGroup());
2887 return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup.data(), vchNetGroup.size()).Finalize();