Merge #10663: net: split resolve out of connect
[bitcoinplatinum.git] / src / net.cpp
blobea3840a708614b3a915c1b11c6fd0e49ac7bfc46
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->nServicesExpected = ServiceFlags(addrConnect.nServices & nRelevantServices);
448 pnode->AddRef();
450 return pnode;
453 return nullptr;
456 void CConnman::DumpBanlist()
458 SweepBanned(); // clean unused entries (if bantime has expired)
460 if (!BannedSetIsDirty())
461 return;
463 int64_t nStart = GetTimeMillis();
465 CBanDB bandb;
466 banmap_t banmap;
467 GetBanned(banmap);
468 if (bandb.Write(banmap)) {
469 SetBannedSetDirty(false);
472 LogPrint(BCLog::NET, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
473 banmap.size(), GetTimeMillis() - nStart);
476 void CNode::CloseSocketDisconnect()
478 fDisconnect = true;
479 LOCK(cs_hSocket);
480 if (hSocket != INVALID_SOCKET)
482 LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
483 CloseSocket(hSocket);
487 void CConnman::ClearBanned()
490 LOCK(cs_setBanned);
491 setBanned.clear();
492 setBannedIsDirty = true;
494 DumpBanlist(); //store banlist to disk
495 if(clientInterface)
496 clientInterface->BannedListChanged();
499 bool CConnman::IsBanned(CNetAddr ip)
501 LOCK(cs_setBanned);
502 for (const auto& it : setBanned) {
503 CSubNet subNet = it.first;
504 CBanEntry banEntry = it.second;
506 if (subNet.Match(ip) && GetTime() < banEntry.nBanUntil) {
507 return true;
510 return false;
513 bool CConnman::IsBanned(CSubNet subnet)
515 LOCK(cs_setBanned);
516 banmap_t::iterator i = setBanned.find(subnet);
517 if (i != setBanned.end())
519 CBanEntry banEntry = (*i).second;
520 if (GetTime() < banEntry.nBanUntil) {
521 return true;
524 return false;
527 void CConnman::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
528 CSubNet subNet(addr);
529 Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
532 void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
533 CBanEntry banEntry(GetTime());
534 banEntry.banReason = banReason;
535 if (bantimeoffset <= 0)
537 bantimeoffset = gArgs.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
538 sinceUnixEpoch = false;
540 banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
543 LOCK(cs_setBanned);
544 if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
545 setBanned[subNet] = banEntry;
546 setBannedIsDirty = true;
548 else
549 return;
551 if(clientInterface)
552 clientInterface->BannedListChanged();
554 LOCK(cs_vNodes);
555 for (CNode* pnode : vNodes) {
556 if (subNet.Match((CNetAddr)pnode->addr))
557 pnode->fDisconnect = true;
560 if(banReason == BanReasonManuallyAdded)
561 DumpBanlist(); //store banlist to disk immediately if user requested ban
564 bool CConnman::Unban(const CNetAddr &addr) {
565 CSubNet subNet(addr);
566 return Unban(subNet);
569 bool CConnman::Unban(const CSubNet &subNet) {
571 LOCK(cs_setBanned);
572 if (!setBanned.erase(subNet))
573 return false;
574 setBannedIsDirty = true;
576 if(clientInterface)
577 clientInterface->BannedListChanged();
578 DumpBanlist(); //store banlist to disk immediately
579 return true;
582 void CConnman::GetBanned(banmap_t &banMap)
584 LOCK(cs_setBanned);
585 // Sweep the banlist so expired bans are not returned
586 SweepBanned();
587 banMap = setBanned; //create a thread safe copy
590 void CConnman::SetBanned(const banmap_t &banMap)
592 LOCK(cs_setBanned);
593 setBanned = banMap;
594 setBannedIsDirty = true;
597 void CConnman::SweepBanned()
599 int64_t now = GetTime();
601 LOCK(cs_setBanned);
602 banmap_t::iterator it = setBanned.begin();
603 while(it != setBanned.end())
605 CSubNet subNet = (*it).first;
606 CBanEntry banEntry = (*it).second;
607 if(now > banEntry.nBanUntil)
609 setBanned.erase(it++);
610 setBannedIsDirty = true;
611 LogPrint(BCLog::NET, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
613 else
614 ++it;
618 bool CConnman::BannedSetIsDirty()
620 LOCK(cs_setBanned);
621 return setBannedIsDirty;
624 void CConnman::SetBannedSetDirty(bool dirty)
626 LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
627 setBannedIsDirty = dirty;
631 bool CConnman::IsWhitelistedRange(const CNetAddr &addr) {
632 for (const CSubNet& subnet : vWhitelistedRange) {
633 if (subnet.Match(addr))
634 return true;
636 return false;
639 std::string CNode::GetAddrName() const {
640 LOCK(cs_addrName);
641 return addrName;
644 void CNode::MaybeSetAddrName(const std::string& addrNameIn) {
645 LOCK(cs_addrName);
646 if (addrName.empty()) {
647 addrName = addrNameIn;
651 CService CNode::GetAddrLocal() const {
652 LOCK(cs_addrLocal);
653 return addrLocal;
656 void CNode::SetAddrLocal(const CService& addrLocalIn) {
657 LOCK(cs_addrLocal);
658 if (addrLocal.IsValid()) {
659 error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString());
660 } else {
661 addrLocal = addrLocalIn;
665 #undef X
666 #define X(name) stats.name = name
667 void CNode::copyStats(CNodeStats &stats)
669 stats.nodeid = this->GetId();
670 X(nServices);
671 X(addr);
672 X(addrBind);
674 LOCK(cs_filter);
675 X(fRelayTxes);
677 X(nLastSend);
678 X(nLastRecv);
679 X(nTimeConnected);
680 X(nTimeOffset);
681 stats.addrName = GetAddrName();
682 X(nVersion);
684 LOCK(cs_SubVer);
685 X(cleanSubVer);
687 X(fInbound);
688 X(fAddnode);
689 X(nStartingHeight);
691 LOCK(cs_vSend);
692 X(mapSendBytesPerMsgCmd);
693 X(nSendBytes);
696 LOCK(cs_vRecv);
697 X(mapRecvBytesPerMsgCmd);
698 X(nRecvBytes);
700 X(fWhitelisted);
702 // It is common for nodes with good ping times to suddenly become lagged,
703 // due to a new block arriving or other large transfer.
704 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
705 // since pingtime does not update until the ping is complete, which might take a while.
706 // So, if a ping is taking an unusually long time in flight,
707 // the caller can immediately detect that this is happening.
708 int64_t nPingUsecWait = 0;
709 if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
710 nPingUsecWait = GetTimeMicros() - nPingUsecStart;
713 // 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 :)
714 stats.dPingTime = (((double)nPingUsecTime) / 1e6);
715 stats.dMinPing = (((double)nMinPingUsecTime) / 1e6);
716 stats.dPingWait = (((double)nPingUsecWait) / 1e6);
718 // Leave string empty if addrLocal invalid (not filled in yet)
719 CService addrLocalUnlocked = GetAddrLocal();
720 stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
722 #undef X
724 bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete)
726 complete = false;
727 int64_t nTimeMicros = GetTimeMicros();
728 LOCK(cs_vRecv);
729 nLastRecv = nTimeMicros / 1000000;
730 nRecvBytes += nBytes;
731 while (nBytes > 0) {
733 // get current incomplete message, or create a new one
734 if (vRecvMsg.empty() ||
735 vRecvMsg.back().complete())
736 vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION));
738 CNetMessage& msg = vRecvMsg.back();
740 // absorb network data
741 int handled;
742 if (!msg.in_data)
743 handled = msg.readHeader(pch, nBytes);
744 else
745 handled = msg.readData(pch, nBytes);
747 if (handled < 0)
748 return false;
750 if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
751 LogPrint(BCLog::NET, "Oversized message from peer=%i, disconnecting\n", GetId());
752 return false;
755 pch += handled;
756 nBytes -= handled;
758 if (msg.complete()) {
760 //store received bytes per message command
761 //to prevent a memory DOS, only allow valid commands
762 mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand);
763 if (i == mapRecvBytesPerMsgCmd.end())
764 i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
765 assert(i != mapRecvBytesPerMsgCmd.end());
766 i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
768 msg.nTime = nTimeMicros;
769 complete = true;
773 return true;
776 void CNode::SetSendVersion(int nVersionIn)
778 // Send version may only be changed in the version message, and
779 // only one version message is allowed per session. We can therefore
780 // treat this value as const and even atomic as long as it's only used
781 // once a version message has been successfully processed. Any attempt to
782 // set this twice is an error.
783 if (nSendVersion != 0) {
784 error("Send version already set for node: %i. Refusing to change from %i to %i", id, nSendVersion, nVersionIn);
785 } else {
786 nSendVersion = nVersionIn;
790 int CNode::GetSendVersion() const
792 // The send version should always be explicitly set to
793 // INIT_PROTO_VERSION rather than using this value until SetSendVersion
794 // has been called.
795 if (nSendVersion == 0) {
796 error("Requesting unset send version for node: %i. Using %i", id, INIT_PROTO_VERSION);
797 return INIT_PROTO_VERSION;
799 return nSendVersion;
803 int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
805 // copy data to temporary parsing buffer
806 unsigned int nRemaining = 24 - nHdrPos;
807 unsigned int nCopy = std::min(nRemaining, nBytes);
809 memcpy(&hdrbuf[nHdrPos], pch, nCopy);
810 nHdrPos += nCopy;
812 // if header incomplete, exit
813 if (nHdrPos < 24)
814 return nCopy;
816 // deserialize to CMessageHeader
817 try {
818 hdrbuf >> hdr;
820 catch (const std::exception&) {
821 return -1;
824 // reject messages larger than MAX_SIZE
825 if (hdr.nMessageSize > MAX_SIZE)
826 return -1;
828 // switch state to reading message data
829 in_data = true;
831 return nCopy;
834 int CNetMessage::readData(const char *pch, unsigned int nBytes)
836 unsigned int nRemaining = hdr.nMessageSize - nDataPos;
837 unsigned int nCopy = std::min(nRemaining, nBytes);
839 if (vRecv.size() < nDataPos + nCopy) {
840 // Allocate up to 256 KiB ahead, but never more than the total message size.
841 vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
844 hasher.Write((const unsigned char*)pch, nCopy);
845 memcpy(&vRecv[nDataPos], pch, nCopy);
846 nDataPos += nCopy;
848 return nCopy;
851 const uint256& CNetMessage::GetMessageHash() const
853 assert(complete());
854 if (data_hash.IsNull())
855 hasher.Finalize(data_hash.begin());
856 return data_hash;
867 // requires LOCK(cs_vSend)
868 size_t CConnman::SocketSendData(CNode *pnode) const
870 auto it = pnode->vSendMsg.begin();
871 size_t nSentSize = 0;
873 while (it != pnode->vSendMsg.end()) {
874 const auto &data = *it;
875 assert(data.size() > pnode->nSendOffset);
876 int nBytes = 0;
878 LOCK(pnode->cs_hSocket);
879 if (pnode->hSocket == INVALID_SOCKET)
880 break;
881 nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
883 if (nBytes > 0) {
884 pnode->nLastSend = GetSystemTimeInSeconds();
885 pnode->nSendBytes += nBytes;
886 pnode->nSendOffset += nBytes;
887 nSentSize += nBytes;
888 if (pnode->nSendOffset == data.size()) {
889 pnode->nSendOffset = 0;
890 pnode->nSendSize -= data.size();
891 pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
892 it++;
893 } else {
894 // could not send full message; stop sending more
895 break;
897 } else {
898 if (nBytes < 0) {
899 // error
900 int nErr = WSAGetLastError();
901 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
903 LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
904 pnode->CloseSocketDisconnect();
907 // couldn't send anything at all
908 break;
912 if (it == pnode->vSendMsg.end()) {
913 assert(pnode->nSendOffset == 0);
914 assert(pnode->nSendSize == 0);
916 pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
917 return nSentSize;
920 struct NodeEvictionCandidate
922 NodeId id;
923 int64_t nTimeConnected;
924 int64_t nMinPingUsecTime;
925 int64_t nLastBlockTime;
926 int64_t nLastTXTime;
927 bool fRelevantServices;
928 bool fRelayTxes;
929 bool fBloomFilter;
930 CAddress addr;
931 uint64_t nKeyedNetGroup;
934 static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
936 return a.nMinPingUsecTime > b.nMinPingUsecTime;
939 static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
941 return a.nTimeConnected > b.nTimeConnected;
944 static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
945 return a.nKeyedNetGroup < b.nKeyedNetGroup;
948 static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
950 // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
951 if (a.nLastBlockTime != b.nLastBlockTime) return a.nLastBlockTime < b.nLastBlockTime;
952 if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
953 return a.nTimeConnected > b.nTimeConnected;
956 static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
958 // 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.
959 if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime;
960 if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes;
961 if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
962 return a.nTimeConnected > b.nTimeConnected;
965 /** Try to find a connection to evict when the node is full.
966 * Extreme care must be taken to avoid opening the node to attacker
967 * triggered network partitioning.
968 * The strategy used here is to protect a small number of peers
969 * for each of several distinct characteristics which are difficult
970 * to forge. In order to partition a node the attacker must be
971 * simultaneously better at all of them than honest peers.
973 bool CConnman::AttemptToEvictConnection()
975 std::vector<NodeEvictionCandidate> vEvictionCandidates;
977 LOCK(cs_vNodes);
979 for (const CNode* node : vNodes) {
980 if (node->fWhitelisted)
981 continue;
982 if (!node->fInbound)
983 continue;
984 if (node->fDisconnect)
985 continue;
986 NodeEvictionCandidate candidate = {node->GetId(), node->nTimeConnected, node->nMinPingUsecTime,
987 node->nLastBlockTime, node->nLastTXTime,
988 (node->nServices & nRelevantServices) == nRelevantServices,
989 node->fRelayTxes, node->pfilter != nullptr, node->addr, node->nKeyedNetGroup};
990 vEvictionCandidates.push_back(candidate);
994 if (vEvictionCandidates.empty()) return false;
996 // Protect connections with certain characteristics
998 // Deterministically select 4 peers to protect by netgroup.
999 // An attacker cannot predict which netgroups will be protected
1000 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNetGroupKeyed);
1001 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
1003 if (vEvictionCandidates.empty()) return false;
1005 // Protect the 8 nodes with the lowest minimum ping time.
1006 // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
1007 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime);
1008 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
1010 if (vEvictionCandidates.empty()) return false;
1012 // Protect 4 nodes that most recently sent us transactions.
1013 // An attacker cannot manipulate this metric without performing useful work.
1014 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeTXTime);
1015 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
1017 if (vEvictionCandidates.empty()) return false;
1019 // Protect 4 nodes that most recently sent us blocks.
1020 // An attacker cannot manipulate this metric without performing useful work.
1021 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeBlockTime);
1022 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
1024 if (vEvictionCandidates.empty()) return false;
1026 // Protect the half of the remaining nodes which have been connected the longest.
1027 // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
1028 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected);
1029 vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end());
1031 if (vEvictionCandidates.empty()) return false;
1033 // Identify the network group with the most connections and youngest member.
1034 // (vEvictionCandidates is already sorted by reverse connect time)
1035 uint64_t naMostConnections;
1036 unsigned int nMostConnections = 0;
1037 int64_t nMostConnectionsTime = 0;
1038 std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
1039 for (const NodeEvictionCandidate &node : vEvictionCandidates) {
1040 mapNetGroupNodes[node.nKeyedNetGroup].push_back(node);
1041 int64_t grouptime = mapNetGroupNodes[node.nKeyedNetGroup][0].nTimeConnected;
1042 size_t groupsize = mapNetGroupNodes[node.nKeyedNetGroup].size();
1044 if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) {
1045 nMostConnections = groupsize;
1046 nMostConnectionsTime = grouptime;
1047 naMostConnections = node.nKeyedNetGroup;
1051 // Reduce to the network group with the most connections
1052 vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
1054 // Disconnect from the network group with the most connections
1055 NodeId evicted = vEvictionCandidates.front().id;
1056 LOCK(cs_vNodes);
1057 for (CNode* pnode : vNodes) {
1058 if (pnode->GetId() == evicted) {
1059 pnode->fDisconnect = true;
1060 return true;
1063 return false;
1066 void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
1067 struct sockaddr_storage sockaddr;
1068 socklen_t len = sizeof(sockaddr);
1069 SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
1070 CAddress addr;
1071 int nInbound = 0;
1072 int nMaxInbound = nMaxConnections - (nMaxOutbound + nMaxFeeler);
1074 if (hSocket != INVALID_SOCKET) {
1075 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) {
1076 LogPrintf("Warning: Unknown socket family\n");
1080 bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr);
1082 LOCK(cs_vNodes);
1083 for (const CNode* pnode : vNodes) {
1084 if (pnode->fInbound) nInbound++;
1088 if (hSocket == INVALID_SOCKET)
1090 int nErr = WSAGetLastError();
1091 if (nErr != WSAEWOULDBLOCK)
1092 LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
1093 return;
1096 if (!fNetworkActive) {
1097 LogPrintf("connection from %s dropped: not accepting new connections\n", addr.ToString());
1098 CloseSocket(hSocket);
1099 return;
1102 if (!IsSelectableSocket(hSocket))
1104 LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
1105 CloseSocket(hSocket);
1106 return;
1109 // According to the internet TCP_NODELAY is not carried into accepted sockets
1110 // on all platforms. Set it again here just to be sure.
1111 SetSocketNoDelay(hSocket);
1113 if (IsBanned(addr) && !whitelisted)
1115 LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
1116 CloseSocket(hSocket);
1117 return;
1120 if (nInbound >= nMaxInbound)
1122 if (!AttemptToEvictConnection()) {
1123 // No connection to evict, disconnect the new connection
1124 LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1125 CloseSocket(hSocket);
1126 return;
1130 NodeId id = GetNewNodeId();
1131 uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
1132 CAddress addr_bind = GetBindAddress(hSocket);
1134 CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, addr_bind, "", true);
1135 pnode->AddRef();
1136 pnode->fWhitelisted = whitelisted;
1137 m_msgproc->InitializeNode(pnode);
1139 LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
1142 LOCK(cs_vNodes);
1143 vNodes.push_back(pnode);
1147 void CConnman::ThreadSocketHandler()
1149 unsigned int nPrevNodeCount = 0;
1150 while (!interruptNet)
1153 // Disconnect nodes
1156 LOCK(cs_vNodes);
1157 // Disconnect unused nodes
1158 std::vector<CNode*> vNodesCopy = vNodes;
1159 for (CNode* pnode : vNodesCopy)
1161 if (pnode->fDisconnect)
1163 // remove from vNodes
1164 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
1166 // release outbound grant (if any)
1167 pnode->grantOutbound.Release();
1169 // close socket and cleanup
1170 pnode->CloseSocketDisconnect();
1172 // hold in disconnected pool until all refs are released
1173 pnode->Release();
1174 vNodesDisconnected.push_back(pnode);
1179 // Delete disconnected nodes
1180 std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1181 for (CNode* pnode : vNodesDisconnectedCopy)
1183 // wait until threads are done using it
1184 if (pnode->GetRefCount() <= 0) {
1185 bool fDelete = false;
1187 TRY_LOCK(pnode->cs_inventory, lockInv);
1188 if (lockInv) {
1189 TRY_LOCK(pnode->cs_vSend, lockSend);
1190 if (lockSend) {
1191 fDelete = true;
1195 if (fDelete) {
1196 vNodesDisconnected.remove(pnode);
1197 DeleteNode(pnode);
1202 size_t vNodesSize;
1204 LOCK(cs_vNodes);
1205 vNodesSize = vNodes.size();
1207 if(vNodesSize != nPrevNodeCount) {
1208 nPrevNodeCount = vNodesSize;
1209 if(clientInterface)
1210 clientInterface->NotifyNumConnectionsChanged(nPrevNodeCount);
1214 // Find which sockets have data to receive
1216 struct timeval timeout;
1217 timeout.tv_sec = 0;
1218 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
1220 fd_set fdsetRecv;
1221 fd_set fdsetSend;
1222 fd_set fdsetError;
1223 FD_ZERO(&fdsetRecv);
1224 FD_ZERO(&fdsetSend);
1225 FD_ZERO(&fdsetError);
1226 SOCKET hSocketMax = 0;
1227 bool have_fds = false;
1229 for (const ListenSocket& hListenSocket : vhListenSocket) {
1230 FD_SET(hListenSocket.socket, &fdsetRecv);
1231 hSocketMax = std::max(hSocketMax, hListenSocket.socket);
1232 have_fds = true;
1236 LOCK(cs_vNodes);
1237 for (CNode* pnode : vNodes)
1239 // Implement the following logic:
1240 // * If there is data to send, select() for sending data. As this only
1241 // happens when optimistic write failed, we choose to first drain the
1242 // write buffer in this case before receiving more. This avoids
1243 // needlessly queueing received data, if the remote peer is not themselves
1244 // receiving data. This means properly utilizing TCP flow control signalling.
1245 // * Otherwise, if there is space left in the receive buffer, select() for
1246 // receiving data.
1247 // * Hand off all complete messages to the processor, to be handled without
1248 // blocking here.
1250 bool select_recv = !pnode->fPauseRecv;
1251 bool select_send;
1253 LOCK(pnode->cs_vSend);
1254 select_send = !pnode->vSendMsg.empty();
1257 LOCK(pnode->cs_hSocket);
1258 if (pnode->hSocket == INVALID_SOCKET)
1259 continue;
1261 FD_SET(pnode->hSocket, &fdsetError);
1262 hSocketMax = std::max(hSocketMax, pnode->hSocket);
1263 have_fds = true;
1265 if (select_send) {
1266 FD_SET(pnode->hSocket, &fdsetSend);
1267 continue;
1269 if (select_recv) {
1270 FD_SET(pnode->hSocket, &fdsetRecv);
1275 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
1276 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1277 if (interruptNet)
1278 return;
1280 if (nSelect == SOCKET_ERROR)
1282 if (have_fds)
1284 int nErr = WSAGetLastError();
1285 LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1286 for (unsigned int i = 0; i <= hSocketMax; i++)
1287 FD_SET(i, &fdsetRecv);
1289 FD_ZERO(&fdsetSend);
1290 FD_ZERO(&fdsetError);
1291 if (!interruptNet.sleep_for(std::chrono::milliseconds(timeout.tv_usec/1000)))
1292 return;
1296 // Accept new connections
1298 for (const ListenSocket& hListenSocket : vhListenSocket)
1300 if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
1302 AcceptConnection(hListenSocket);
1307 // Service each socket
1309 std::vector<CNode*> vNodesCopy;
1311 LOCK(cs_vNodes);
1312 vNodesCopy = vNodes;
1313 for (CNode* pnode : vNodesCopy)
1314 pnode->AddRef();
1316 for (CNode* pnode : vNodesCopy)
1318 if (interruptNet)
1319 return;
1322 // Receive
1324 bool recvSet = false;
1325 bool sendSet = false;
1326 bool errorSet = false;
1328 LOCK(pnode->cs_hSocket);
1329 if (pnode->hSocket == INVALID_SOCKET)
1330 continue;
1331 recvSet = FD_ISSET(pnode->hSocket, &fdsetRecv);
1332 sendSet = FD_ISSET(pnode->hSocket, &fdsetSend);
1333 errorSet = FD_ISSET(pnode->hSocket, &fdsetError);
1335 if (recvSet || errorSet)
1337 // typical socket buffer is 8K-64K
1338 char pchBuf[0x10000];
1339 int nBytes = 0;
1341 LOCK(pnode->cs_hSocket);
1342 if (pnode->hSocket == INVALID_SOCKET)
1343 continue;
1344 nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1346 if (nBytes > 0)
1348 bool notify = false;
1349 if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify))
1350 pnode->CloseSocketDisconnect();
1351 RecordBytesRecv(nBytes);
1352 if (notify) {
1353 size_t nSizeAdded = 0;
1354 auto it(pnode->vRecvMsg.begin());
1355 for (; it != pnode->vRecvMsg.end(); ++it) {
1356 if (!it->complete())
1357 break;
1358 nSizeAdded += it->vRecv.size() + CMessageHeader::HEADER_SIZE;
1361 LOCK(pnode->cs_vProcessMsg);
1362 pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
1363 pnode->nProcessQueueSize += nSizeAdded;
1364 pnode->fPauseRecv = pnode->nProcessQueueSize > nReceiveFloodSize;
1366 WakeMessageHandler();
1369 else if (nBytes == 0)
1371 // socket closed gracefully
1372 if (!pnode->fDisconnect) {
1373 LogPrint(BCLog::NET, "socket closed\n");
1375 pnode->CloseSocketDisconnect();
1377 else if (nBytes < 0)
1379 // error
1380 int nErr = WSAGetLastError();
1381 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1383 if (!pnode->fDisconnect)
1384 LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
1385 pnode->CloseSocketDisconnect();
1391 // Send
1393 if (sendSet)
1395 LOCK(pnode->cs_vSend);
1396 size_t nBytes = SocketSendData(pnode);
1397 if (nBytes) {
1398 RecordBytesSent(nBytes);
1403 // Inactivity checking
1405 int64_t nTime = GetSystemTimeInSeconds();
1406 if (nTime - pnode->nTimeConnected > 60)
1408 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1410 LogPrint(BCLog::NET, "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->GetId());
1411 pnode->fDisconnect = true;
1413 else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
1415 LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
1416 pnode->fDisconnect = true;
1418 else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
1420 LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
1421 pnode->fDisconnect = true;
1423 else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
1425 LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
1426 pnode->fDisconnect = true;
1428 else if (!pnode->fSuccessfullyConnected)
1430 LogPrintf("version handshake timeout from %d\n", pnode->GetId());
1431 pnode->fDisconnect = true;
1436 LOCK(cs_vNodes);
1437 for (CNode* pnode : vNodesCopy)
1438 pnode->Release();
1443 void CConnman::WakeMessageHandler()
1446 std::lock_guard<std::mutex> lock(mutexMsgProc);
1447 fMsgProcWake = true;
1449 condMsgProc.notify_one();
1457 #ifdef USE_UPNP
1458 void ThreadMapPort()
1460 std::string port = strprintf("%u", GetListenPort());
1461 const char * multicastif = nullptr;
1462 const char * minissdpdpath = nullptr;
1463 struct UPNPDev * devlist = nullptr;
1464 char lanaddr[64];
1466 #ifndef UPNPDISCOVER_SUCCESS
1467 /* miniupnpc 1.5 */
1468 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1469 #elif MINIUPNPC_API_VERSION < 14
1470 /* miniupnpc 1.6 */
1471 int error = 0;
1472 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1473 #else
1474 /* miniupnpc 1.9.20150730 */
1475 int error = 0;
1476 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
1477 #endif
1479 struct UPNPUrls urls;
1480 struct IGDdatas data;
1481 int r;
1483 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1484 if (r == 1)
1486 if (fDiscover) {
1487 char externalIPAddress[40];
1488 r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1489 if(r != UPNPCOMMAND_SUCCESS)
1490 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
1491 else
1493 if(externalIPAddress[0])
1495 CNetAddr resolved;
1496 if(LookupHost(externalIPAddress, resolved, false)) {
1497 LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToString().c_str());
1498 AddLocal(resolved, LOCAL_UPNP);
1501 else
1502 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1506 std::string strDesc = "Bitcoin " + FormatFullVersion();
1508 try {
1509 while (true) {
1510 #ifndef UPNPDISCOVER_SUCCESS
1511 /* miniupnpc 1.5 */
1512 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1513 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1514 #else
1515 /* miniupnpc 1.6 */
1516 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1517 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1518 #endif
1520 if(r!=UPNPCOMMAND_SUCCESS)
1521 LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1522 port, port, lanaddr, r, strupnperror(r));
1523 else
1524 LogPrintf("UPnP Port Mapping successful.\n");
1526 MilliSleep(20*60*1000); // Refresh every 20 minutes
1529 catch (const boost::thread_interrupted&)
1531 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1532 LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
1533 freeUPNPDevlist(devlist); devlist = nullptr;
1534 FreeUPNPUrls(&urls);
1535 throw;
1537 } else {
1538 LogPrintf("No valid UPnP IGDs found\n");
1539 freeUPNPDevlist(devlist); devlist = nullptr;
1540 if (r != 0)
1541 FreeUPNPUrls(&urls);
1545 void MapPort(bool fUseUPnP)
1547 static boost::thread* upnp_thread = nullptr;
1549 if (fUseUPnP)
1551 if (upnp_thread) {
1552 upnp_thread->interrupt();
1553 upnp_thread->join();
1554 delete upnp_thread;
1556 upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
1558 else if (upnp_thread) {
1559 upnp_thread->interrupt();
1560 upnp_thread->join();
1561 delete upnp_thread;
1562 upnp_thread = nullptr;
1566 #else
1567 void MapPort(bool)
1569 // Intentionally left blank.
1571 #endif
1578 static std::string GetDNSHost(const CDNSSeedData& data, ServiceFlags* requiredServiceBits)
1580 //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
1581 if (!data.supportsServiceBitsFiltering || *requiredServiceBits == NODE_NETWORK) {
1582 *requiredServiceBits = NODE_NETWORK;
1583 return data.host;
1586 // See chainparams.cpp, most dnsseeds only support one or two possible servicebits hostnames
1587 return strprintf("x%x.%s", *requiredServiceBits, data.host);
1591 void CConnman::ThreadDNSAddressSeed()
1593 // goal: only query DNS seeds if address need is acute
1594 // Avoiding DNS seeds when we don't need them improves user privacy by
1595 // creating fewer identifying DNS requests, reduces trust by giving seeds
1596 // less influence on the network topology, and reduces traffic to the seeds.
1597 if ((addrman.size() > 0) &&
1598 (!gArgs.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
1599 if (!interruptNet.sleep_for(std::chrono::seconds(11)))
1600 return;
1602 LOCK(cs_vNodes);
1603 int nRelevant = 0;
1604 for (auto pnode : vNodes) {
1605 nRelevant += pnode->fSuccessfullyConnected && ((pnode->nServices & nRelevantServices) == nRelevantServices);
1607 if (nRelevant >= 2) {
1608 LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1609 return;
1613 const std::vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
1614 int found = 0;
1616 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1618 for (const CDNSSeedData &seed : vSeeds) {
1619 if (interruptNet) {
1620 return;
1622 if (HaveNameProxy()) {
1623 AddOneShot(seed.host);
1624 } else {
1625 std::vector<CNetAddr> vIPs;
1626 std::vector<CAddress> vAdd;
1627 ServiceFlags requiredServiceBits = nRelevantServices;
1628 std::string host = GetDNSHost(seed, &requiredServiceBits);
1629 CNetAddr resolveSource;
1630 if (!resolveSource.SetInternal(host)) {
1631 continue;
1633 if (LookupHost(host.c_str(), vIPs, 0, true))
1635 for (const CNetAddr& ip : vIPs)
1637 int nOneDay = 24*3600;
1638 CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
1639 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1640 vAdd.push_back(addr);
1641 found++;
1643 addrman.Add(vAdd, resolveSource);
1648 LogPrintf("%d addresses found from DNS seeds\n", found);
1662 void CConnman::DumpAddresses()
1664 int64_t nStart = GetTimeMillis();
1666 CAddrDB adb;
1667 adb.Write(addrman);
1669 LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1670 addrman.size(), GetTimeMillis() - nStart);
1673 void CConnman::DumpData()
1675 DumpAddresses();
1676 DumpBanlist();
1679 void CConnman::ProcessOneShot()
1681 std::string strDest;
1683 LOCK(cs_vOneShots);
1684 if (vOneShots.empty())
1685 return;
1686 strDest = vOneShots.front();
1687 vOneShots.pop_front();
1689 CAddress addr;
1690 CSemaphoreGrant grant(*semOutbound, true);
1691 if (grant) {
1692 if (!OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true))
1693 AddOneShot(strDest);
1697 void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
1699 // Connect to specific addresses
1700 if (!connect.empty())
1702 for (int64_t nLoop = 0;; nLoop++)
1704 ProcessOneShot();
1705 for (const std::string& strAddr : connect)
1707 CAddress addr(CService(), NODE_NONE);
1708 OpenNetworkConnection(addr, false, nullptr, strAddr.c_str());
1709 for (int i = 0; i < 10 && i < nLoop; i++)
1711 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1712 return;
1715 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1716 return;
1720 // Initiate network connections
1721 int64_t nStart = GetTime();
1723 // Minimum time before next feeler connection (in microseconds).
1724 int64_t nNextFeeler = PoissonNextSend(nStart*1000*1000, FEELER_INTERVAL);
1725 while (!interruptNet)
1727 ProcessOneShot();
1729 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1730 return;
1732 CSemaphoreGrant grant(*semOutbound);
1733 if (interruptNet)
1734 return;
1736 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1737 if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1738 static bool done = false;
1739 if (!done) {
1740 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1741 CNetAddr local;
1742 local.SetInternal("fixedseeds");
1743 addrman.Add(convertSeed6(Params().FixedSeeds()), local);
1744 done = true;
1749 // Choose an address to connect to based on most recently seen
1751 CAddress addrConnect;
1753 // Only connect out to one peer per network group (/16 for IPv4).
1754 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1755 int nOutbound = 0;
1756 int nOutboundRelevant = 0;
1757 std::set<std::vector<unsigned char> > setConnected;
1759 LOCK(cs_vNodes);
1760 for (CNode* pnode : vNodes) {
1761 if (!pnode->fInbound && !pnode->fAddnode) {
1763 // Count the peers that have all relevant services
1764 if (pnode->fSuccessfullyConnected && !pnode->fFeeler && ((pnode->nServices & nRelevantServices) == nRelevantServices)) {
1765 nOutboundRelevant++;
1767 // Netgroups for inbound and addnode peers are not excluded because our goal here
1768 // is to not use multiple of our limited outbound slots on a single netgroup
1769 // but inbound and addnode peers do not use our outbound slots. Inbound peers
1770 // also have the added issue that they're attacker controlled and could be used
1771 // to prevent us from connecting to particular hosts if we used them here.
1772 setConnected.insert(pnode->addr.GetGroup());
1773 nOutbound++;
1778 // Feeler Connections
1780 // Design goals:
1781 // * Increase the number of connectable addresses in the tried table.
1783 // Method:
1784 // * Choose a random address from new and attempt to connect to it if we can connect
1785 // successfully it is added to tried.
1786 // * Start attempting feeler connections only after node finishes making outbound
1787 // connections.
1788 // * Only make a feeler connection once every few minutes.
1790 bool fFeeler = false;
1791 if (nOutbound >= nMaxOutbound) {
1792 int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds).
1793 if (nTime > nNextFeeler) {
1794 nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
1795 fFeeler = true;
1796 } else {
1797 continue;
1801 int64_t nANow = GetAdjustedTime();
1802 int nTries = 0;
1803 while (!interruptNet)
1805 CAddrInfo addr = addrman.Select(fFeeler);
1807 // if we selected an invalid address, restart
1808 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1809 break;
1811 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1812 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1813 // already-connected network ranges, ...) before trying new addrman addresses.
1814 nTries++;
1815 if (nTries > 100)
1816 break;
1818 if (IsLimited(addr))
1819 continue;
1821 // only connect to full nodes
1822 if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
1823 continue;
1825 // only consider very recently tried nodes after 30 failed attempts
1826 if (nANow - addr.nLastTry < 600 && nTries < 30)
1827 continue;
1829 // only consider nodes missing relevant services after 40 failed attempts and only if less than half the outbound are up.
1830 ServiceFlags nRequiredServices = nRelevantServices;
1831 if (nTries >= 40 && nOutbound < (nMaxOutbound >> 1)) {
1832 nRequiredServices = REQUIRED_SERVICES;
1835 if ((addr.nServices & nRequiredServices) != nRequiredServices) {
1836 continue;
1839 // do not allow non-default ports, unless after 50 invalid addresses selected already
1840 if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1841 continue;
1843 addrConnect = addr;
1845 // regardless of the services assumed to be available, only require the minimum if half or more outbound have relevant services
1846 if (nOutboundRelevant >= (nMaxOutbound >> 1)) {
1847 addrConnect.nServices = REQUIRED_SERVICES;
1848 } else {
1849 addrConnect.nServices = nRequiredServices;
1851 break;
1854 if (addrConnect.IsValid()) {
1856 if (fFeeler) {
1857 // Add small amount of random noise before connection to avoid synchronization.
1858 int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
1859 if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
1860 return;
1861 LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
1864 OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, nullptr, false, fFeeler);
1869 std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
1871 std::vector<AddedNodeInfo> ret;
1873 std::list<std::string> lAddresses(0);
1875 LOCK(cs_vAddedNodes);
1876 ret.reserve(vAddedNodes.size());
1877 std::copy(vAddedNodes.cbegin(), vAddedNodes.cend(), std::back_inserter(lAddresses));
1881 // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
1882 std::map<CService, bool> mapConnected;
1883 std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
1885 LOCK(cs_vNodes);
1886 for (const CNode* pnode : vNodes) {
1887 if (pnode->addr.IsValid()) {
1888 mapConnected[pnode->addr] = pnode->fInbound;
1890 std::string addrName = pnode->GetAddrName();
1891 if (!addrName.empty()) {
1892 mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr));
1897 for (const std::string& strAddNode : lAddresses) {
1898 CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort()));
1899 if (service.IsValid()) {
1900 // strAddNode is an IP:port
1901 auto it = mapConnected.find(service);
1902 if (it != mapConnected.end()) {
1903 ret.push_back(AddedNodeInfo{strAddNode, service, true, it->second});
1904 } else {
1905 ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
1907 } else {
1908 // strAddNode is a name
1909 auto it = mapConnectedByName.find(strAddNode);
1910 if (it != mapConnectedByName.end()) {
1911 ret.push_back(AddedNodeInfo{strAddNode, it->second.second, true, it->second.first});
1912 } else {
1913 ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
1918 return ret;
1921 void CConnman::ThreadOpenAddedConnections()
1923 while (true)
1925 CSemaphoreGrant grant(*semAddnode);
1926 std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
1927 bool tried = false;
1928 for (const AddedNodeInfo& info : vInfo) {
1929 if (!info.fConnected) {
1930 if (!grant.TryAcquire()) {
1931 // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
1932 // the addednodeinfo state might change.
1933 break;
1935 tried = true;
1936 CAddress addr(CService(), NODE_NONE);
1937 OpenNetworkConnection(addr, false, &grant, info.strAddedNode.c_str(), false, false, true);
1938 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1939 return;
1942 // Retry every 60 seconds if a connection was attempted, otherwise two seconds
1943 if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
1944 return;
1948 // if successful, this moves the passed grant to the constructed node
1949 bool CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot, bool fFeeler, bool fAddnode)
1952 // Initiate outbound network connection
1954 if (interruptNet) {
1955 return false;
1957 if (!fNetworkActive) {
1958 return false;
1960 if (!pszDest) {
1961 if (IsLocal(addrConnect) ||
1962 FindNode((CNetAddr)addrConnect) || IsBanned(addrConnect) ||
1963 FindNode(addrConnect.ToStringIPPort()))
1964 return false;
1965 } else if (FindNode(std::string(pszDest)))
1966 return false;
1968 CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure);
1970 if (!pnode)
1971 return false;
1972 if (grantOutbound)
1973 grantOutbound->MoveTo(pnode->grantOutbound);
1974 if (fOneShot)
1975 pnode->fOneShot = true;
1976 if (fFeeler)
1977 pnode->fFeeler = true;
1978 if (fAddnode)
1979 pnode->fAddnode = true;
1981 m_msgproc->InitializeNode(pnode);
1983 LOCK(cs_vNodes);
1984 vNodes.push_back(pnode);
1987 return true;
1990 void CConnman::ThreadMessageHandler()
1992 while (!flagInterruptMsgProc)
1994 std::vector<CNode*> vNodesCopy;
1996 LOCK(cs_vNodes);
1997 vNodesCopy = vNodes;
1998 for (CNode* pnode : vNodesCopy) {
1999 pnode->AddRef();
2003 bool fMoreWork = false;
2005 for (CNode* pnode : vNodesCopy)
2007 if (pnode->fDisconnect)
2008 continue;
2010 // Receive messages
2011 bool fMoreNodeWork = m_msgproc->ProcessMessages(pnode, flagInterruptMsgProc);
2012 fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
2013 if (flagInterruptMsgProc)
2014 return;
2015 // Send messages
2017 LOCK(pnode->cs_sendProcessing);
2018 m_msgproc->SendMessages(pnode, flagInterruptMsgProc);
2021 if (flagInterruptMsgProc)
2022 return;
2026 LOCK(cs_vNodes);
2027 for (CNode* pnode : vNodesCopy)
2028 pnode->Release();
2031 std::unique_lock<std::mutex> lock(mutexMsgProc);
2032 if (!fMoreWork) {
2033 condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; });
2035 fMsgProcWake = false;
2044 bool CConnman::BindListenPort(const CService &addrBind, std::string& strError, bool fWhitelisted)
2046 strError = "";
2047 int nOne = 1;
2049 // Create socket for listening for incoming connections
2050 struct sockaddr_storage sockaddr;
2051 socklen_t len = sizeof(sockaddr);
2052 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
2054 strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
2055 LogPrintf("%s\n", strError);
2056 return false;
2059 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
2060 if (hListenSocket == INVALID_SOCKET)
2062 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2063 LogPrintf("%s\n", strError);
2064 return false;
2066 if (!IsSelectableSocket(hListenSocket))
2068 strError = "Error: Couldn't create a listenable socket for incoming connections";
2069 LogPrintf("%s\n", strError);
2070 return false;
2074 #ifndef WIN32
2075 #ifdef SO_NOSIGPIPE
2076 // Different way of disabling SIGPIPE on BSD
2077 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
2078 #endif
2079 // Allow binding if the port is still in TIME_WAIT state after
2080 // the program was closed and restarted.
2081 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
2082 // Disable Nagle's algorithm
2083 setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int));
2084 #else
2085 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int));
2086 setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int));
2087 #endif
2089 // Set to non-blocking, incoming connections will also inherit this
2090 if (!SetSocketNonBlocking(hListenSocket, true)) {
2091 CloseSocket(hListenSocket);
2092 strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
2093 LogPrintf("%s\n", strError);
2094 return false;
2097 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2098 // and enable it by default or not. Try to enable it, if possible.
2099 if (addrBind.IsIPv6()) {
2100 #ifdef IPV6_V6ONLY
2101 #ifdef WIN32
2102 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
2103 #else
2104 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
2105 #endif
2106 #endif
2107 #ifdef WIN32
2108 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2109 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
2110 #endif
2113 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
2115 int nErr = WSAGetLastError();
2116 if (nErr == WSAEADDRINUSE)
2117 strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), _(PACKAGE_NAME));
2118 else
2119 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
2120 LogPrintf("%s\n", strError);
2121 CloseSocket(hListenSocket);
2122 return false;
2124 LogPrintf("Bound to %s\n", addrBind.ToString());
2126 // Listen for incoming connections
2127 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
2129 strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2130 LogPrintf("%s\n", strError);
2131 CloseSocket(hListenSocket);
2132 return false;
2135 vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
2137 if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
2138 AddLocal(addrBind, LOCAL_BIND);
2140 return true;
2143 void Discover(boost::thread_group& threadGroup)
2145 if (!fDiscover)
2146 return;
2148 #ifdef WIN32
2149 // Get local host IP
2150 char pszHostName[256] = "";
2151 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
2153 std::vector<CNetAddr> vaddr;
2154 if (LookupHost(pszHostName, vaddr, 0, true))
2156 for (const CNetAddr &addr : vaddr)
2158 if (AddLocal(addr, LOCAL_IF))
2159 LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
2163 #else
2164 // Get local host ip
2165 struct ifaddrs* myaddrs;
2166 if (getifaddrs(&myaddrs) == 0)
2168 for (struct ifaddrs* ifa = myaddrs; ifa != nullptr; ifa = ifa->ifa_next)
2170 if (ifa->ifa_addr == nullptr) continue;
2171 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
2172 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
2173 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
2174 if (ifa->ifa_addr->sa_family == AF_INET)
2176 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
2177 CNetAddr addr(s4->sin_addr);
2178 if (AddLocal(addr, LOCAL_IF))
2179 LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2181 else if (ifa->ifa_addr->sa_family == AF_INET6)
2183 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
2184 CNetAddr addr(s6->sin6_addr);
2185 if (AddLocal(addr, LOCAL_IF))
2186 LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2189 freeifaddrs(myaddrs);
2191 #endif
2194 void CConnman::SetNetworkActive(bool active)
2196 LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active);
2198 if (fNetworkActive == active) {
2199 return;
2202 fNetworkActive = active;
2204 if (!fNetworkActive) {
2205 LOCK(cs_vNodes);
2206 // Close sockets to all nodes
2207 for (CNode* pnode : vNodes) {
2208 pnode->CloseSocketDisconnect();
2212 uiInterface.NotifyNetworkActiveChanged(fNetworkActive);
2215 CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSeed1(nSeed1In)
2217 fNetworkActive = true;
2218 setBannedIsDirty = false;
2219 fAddressesInitialized = false;
2220 nLastNodeId = 0;
2221 nSendBufferMaxSize = 0;
2222 nReceiveFloodSize = 0;
2223 semOutbound = nullptr;
2224 semAddnode = nullptr;
2225 flagInterruptMsgProc = false;
2227 Options connOptions;
2228 Init(connOptions);
2231 NodeId CConnman::GetNewNodeId()
2233 return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
2237 bool CConnman::Bind(const CService &addr, unsigned int flags) {
2238 if (!(flags & BF_EXPLICIT) && IsLimited(addr))
2239 return false;
2240 std::string strError;
2241 if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
2242 if ((flags & BF_REPORT_ERROR) && clientInterface) {
2243 clientInterface->ThreadSafeMessageBox(strError, "", CClientUIInterface::MSG_ERROR);
2245 return false;
2247 return true;
2250 bool CConnman::InitBinds(const std::vector<CService>& binds, const std::vector<CService>& whiteBinds) {
2251 bool fBound = false;
2252 for (const auto& addrBind : binds) {
2253 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
2255 for (const auto& addrBind : whiteBinds) {
2256 fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
2258 if (binds.empty() && whiteBinds.empty()) {
2259 struct in_addr inaddr_any;
2260 inaddr_any.s_addr = INADDR_ANY;
2261 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
2262 fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
2264 return fBound;
2267 bool CConnman::Start(CScheduler& scheduler, const Options& connOptions)
2269 Init(connOptions);
2271 nTotalBytesRecv = 0;
2272 nTotalBytesSent = 0;
2273 nMaxOutboundTotalBytesSentInCycle = 0;
2274 nMaxOutboundCycleStartTime = 0;
2276 if (fListen && !InitBinds(connOptions.vBinds, connOptions.vWhiteBinds)) {
2277 if (clientInterface) {
2278 clientInterface->ThreadSafeMessageBox(
2279 _("Failed to listen on any port. Use -listen=0 if you want this."),
2280 "", CClientUIInterface::MSG_ERROR);
2282 return false;
2285 for (const auto& strDest : connOptions.vSeedNodes) {
2286 AddOneShot(strDest);
2289 if (clientInterface) {
2290 clientInterface->InitMessage(_("Loading P2P addresses..."));
2292 // Load addresses from peers.dat
2293 int64_t nStart = GetTimeMillis();
2295 CAddrDB adb;
2296 if (adb.Read(addrman))
2297 LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
2298 else {
2299 addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2300 LogPrintf("Invalid or missing peers.dat; recreating\n");
2301 DumpAddresses();
2304 if (clientInterface)
2305 clientInterface->InitMessage(_("Loading banlist..."));
2306 // Load addresses from banlist.dat
2307 nStart = GetTimeMillis();
2308 CBanDB bandb;
2309 banmap_t banmap;
2310 if (bandb.Read(banmap)) {
2311 SetBanned(banmap); // thread save setter
2312 SetBannedSetDirty(false); // no need to write down, just read data
2313 SweepBanned(); // sweep out unused entries
2315 LogPrint(BCLog::NET, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
2316 banmap.size(), GetTimeMillis() - nStart);
2317 } else {
2318 LogPrintf("Invalid or missing banlist.dat; recreating\n");
2319 SetBannedSetDirty(true); // force write
2320 DumpBanlist();
2323 uiInterface.InitMessage(_("Starting network threads..."));
2325 fAddressesInitialized = true;
2327 if (semOutbound == nullptr) {
2328 // initialize semaphore
2329 semOutbound = new CSemaphore(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
2331 if (semAddnode == nullptr) {
2332 // initialize semaphore
2333 semAddnode = new CSemaphore(nMaxAddnode);
2337 // Start threads
2339 assert(m_msgproc);
2340 InterruptSocks5(false);
2341 interruptNet.reset();
2342 flagInterruptMsgProc = false;
2345 std::unique_lock<std::mutex> lock(mutexMsgProc);
2346 fMsgProcWake = false;
2349 // Send and receive from sockets, accept connections
2350 threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
2352 if (!gArgs.GetBoolArg("-dnsseed", true))
2353 LogPrintf("DNS seeding disabled\n");
2354 else
2355 threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
2357 // Initiate outbound connections from -addnode
2358 threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
2360 if (connOptions.m_use_addrman_outgoing && !connOptions.m_specified_outgoing.empty()) {
2361 if (clientInterface) {
2362 clientInterface->ThreadSafeMessageBox(
2363 _("Cannot provide specific connections and have addrman find outgoing connections at the same."),
2364 "", CClientUIInterface::MSG_ERROR);
2366 return false;
2368 if (connOptions.m_use_addrman_outgoing || !connOptions.m_specified_outgoing.empty())
2369 threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this, connOptions.m_specified_outgoing)));
2371 // Process messages
2372 threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this)));
2374 // Dump network addresses
2375 scheduler.scheduleEvery(std::bind(&CConnman::DumpData, this), DUMP_ADDRESSES_INTERVAL * 1000);
2377 return true;
2380 class CNetCleanup
2382 public:
2383 CNetCleanup() {}
2385 ~CNetCleanup()
2387 #ifdef WIN32
2388 // Shutdown Windows Sockets
2389 WSACleanup();
2390 #endif
2393 instance_of_cnetcleanup;
2395 void CConnman::Interrupt()
2398 std::lock_guard<std::mutex> lock(mutexMsgProc);
2399 flagInterruptMsgProc = true;
2401 condMsgProc.notify_all();
2403 interruptNet();
2404 InterruptSocks5(true);
2406 if (semOutbound) {
2407 for (int i=0; i<(nMaxOutbound + nMaxFeeler); i++) {
2408 semOutbound->post();
2412 if (semAddnode) {
2413 for (int i=0; i<nMaxAddnode; i++) {
2414 semAddnode->post();
2419 void CConnman::Stop()
2421 if (threadMessageHandler.joinable())
2422 threadMessageHandler.join();
2423 if (threadOpenConnections.joinable())
2424 threadOpenConnections.join();
2425 if (threadOpenAddedConnections.joinable())
2426 threadOpenAddedConnections.join();
2427 if (threadDNSAddressSeed.joinable())
2428 threadDNSAddressSeed.join();
2429 if (threadSocketHandler.joinable())
2430 threadSocketHandler.join();
2432 if (fAddressesInitialized)
2434 DumpData();
2435 fAddressesInitialized = false;
2438 // Close sockets
2439 for (CNode* pnode : vNodes)
2440 pnode->CloseSocketDisconnect();
2441 for (ListenSocket& hListenSocket : vhListenSocket)
2442 if (hListenSocket.socket != INVALID_SOCKET)
2443 if (!CloseSocket(hListenSocket.socket))
2444 LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2446 // clean up some globals (to help leak detection)
2447 for (CNode *pnode : vNodes) {
2448 DeleteNode(pnode);
2450 for (CNode *pnode : vNodesDisconnected) {
2451 DeleteNode(pnode);
2453 vNodes.clear();
2454 vNodesDisconnected.clear();
2455 vhListenSocket.clear();
2456 delete semOutbound;
2457 semOutbound = nullptr;
2458 delete semAddnode;
2459 semAddnode = nullptr;
2462 void CConnman::DeleteNode(CNode* pnode)
2464 assert(pnode);
2465 bool fUpdateConnectionTime = false;
2466 m_msgproc->FinalizeNode(pnode->GetId(), fUpdateConnectionTime);
2467 if(fUpdateConnectionTime) {
2468 addrman.Connected(pnode->addr);
2470 delete pnode;
2473 CConnman::~CConnman()
2475 Interrupt();
2476 Stop();
2479 size_t CConnman::GetAddressCount() const
2481 return addrman.size();
2484 void CConnman::SetServices(const CService &addr, ServiceFlags nServices)
2486 addrman.SetServices(addr, nServices);
2489 void CConnman::MarkAddressGood(const CAddress& addr)
2491 addrman.Good(addr);
2494 void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
2496 addrman.Add(vAddr, addrFrom, nTimePenalty);
2499 std::vector<CAddress> CConnman::GetAddresses()
2501 return addrman.GetAddr();
2504 bool CConnman::AddNode(const std::string& strNode)
2506 LOCK(cs_vAddedNodes);
2507 for (const std::string& it : vAddedNodes) {
2508 if (strNode == it) return false;
2511 vAddedNodes.push_back(strNode);
2512 return true;
2515 bool CConnman::RemoveAddedNode(const std::string& strNode)
2517 LOCK(cs_vAddedNodes);
2518 for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
2519 if (strNode == *it) {
2520 vAddedNodes.erase(it);
2521 return true;
2524 return false;
2527 size_t CConnman::GetNodeCount(NumConnections flags)
2529 LOCK(cs_vNodes);
2530 if (flags == CConnman::CONNECTIONS_ALL) // Shortcut if we want total
2531 return vNodes.size();
2533 int nNum = 0;
2534 for (const auto& pnode : vNodes) {
2535 if (flags & (pnode->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT)) {
2536 nNum++;
2540 return nNum;
2543 void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats)
2545 vstats.clear();
2546 LOCK(cs_vNodes);
2547 vstats.reserve(vNodes.size());
2548 for (CNode* pnode : vNodes) {
2549 vstats.emplace_back();
2550 pnode->copyStats(vstats.back());
2554 bool CConnman::DisconnectNode(const std::string& strNode)
2556 LOCK(cs_vNodes);
2557 if (CNode* pnode = FindNode(strNode)) {
2558 pnode->fDisconnect = true;
2559 return true;
2561 return false;
2563 bool CConnman::DisconnectNode(NodeId id)
2565 LOCK(cs_vNodes);
2566 for(CNode* pnode : vNodes) {
2567 if (id == pnode->GetId()) {
2568 pnode->fDisconnect = true;
2569 return true;
2572 return false;
2575 void CConnman::RecordBytesRecv(uint64_t bytes)
2577 LOCK(cs_totalBytesRecv);
2578 nTotalBytesRecv += bytes;
2581 void CConnman::RecordBytesSent(uint64_t bytes)
2583 LOCK(cs_totalBytesSent);
2584 nTotalBytesSent += bytes;
2586 uint64_t now = GetTime();
2587 if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now)
2589 // timeframe expired, reset cycle
2590 nMaxOutboundCycleStartTime = now;
2591 nMaxOutboundTotalBytesSentInCycle = 0;
2594 // TODO, exclude whitebind peers
2595 nMaxOutboundTotalBytesSentInCycle += bytes;
2598 void CConnman::SetMaxOutboundTarget(uint64_t limit)
2600 LOCK(cs_totalBytesSent);
2601 nMaxOutboundLimit = limit;
2604 uint64_t CConnman::GetMaxOutboundTarget()
2606 LOCK(cs_totalBytesSent);
2607 return nMaxOutboundLimit;
2610 uint64_t CConnman::GetMaxOutboundTimeframe()
2612 LOCK(cs_totalBytesSent);
2613 return nMaxOutboundTimeframe;
2616 uint64_t CConnman::GetMaxOutboundTimeLeftInCycle()
2618 LOCK(cs_totalBytesSent);
2619 if (nMaxOutboundLimit == 0)
2620 return 0;
2622 if (nMaxOutboundCycleStartTime == 0)
2623 return nMaxOutboundTimeframe;
2625 uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe;
2626 uint64_t now = GetTime();
2627 return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime();
2630 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe)
2632 LOCK(cs_totalBytesSent);
2633 if (nMaxOutboundTimeframe != timeframe)
2635 // reset measure-cycle in case of changing
2636 // the timeframe
2637 nMaxOutboundCycleStartTime = GetTime();
2639 nMaxOutboundTimeframe = timeframe;
2642 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit)
2644 LOCK(cs_totalBytesSent);
2645 if (nMaxOutboundLimit == 0)
2646 return false;
2648 if (historicalBlockServingLimit)
2650 // keep a large enough buffer to at least relay each block once
2651 uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
2652 uint64_t buffer = timeLeftInCycle / 600 * MAX_BLOCK_SERIALIZED_SIZE;
2653 if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
2654 return true;
2656 else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
2657 return true;
2659 return false;
2662 uint64_t CConnman::GetOutboundTargetBytesLeft()
2664 LOCK(cs_totalBytesSent);
2665 if (nMaxOutboundLimit == 0)
2666 return 0;
2668 return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
2671 uint64_t CConnman::GetTotalBytesRecv()
2673 LOCK(cs_totalBytesRecv);
2674 return nTotalBytesRecv;
2677 uint64_t CConnman::GetTotalBytesSent()
2679 LOCK(cs_totalBytesSent);
2680 return nTotalBytesSent;
2683 ServiceFlags CConnman::GetLocalServices() const
2685 return nLocalServices;
2688 void CConnman::SetBestHeight(int height)
2690 nBestHeight.store(height, std::memory_order_release);
2693 int CConnman::GetBestHeight() const
2695 return nBestHeight.load(std::memory_order_acquire);
2698 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
2700 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) :
2701 nTimeConnected(GetSystemTimeInSeconds()),
2702 addr(addrIn),
2703 addrBind(addrBindIn),
2704 fInbound(fInboundIn),
2705 nKeyedNetGroup(nKeyedNetGroupIn),
2706 addrKnown(5000, 0.001),
2707 filterInventoryKnown(50000, 0.000001),
2708 id(idIn),
2709 nLocalHostNonce(nLocalHostNonceIn),
2710 nLocalServices(nLocalServicesIn),
2711 nMyStartingHeight(nMyStartingHeightIn),
2712 nSendVersion(0)
2714 nServices = NODE_NONE;
2715 nServicesExpected = NODE_NONE;
2716 hSocket = hSocketIn;
2717 nRecvVersion = INIT_PROTO_VERSION;
2718 nLastSend = 0;
2719 nLastRecv = 0;
2720 nSendBytes = 0;
2721 nRecvBytes = 0;
2722 nTimeOffset = 0;
2723 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
2724 nVersion = 0;
2725 strSubVer = "";
2726 fWhitelisted = false;
2727 fOneShot = false;
2728 fAddnode = false;
2729 fClient = false; // set by version message
2730 fFeeler = false;
2731 fSuccessfullyConnected = false;
2732 fDisconnect = false;
2733 nRefCount = 0;
2734 nSendSize = 0;
2735 nSendOffset = 0;
2736 hashContinue = uint256();
2737 nStartingHeight = -1;
2738 filterInventoryKnown.reset();
2739 fSendMempool = false;
2740 fGetAddr = false;
2741 nNextLocalAddrSend = 0;
2742 nNextAddrSend = 0;
2743 nNextInvSend = 0;
2744 fRelayTxes = false;
2745 fSentAddr = false;
2746 pfilter = new CBloomFilter();
2747 timeLastMempoolReq = 0;
2748 nLastBlockTime = 0;
2749 nLastTXTime = 0;
2750 nPingNonceSent = 0;
2751 nPingUsecStart = 0;
2752 nPingUsecTime = 0;
2753 fPingQueued = false;
2754 nMinPingUsecTime = std::numeric_limits<int64_t>::max();
2755 minFeeFilter = 0;
2756 lastSentFeeFilter = 0;
2757 nextSendTimeFeeFilter = 0;
2758 fPauseRecv = false;
2759 fPauseSend = false;
2760 nProcessQueueSize = 0;
2762 for (const std::string &msg : getAllNetMessageTypes())
2763 mapRecvBytesPerMsgCmd[msg] = 0;
2764 mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
2766 if (fLogIPs) {
2767 LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
2768 } else {
2769 LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
2773 CNode::~CNode()
2775 CloseSocket(hSocket);
2777 if (pfilter)
2778 delete pfilter;
2781 void CNode::AskFor(const CInv& inv)
2783 if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ)
2784 return;
2785 // a peer may not have multiple non-responded queue positions for a single inv item
2786 if (!setAskFor.insert(inv.hash).second)
2787 return;
2789 // We're using mapAskFor as a priority queue,
2790 // the key is the earliest time the request can be sent
2791 int64_t nRequestTime;
2792 limitedmap<uint256, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv.hash);
2793 if (it != mapAlreadyAskedFor.end())
2794 nRequestTime = it->second;
2795 else
2796 nRequestTime = 0;
2797 LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
2799 // Make sure not to reuse time indexes to keep things in the same order
2800 int64_t nNow = GetTimeMicros() - 1000000;
2801 static int64_t nLastTime;
2802 ++nLastTime;
2803 nNow = std::max(nNow, nLastTime);
2804 nLastTime = nNow;
2806 // Each retry is 2 minutes after the last
2807 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
2808 if (it != mapAlreadyAskedFor.end())
2809 mapAlreadyAskedFor.update(it, nRequestTime);
2810 else
2811 mapAlreadyAskedFor.insert(std::make_pair(inv.hash, nRequestTime));
2812 mapAskFor.insert(std::make_pair(nRequestTime, inv));
2815 bool CConnman::NodeFullyConnected(const CNode* pnode)
2817 return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
2820 void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg)
2822 size_t nMessageSize = msg.data.size();
2823 size_t nTotalSize = nMessageSize + CMessageHeader::HEADER_SIZE;
2824 LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command.c_str()), nMessageSize, pnode->GetId());
2826 std::vector<unsigned char> serializedHeader;
2827 serializedHeader.reserve(CMessageHeader::HEADER_SIZE);
2828 uint256 hash = Hash(msg.data.data(), msg.data.data() + nMessageSize);
2829 CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), nMessageSize);
2830 memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
2832 CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, serializedHeader, 0, hdr};
2834 size_t nBytesSent = 0;
2836 LOCK(pnode->cs_vSend);
2837 bool optimisticSend(pnode->vSendMsg.empty());
2839 //log total amount of bytes per command
2840 pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize;
2841 pnode->nSendSize += nTotalSize;
2843 if (pnode->nSendSize > nSendBufferMaxSize)
2844 pnode->fPauseSend = true;
2845 pnode->vSendMsg.push_back(std::move(serializedHeader));
2846 if (nMessageSize)
2847 pnode->vSendMsg.push_back(std::move(msg.data));
2849 // If write queue empty, attempt "optimistic write"
2850 if (optimisticSend == true)
2851 nBytesSent = SocketSendData(pnode);
2853 if (nBytesSent)
2854 RecordBytesSent(nBytesSent);
2857 bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
2859 CNode* found = nullptr;
2860 LOCK(cs_vNodes);
2861 for (auto&& pnode : vNodes) {
2862 if(pnode->GetId() == id) {
2863 found = pnode;
2864 break;
2867 return found != nullptr && NodeFullyConnected(found) && func(found);
2870 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds) {
2871 return nNow + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5);
2874 CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const
2876 return CSipHasher(nSeed0, nSeed1).Write(id);
2879 uint64_t CConnman::CalculateKeyedNetGroup(const CAddress& ad) const
2881 std::vector<unsigned char> vchNetGroup(ad.GetGroup());
2883 return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(vchNetGroup.data(), vchNetGroup.size()).Finalize();