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"
13 #include "chainparams.h"
14 #include "clientversion.h"
15 #include "consensus/consensus.h"
16 #include "crypto/common.h"
17 #include "crypto/sha256.h"
19 #include "primitives/transaction.h"
21 #include "scheduler.h"
22 #include "ui_interface.h"
23 #include "utilstrencodings.h"
32 #include <miniupnpc/miniupnpc.h>
33 #include <miniupnpc/miniwget.h>
34 #include <miniupnpc/upnpcommands.h>
35 #include <miniupnpc/upnperrors.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
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
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.
59 #ifndef PROTECTION_LEVEL_UNRESTRICTED
60 #define PROTECTION_LEVEL_UNRESTRICTED 10
62 #ifndef IPV6_PROTECTION_LEVEL
63 #define IPV6_PROTECTION_LEVEL 23
67 /** Used to pass flags to the Bind() function */
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;
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
)
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
)
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
;
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
135 const int64_t nOneWeek
= 7*24*60*60;
136 std::vector
<CAddress
> vSeedsOut
;
137 vSeedsOut
.reserve(vSeedsIn
.size());
138 for (std::vector
<SeedSpec6
>::const_iterator
i(vSeedsIn
.begin()); i
!= vSeedsIn
.end(); ++i
)
141 memcpy(&ip
, i
->addr
, sizeof(ip
));
142 CAddress
addr(CService(ip
, i
->port
), NODE_NETWORK
);
143 addr
.nTime
= GetTime() - GetRand(nOneWeek
) - nOneWeek
;
144 vSeedsOut
.push_back(addr
);
149 // get best local address for a particular peer as a CAddress
150 // Otherwise, return the unroutable 0.0.0.0 but filled in with
151 // the normal parameters, since the IP may be changed to a useful
153 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
)
155 CAddress
ret(CService(CNetAddr(),GetListenPort()), nLocalServices
);
157 if (GetLocal(addr
, paddrPeer
))
159 ret
= CAddress(addr
, nLocalServices
);
161 ret
.nTime
= GetAdjustedTime();
165 int GetnScore(const CService
& addr
)
167 LOCK(cs_mapLocalHost
);
168 if (mapLocalHost
.count(addr
) == LOCAL_NONE
)
170 return mapLocalHost
[addr
].nScore
;
173 // Is our peer's addrLocal potentially useful as an external IP source?
174 bool IsPeerAddrLocalGood(CNode
*pnode
)
176 CService addrLocal
= pnode
->GetAddrLocal();
177 return fDiscover
&& pnode
->addr
.IsRoutable() && addrLocal
.IsRoutable() &&
178 !IsLimited(addrLocal
.GetNetwork());
181 // pushes our own address to a peer
182 void AdvertiseLocal(CNode
*pnode
)
184 if (fListen
&& pnode
->fSuccessfullyConnected
)
186 CAddress addrLocal
= GetLocalAddress(&pnode
->addr
, pnode
->GetLocalServices());
187 // If discovery is enabled, sometimes give our peer the address it
188 // tells us that it sees us as in case it has a better idea of our
189 // address than we do.
190 if (IsPeerAddrLocalGood(pnode
) && (!addrLocal
.IsRoutable() ||
191 GetRand((GetnScore(addrLocal
) > LOCAL_MANUAL
) ? 8:2) == 0))
193 addrLocal
.SetIP(pnode
->GetAddrLocal());
195 if (addrLocal
.IsRoutable())
197 LogPrint(BCLog::NET
, "AdvertiseLocal: advertising address %s\n", addrLocal
.ToString());
198 FastRandomContext insecure_rand
;
199 pnode
->PushAddress(addrLocal
, insecure_rand
);
204 // learn a new local address
205 bool AddLocal(const CService
& addr
, int nScore
)
207 if (!addr
.IsRoutable())
210 if (!fDiscover
&& nScore
< LOCAL_MANUAL
)
216 LogPrintf("AddLocal(%s,%i)\n", addr
.ToString(), nScore
);
219 LOCK(cs_mapLocalHost
);
220 bool fAlready
= mapLocalHost
.count(addr
) > 0;
221 LocalServiceInfo
&info
= mapLocalHost
[addr
];
222 if (!fAlready
|| nScore
>= info
.nScore
) {
223 info
.nScore
= nScore
+ (fAlready
? 1 : 0);
224 info
.nPort
= addr
.GetPort();
231 bool AddLocal(const CNetAddr
&addr
, int nScore
)
233 return AddLocal(CService(addr
, GetListenPort()), nScore
);
236 bool RemoveLocal(const CService
& addr
)
238 LOCK(cs_mapLocalHost
);
239 LogPrintf("RemoveLocal(%s)\n", addr
.ToString());
240 mapLocalHost
.erase(addr
);
244 /** Make a particular network entirely off-limits (no automatic connects to it) */
245 void SetLimited(enum Network net
, bool fLimited
)
247 if (net
== NET_UNROUTABLE
|| net
== NET_INTERNAL
)
249 LOCK(cs_mapLocalHost
);
250 vfLimited
[net
] = fLimited
;
253 bool IsLimited(enum Network net
)
255 LOCK(cs_mapLocalHost
);
256 return vfLimited
[net
];
259 bool IsLimited(const CNetAddr
&addr
)
261 return IsLimited(addr
.GetNetwork());
264 /** vote for a local address */
265 bool SeenLocal(const CService
& addr
)
268 LOCK(cs_mapLocalHost
);
269 if (mapLocalHost
.count(addr
) == 0)
271 mapLocalHost
[addr
].nScore
++;
277 /** check whether a given address is potentially local */
278 bool IsLocal(const CService
& addr
)
280 LOCK(cs_mapLocalHost
);
281 return mapLocalHost
.count(addr
) > 0;
284 /** check whether a given network is one we can probably connect to */
285 bool IsReachable(enum Network net
)
287 LOCK(cs_mapLocalHost
);
288 return !vfLimited
[net
];
291 /** check whether a given address is in a network we can probably connect to */
292 bool IsReachable(const CNetAddr
& addr
)
294 enum Network net
= addr
.GetNetwork();
295 return IsReachable(net
);
299 CNode
* CConnman::FindNode(const CNetAddr
& ip
)
302 for (CNode
* pnode
: vNodes
)
303 if ((CNetAddr
)pnode
->addr
== ip
)
308 CNode
* CConnman::FindNode(const CSubNet
& subNet
)
311 for (CNode
* pnode
: vNodes
)
312 if (subNet
.Match((CNetAddr
)pnode
->addr
))
317 CNode
* CConnman::FindNode(const std::string
& addrName
)
320 for (CNode
* pnode
: vNodes
) {
321 if (pnode
->GetAddrName() == addrName
) {
328 CNode
* CConnman::FindNode(const CService
& addr
)
331 for (CNode
* pnode
: vNodes
)
332 if ((CService
)pnode
->addr
== addr
)
337 bool CConnman::CheckIncomingNonce(uint64_t nonce
)
340 for (CNode
* pnode
: vNodes
) {
341 if (!pnode
->fSuccessfullyConnected
&& !pnode
->fInbound
&& pnode
->GetLocalNonce() == nonce
)
347 /** Get the bind address for a socket as CAddress */
348 static CAddress
GetBindAddress(SOCKET sock
)
351 struct sockaddr_storage sockaddr_bind
;
352 socklen_t sockaddr_bind_len
= sizeof(sockaddr_bind
);
353 if (sock
!= INVALID_SOCKET
) {
354 if (!getsockname(sock
, (struct sockaddr
*)&sockaddr_bind
, &sockaddr_bind_len
)) {
355 addr_bind
.SetSockAddr((const struct sockaddr
*)&sockaddr_bind
);
357 LogPrint(BCLog::NET
, "Warning: getsockname failed\n");
363 CNode
* CConnman::ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
)
365 if (pszDest
== nullptr) {
366 if (IsLocal(addrConnect
))
369 // Look for an existing connection
370 CNode
* pnode
= FindNode((CService
)addrConnect
);
373 LogPrintf("Failed to open new connection, already connected\n");
379 LogPrint(BCLog::NET
, "trying connection %s lastseen=%.1fhrs\n",
380 pszDest
? pszDest
: addrConnect
.ToString(),
381 pszDest
? 0.0 : (double)(GetAdjustedTime() - addrConnect
.nTime
)/3600.0);
385 bool proxyConnectionFailed
= false;
386 if (pszDest
? ConnectSocketByName(addrConnect
, hSocket
, pszDest
, Params().GetDefaultPort(), nConnectTimeout
, &proxyConnectionFailed
) :
387 ConnectSocket(addrConnect
, hSocket
, nConnectTimeout
, &proxyConnectionFailed
))
389 if (!IsSelectableSocket(hSocket
)) {
390 LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
391 CloseSocket(hSocket
);
395 if (pszDest
&& addrConnect
.IsValid()) {
396 // It is possible that we already have a connection to the IP/port pszDest resolved to.
397 // In that case, drop the connection that was just created, and return the existing CNode instead.
398 // Also store the name we used to connect in that CNode, so that future FindNode() calls to that
399 // name catch this early.
401 CNode
* pnode
= FindNode((CService
)addrConnect
);
404 pnode
->MaybeSetAddrName(std::string(pszDest
));
405 CloseSocket(hSocket
);
406 LogPrintf("Failed to open new connection, already connected\n");
411 addrman
.Attempt(addrConnect
, fCountFailure
);
414 NodeId id
= GetNewNodeId();
415 uint64_t nonce
= GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE
).Write(id
).Finalize();
416 CAddress addr_bind
= GetBindAddress(hSocket
);
417 CNode
* pnode
= new CNode(id
, nLocalServices
, GetBestHeight(), hSocket
, addrConnect
, CalculateKeyedNetGroup(addrConnect
), nonce
, addr_bind
, pszDest
? pszDest
: "", false);
418 pnode
->nServicesExpected
= ServiceFlags(addrConnect
.nServices
& nRelevantServices
);
422 } else if (!proxyConnectionFailed
) {
423 // If connecting to the node failed, and failure is not caused by a problem connecting to
424 // the proxy, mark this as an attempt.
425 addrman
.Attempt(addrConnect
, fCountFailure
);
431 void CConnman::DumpBanlist()
433 SweepBanned(); // clean unused entries (if bantime has expired)
435 if (!BannedSetIsDirty())
438 int64_t nStart
= GetTimeMillis();
443 if (bandb
.Write(banmap
)) {
444 SetBannedSetDirty(false);
447 LogPrint(BCLog::NET
, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
448 banmap
.size(), GetTimeMillis() - nStart
);
451 void CNode::CloseSocketDisconnect()
455 if (hSocket
!= INVALID_SOCKET
)
457 LogPrint(BCLog::NET
, "disconnecting peer=%d\n", id
);
458 CloseSocket(hSocket
);
462 void CConnman::ClearBanned()
467 setBannedIsDirty
= true;
469 DumpBanlist(); //store banlist to disk
471 clientInterface
->BannedListChanged();
474 bool CConnman::IsBanned(CNetAddr ip
)
477 for (banmap_t::iterator it
= setBanned
.begin(); it
!= setBanned
.end(); it
++)
479 CSubNet subNet
= (*it
).first
;
480 CBanEntry banEntry
= (*it
).second
;
482 if (subNet
.Match(ip
) && GetTime() < banEntry
.nBanUntil
) {
489 bool CConnman::IsBanned(CSubNet subnet
)
492 banmap_t::iterator i
= setBanned
.find(subnet
);
493 if (i
!= setBanned
.end())
495 CBanEntry banEntry
= (*i
).second
;
496 if (GetTime() < banEntry
.nBanUntil
) {
503 void CConnman::Ban(const CNetAddr
& addr
, const BanReason
&banReason
, int64_t bantimeoffset
, bool sinceUnixEpoch
) {
504 CSubNet
subNet(addr
);
505 Ban(subNet
, banReason
, bantimeoffset
, sinceUnixEpoch
);
508 void CConnman::Ban(const CSubNet
& subNet
, const BanReason
&banReason
, int64_t bantimeoffset
, bool sinceUnixEpoch
) {
509 CBanEntry
banEntry(GetTime());
510 banEntry
.banReason
= banReason
;
511 if (bantimeoffset
<= 0)
513 bantimeoffset
= gArgs
.GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME
);
514 sinceUnixEpoch
= false;
516 banEntry
.nBanUntil
= (sinceUnixEpoch
? 0 : GetTime() )+bantimeoffset
;
520 if (setBanned
[subNet
].nBanUntil
< banEntry
.nBanUntil
) {
521 setBanned
[subNet
] = banEntry
;
522 setBannedIsDirty
= true;
528 clientInterface
->BannedListChanged();
531 for (CNode
* pnode
: vNodes
) {
532 if (subNet
.Match((CNetAddr
)pnode
->addr
))
533 pnode
->fDisconnect
= true;
536 if(banReason
== BanReasonManuallyAdded
)
537 DumpBanlist(); //store banlist to disk immediately if user requested ban
540 bool CConnman::Unban(const CNetAddr
&addr
) {
541 CSubNet
subNet(addr
);
542 return Unban(subNet
);
545 bool CConnman::Unban(const CSubNet
&subNet
) {
548 if (!setBanned
.erase(subNet
))
550 setBannedIsDirty
= true;
553 clientInterface
->BannedListChanged();
554 DumpBanlist(); //store banlist to disk immediately
558 void CConnman::GetBanned(banmap_t
&banMap
)
561 // Sweep the banlist so expired bans are not returned
563 banMap
= setBanned
; //create a thread safe copy
566 void CConnman::SetBanned(const banmap_t
&banMap
)
570 setBannedIsDirty
= true;
573 void CConnman::SweepBanned()
575 int64_t now
= GetTime();
578 banmap_t::iterator it
= setBanned
.begin();
579 while(it
!= setBanned
.end())
581 CSubNet subNet
= (*it
).first
;
582 CBanEntry banEntry
= (*it
).second
;
583 if(now
> banEntry
.nBanUntil
)
585 setBanned
.erase(it
++);
586 setBannedIsDirty
= true;
587 LogPrint(BCLog::NET
, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__
, subNet
.ToString());
594 bool CConnman::BannedSetIsDirty()
597 return setBannedIsDirty
;
600 void CConnman::SetBannedSetDirty(bool dirty
)
602 LOCK(cs_setBanned
); //reuse setBanned lock for the isDirty flag
603 setBannedIsDirty
= dirty
;
607 bool CConnman::IsWhitelistedRange(const CNetAddr
&addr
) {
608 for (const CSubNet
& subnet
: vWhitelistedRange
) {
609 if (subnet
.Match(addr
))
615 std::string
CNode::GetAddrName() const {
620 void CNode::MaybeSetAddrName(const std::string
& addrNameIn
) {
622 if (addrName
.empty()) {
623 addrName
= addrNameIn
;
627 CService
CNode::GetAddrLocal() const {
632 void CNode::SetAddrLocal(const CService
& addrLocalIn
) {
634 if (addrLocal
.IsValid()) {
635 error("Addr local already set for node: %i. Refusing to change from %s to %s", id
, addrLocal
.ToString(), addrLocalIn
.ToString());
637 addrLocal
= addrLocalIn
;
642 #define X(name) stats.name = name
643 void CNode::copyStats(CNodeStats
&stats
)
645 stats
.nodeid
= this->GetId();
657 stats
.addrName
= GetAddrName();
668 X(mapSendBytesPerMsgCmd
);
673 X(mapRecvBytesPerMsgCmd
);
678 // It is common for nodes with good ping times to suddenly become lagged,
679 // due to a new block arriving or other large transfer.
680 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
681 // since pingtime does not update until the ping is complete, which might take a while.
682 // So, if a ping is taking an unusually long time in flight,
683 // the caller can immediately detect that this is happening.
684 int64_t nPingUsecWait
= 0;
685 if ((0 != nPingNonceSent
) && (0 != nPingUsecStart
)) {
686 nPingUsecWait
= GetTimeMicros() - nPingUsecStart
;
689 // 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 :)
690 stats
.dPingTime
= (((double)nPingUsecTime
) / 1e6
);
691 stats
.dMinPing
= (((double)nMinPingUsecTime
) / 1e6
);
692 stats
.dPingWait
= (((double)nPingUsecWait
) / 1e6
);
694 // Leave string empty if addrLocal invalid (not filled in yet)
695 CService addrLocalUnlocked
= GetAddrLocal();
696 stats
.addrLocal
= addrLocalUnlocked
.IsValid() ? addrLocalUnlocked
.ToString() : "";
700 bool CNode::ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
)
703 int64_t nTimeMicros
= GetTimeMicros();
705 nLastRecv
= nTimeMicros
/ 1000000;
706 nRecvBytes
+= nBytes
;
709 // get current incomplete message, or create a new one
710 if (vRecvMsg
.empty() ||
711 vRecvMsg
.back().complete())
712 vRecvMsg
.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK
, INIT_PROTO_VERSION
));
714 CNetMessage
& msg
= vRecvMsg
.back();
716 // absorb network data
719 handled
= msg
.readHeader(pch
, nBytes
);
721 handled
= msg
.readData(pch
, nBytes
);
726 if (msg
.in_data
&& msg
.hdr
.nMessageSize
> MAX_PROTOCOL_MESSAGE_LENGTH
) {
727 LogPrint(BCLog::NET
, "Oversized message from peer=%i, disconnecting\n", GetId());
734 if (msg
.complete()) {
736 //store received bytes per message command
737 //to prevent a memory DOS, only allow valid commands
738 mapMsgCmdSize::iterator i
= mapRecvBytesPerMsgCmd
.find(msg
.hdr
.pchCommand
);
739 if (i
== mapRecvBytesPerMsgCmd
.end())
740 i
= mapRecvBytesPerMsgCmd
.find(NET_MESSAGE_COMMAND_OTHER
);
741 assert(i
!= mapRecvBytesPerMsgCmd
.end());
742 i
->second
+= msg
.hdr
.nMessageSize
+ CMessageHeader::HEADER_SIZE
;
744 msg
.nTime
= nTimeMicros
;
752 void CNode::SetSendVersion(int nVersionIn
)
754 // Send version may only be changed in the version message, and
755 // only one version message is allowed per session. We can therefore
756 // treat this value as const and even atomic as long as it's only used
757 // once a version message has been successfully processed. Any attempt to
758 // set this twice is an error.
759 if (nSendVersion
!= 0) {
760 error("Send version already set for node: %i. Refusing to change from %i to %i", id
, nSendVersion
, nVersionIn
);
762 nSendVersion
= nVersionIn
;
766 int CNode::GetSendVersion() const
768 // The send version should always be explicitly set to
769 // INIT_PROTO_VERSION rather than using this value until SetSendVersion
771 if (nSendVersion
== 0) {
772 error("Requesting unset send version for node: %i. Using %i", id
, INIT_PROTO_VERSION
);
773 return INIT_PROTO_VERSION
;
779 int CNetMessage::readHeader(const char *pch
, unsigned int nBytes
)
781 // copy data to temporary parsing buffer
782 unsigned int nRemaining
= 24 - nHdrPos
;
783 unsigned int nCopy
= std::min(nRemaining
, nBytes
);
785 memcpy(&hdrbuf
[nHdrPos
], pch
, nCopy
);
788 // if header incomplete, exit
792 // deserialize to CMessageHeader
796 catch (const std::exception
&) {
800 // reject messages larger than MAX_SIZE
801 if (hdr
.nMessageSize
> MAX_SIZE
)
804 // switch state to reading message data
810 int CNetMessage::readData(const char *pch
, unsigned int nBytes
)
812 unsigned int nRemaining
= hdr
.nMessageSize
- nDataPos
;
813 unsigned int nCopy
= std::min(nRemaining
, nBytes
);
815 if (vRecv
.size() < nDataPos
+ nCopy
) {
816 // Allocate up to 256 KiB ahead, but never more than the total message size.
817 vRecv
.resize(std::min(hdr
.nMessageSize
, nDataPos
+ nCopy
+ 256 * 1024));
820 hasher
.Write((const unsigned char*)pch
, nCopy
);
821 memcpy(&vRecv
[nDataPos
], pch
, nCopy
);
827 const uint256
& CNetMessage::GetMessageHash() const
830 if (data_hash
.IsNull())
831 hasher
.Finalize(data_hash
.begin());
843 // requires LOCK(cs_vSend)
844 size_t CConnman::SocketSendData(CNode
*pnode
) const
846 auto it
= pnode
->vSendMsg
.begin();
847 size_t nSentSize
= 0;
849 while (it
!= pnode
->vSendMsg
.end()) {
850 const auto &data
= *it
;
851 assert(data
.size() > pnode
->nSendOffset
);
854 LOCK(pnode
->cs_hSocket
);
855 if (pnode
->hSocket
== INVALID_SOCKET
)
857 nBytes
= send(pnode
->hSocket
, reinterpret_cast<const char*>(data
.data()) + pnode
->nSendOffset
, data
.size() - pnode
->nSendOffset
, MSG_NOSIGNAL
| MSG_DONTWAIT
);
860 pnode
->nLastSend
= GetSystemTimeInSeconds();
861 pnode
->nSendBytes
+= nBytes
;
862 pnode
->nSendOffset
+= nBytes
;
864 if (pnode
->nSendOffset
== data
.size()) {
865 pnode
->nSendOffset
= 0;
866 pnode
->nSendSize
-= data
.size();
867 pnode
->fPauseSend
= pnode
->nSendSize
> nSendBufferMaxSize
;
870 // could not send full message; stop sending more
876 int nErr
= WSAGetLastError();
877 if (nErr
!= WSAEWOULDBLOCK
&& nErr
!= WSAEMSGSIZE
&& nErr
!= WSAEINTR
&& nErr
!= WSAEINPROGRESS
)
879 LogPrintf("socket send error %s\n", NetworkErrorString(nErr
));
880 pnode
->CloseSocketDisconnect();
883 // couldn't send anything at all
888 if (it
== pnode
->vSendMsg
.end()) {
889 assert(pnode
->nSendOffset
== 0);
890 assert(pnode
->nSendSize
== 0);
892 pnode
->vSendMsg
.erase(pnode
->vSendMsg
.begin(), it
);
896 struct NodeEvictionCandidate
899 int64_t nTimeConnected
;
900 int64_t nMinPingUsecTime
;
901 int64_t nLastBlockTime
;
903 bool fRelevantServices
;
907 uint64_t nKeyedNetGroup
;
910 static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
912 return a
.nMinPingUsecTime
> b
.nMinPingUsecTime
;
915 static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
917 return a
.nTimeConnected
> b
.nTimeConnected
;
920 static bool CompareNetGroupKeyed(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
) {
921 return a
.nKeyedNetGroup
< b
.nKeyedNetGroup
;
924 static bool CompareNodeBlockTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
926 // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
927 if (a
.nLastBlockTime
!= b
.nLastBlockTime
) return a
.nLastBlockTime
< b
.nLastBlockTime
;
928 if (a
.fRelevantServices
!= b
.fRelevantServices
) return b
.fRelevantServices
;
929 return a
.nTimeConnected
> b
.nTimeConnected
;
932 static bool CompareNodeTXTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
934 // 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.
935 if (a
.nLastTXTime
!= b
.nLastTXTime
) return a
.nLastTXTime
< b
.nLastTXTime
;
936 if (a
.fRelayTxes
!= b
.fRelayTxes
) return b
.fRelayTxes
;
937 if (a
.fBloomFilter
!= b
.fBloomFilter
) return a
.fBloomFilter
;
938 return a
.nTimeConnected
> b
.nTimeConnected
;
941 /** Try to find a connection to evict when the node is full.
942 * Extreme care must be taken to avoid opening the node to attacker
943 * triggered network partitioning.
944 * The strategy used here is to protect a small number of peers
945 * for each of several distinct characteristics which are difficult
946 * to forge. In order to partition a node the attacker must be
947 * simultaneously better at all of them than honest peers.
949 bool CConnman::AttemptToEvictConnection()
951 std::vector
<NodeEvictionCandidate
> vEvictionCandidates
;
955 for (CNode
*node
: vNodes
) {
956 if (node
->fWhitelisted
)
960 if (node
->fDisconnect
)
962 NodeEvictionCandidate candidate
= {node
->GetId(), node
->nTimeConnected
, node
->nMinPingUsecTime
,
963 node
->nLastBlockTime
, node
->nLastTXTime
,
964 (node
->nServices
& nRelevantServices
) == nRelevantServices
,
965 node
->fRelayTxes
, node
->pfilter
!= nullptr, node
->addr
, node
->nKeyedNetGroup
};
966 vEvictionCandidates
.push_back(candidate
);
970 if (vEvictionCandidates
.empty()) return false;
972 // Protect connections with certain characteristics
974 // Deterministically select 4 peers to protect by netgroup.
975 // An attacker cannot predict which netgroups will be protected
976 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNetGroupKeyed
);
977 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
979 if (vEvictionCandidates
.empty()) return false;
981 // Protect the 8 nodes with the lowest minimum ping time.
982 // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
983 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), ReverseCompareNodeMinPingTime
);
984 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(8, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
986 if (vEvictionCandidates
.empty()) return false;
988 // Protect 4 nodes that most recently sent us transactions.
989 // An attacker cannot manipulate this metric without performing useful work.
990 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNodeTXTime
);
991 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
993 if (vEvictionCandidates
.empty()) return false;
995 // Protect 4 nodes that most recently sent us blocks.
996 // An attacker cannot manipulate this metric without performing useful work.
997 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNodeBlockTime
);
998 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
1000 if (vEvictionCandidates
.empty()) return false;
1002 // Protect the half of the remaining nodes which have been connected the longest.
1003 // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
1004 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), ReverseCompareNodeTimeConnected
);
1005 vEvictionCandidates
.erase(vEvictionCandidates
.end() - static_cast<int>(vEvictionCandidates
.size() / 2), vEvictionCandidates
.end());
1007 if (vEvictionCandidates
.empty()) return false;
1009 // Identify the network group with the most connections and youngest member.
1010 // (vEvictionCandidates is already sorted by reverse connect time)
1011 uint64_t naMostConnections
;
1012 unsigned int nMostConnections
= 0;
1013 int64_t nMostConnectionsTime
= 0;
1014 std::map
<uint64_t, std::vector
<NodeEvictionCandidate
> > mapNetGroupNodes
;
1015 for (const NodeEvictionCandidate
&node
: vEvictionCandidates
) {
1016 mapNetGroupNodes
[node
.nKeyedNetGroup
].push_back(node
);
1017 int64_t grouptime
= mapNetGroupNodes
[node
.nKeyedNetGroup
][0].nTimeConnected
;
1018 size_t groupsize
= mapNetGroupNodes
[node
.nKeyedNetGroup
].size();
1020 if (groupsize
> nMostConnections
|| (groupsize
== nMostConnections
&& grouptime
> nMostConnectionsTime
)) {
1021 nMostConnections
= groupsize
;
1022 nMostConnectionsTime
= grouptime
;
1023 naMostConnections
= node
.nKeyedNetGroup
;
1027 // Reduce to the network group with the most connections
1028 vEvictionCandidates
= std::move(mapNetGroupNodes
[naMostConnections
]);
1030 // Disconnect from the network group with the most connections
1031 NodeId evicted
= vEvictionCandidates
.front().id
;
1033 for(std::vector
<CNode
*>::const_iterator
it(vNodes
.begin()); it
!= vNodes
.end(); ++it
) {
1034 if ((*it
)->GetId() == evicted
) {
1035 (*it
)->fDisconnect
= true;
1042 void CConnman::AcceptConnection(const ListenSocket
& hListenSocket
) {
1043 struct sockaddr_storage sockaddr
;
1044 socklen_t len
= sizeof(sockaddr
);
1045 SOCKET hSocket
= accept(hListenSocket
.socket
, (struct sockaddr
*)&sockaddr
, &len
);
1048 int nMaxInbound
= nMaxConnections
- (nMaxOutbound
+ nMaxFeeler
);
1050 if (hSocket
!= INVALID_SOCKET
) {
1051 if (!addr
.SetSockAddr((const struct sockaddr
*)&sockaddr
)) {
1052 LogPrintf("Warning: Unknown socket family\n");
1056 bool whitelisted
= hListenSocket
.whitelisted
|| IsWhitelistedRange(addr
);
1059 for (CNode
* pnode
: vNodes
)
1060 if (pnode
->fInbound
)
1064 if (hSocket
== INVALID_SOCKET
)
1066 int nErr
= WSAGetLastError();
1067 if (nErr
!= WSAEWOULDBLOCK
)
1068 LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr
));
1072 if (!fNetworkActive
) {
1073 LogPrintf("connection from %s dropped: not accepting new connections\n", addr
.ToString());
1074 CloseSocket(hSocket
);
1078 if (!IsSelectableSocket(hSocket
))
1080 LogPrintf("connection from %s dropped: non-selectable socket\n", addr
.ToString());
1081 CloseSocket(hSocket
);
1085 // According to the internet TCP_NODELAY is not carried into accepted sockets
1086 // on all platforms. Set it again here just to be sure.
1087 SetSocketNoDelay(hSocket
);
1089 if (IsBanned(addr
) && !whitelisted
)
1091 LogPrintf("connection from %s dropped (banned)\n", addr
.ToString());
1092 CloseSocket(hSocket
);
1096 if (nInbound
>= nMaxInbound
)
1098 if (!AttemptToEvictConnection()) {
1099 // No connection to evict, disconnect the new connection
1100 LogPrint(BCLog::NET
, "failed to find an eviction candidate - connection dropped (full)\n");
1101 CloseSocket(hSocket
);
1106 NodeId id
= GetNewNodeId();
1107 uint64_t nonce
= GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE
).Write(id
).Finalize();
1108 CAddress addr_bind
= GetBindAddress(hSocket
);
1110 CNode
* pnode
= new CNode(id
, nLocalServices
, GetBestHeight(), hSocket
, addr
, CalculateKeyedNetGroup(addr
), nonce
, addr_bind
, "", true);
1112 pnode
->fWhitelisted
= whitelisted
;
1113 m_msgproc
->InitializeNode(pnode
);
1115 LogPrint(BCLog::NET
, "connection from %s accepted\n", addr
.ToString());
1119 vNodes
.push_back(pnode
);
1123 void CConnman::ThreadSocketHandler()
1125 unsigned int nPrevNodeCount
= 0;
1126 while (!interruptNet
)
1133 // Disconnect unused nodes
1134 std::vector
<CNode
*> vNodesCopy
= vNodes
;
1135 for (CNode
* pnode
: vNodesCopy
)
1137 if (pnode
->fDisconnect
)
1139 // remove from vNodes
1140 vNodes
.erase(remove(vNodes
.begin(), vNodes
.end(), pnode
), vNodes
.end());
1142 // release outbound grant (if any)
1143 pnode
->grantOutbound
.Release();
1145 // close socket and cleanup
1146 pnode
->CloseSocketDisconnect();
1148 // hold in disconnected pool until all refs are released
1150 vNodesDisconnected
.push_back(pnode
);
1155 // Delete disconnected nodes
1156 std::list
<CNode
*> vNodesDisconnectedCopy
= vNodesDisconnected
;
1157 for (CNode
* pnode
: vNodesDisconnectedCopy
)
1159 // wait until threads are done using it
1160 if (pnode
->GetRefCount() <= 0) {
1161 bool fDelete
= false;
1163 TRY_LOCK(pnode
->cs_inventory
, lockInv
);
1165 TRY_LOCK(pnode
->cs_vSend
, lockSend
);
1172 vNodesDisconnected
.remove(pnode
);
1181 vNodesSize
= vNodes
.size();
1183 if(vNodesSize
!= nPrevNodeCount
) {
1184 nPrevNodeCount
= vNodesSize
;
1186 clientInterface
->NotifyNumConnectionsChanged(nPrevNodeCount
);
1190 // Find which sockets have data to receive
1192 struct timeval timeout
;
1194 timeout
.tv_usec
= 50000; // frequency to poll pnode->vSend
1199 FD_ZERO(&fdsetRecv
);
1200 FD_ZERO(&fdsetSend
);
1201 FD_ZERO(&fdsetError
);
1202 SOCKET hSocketMax
= 0;
1203 bool have_fds
= false;
1205 for (const ListenSocket
& hListenSocket
: vhListenSocket
) {
1206 FD_SET(hListenSocket
.socket
, &fdsetRecv
);
1207 hSocketMax
= std::max(hSocketMax
, hListenSocket
.socket
);
1213 for (CNode
* pnode
: vNodes
)
1215 // Implement the following logic:
1216 // * If there is data to send, select() for sending data. As this only
1217 // happens when optimistic write failed, we choose to first drain the
1218 // write buffer in this case before receiving more. This avoids
1219 // needlessly queueing received data, if the remote peer is not themselves
1220 // receiving data. This means properly utilizing TCP flow control signalling.
1221 // * Otherwise, if there is space left in the receive buffer, select() for
1223 // * Hand off all complete messages to the processor, to be handled without
1226 bool select_recv
= !pnode
->fPauseRecv
;
1229 LOCK(pnode
->cs_vSend
);
1230 select_send
= !pnode
->vSendMsg
.empty();
1233 LOCK(pnode
->cs_hSocket
);
1234 if (pnode
->hSocket
== INVALID_SOCKET
)
1237 FD_SET(pnode
->hSocket
, &fdsetError
);
1238 hSocketMax
= std::max(hSocketMax
, pnode
->hSocket
);
1242 FD_SET(pnode
->hSocket
, &fdsetSend
);
1246 FD_SET(pnode
->hSocket
, &fdsetRecv
);
1251 int nSelect
= select(have_fds
? hSocketMax
+ 1 : 0,
1252 &fdsetRecv
, &fdsetSend
, &fdsetError
, &timeout
);
1256 if (nSelect
== SOCKET_ERROR
)
1260 int nErr
= WSAGetLastError();
1261 LogPrintf("socket select error %s\n", NetworkErrorString(nErr
));
1262 for (unsigned int i
= 0; i
<= hSocketMax
; i
++)
1263 FD_SET(i
, &fdsetRecv
);
1265 FD_ZERO(&fdsetSend
);
1266 FD_ZERO(&fdsetError
);
1267 if (!interruptNet
.sleep_for(std::chrono::milliseconds(timeout
.tv_usec
/1000)))
1272 // Accept new connections
1274 for (const ListenSocket
& hListenSocket
: vhListenSocket
)
1276 if (hListenSocket
.socket
!= INVALID_SOCKET
&& FD_ISSET(hListenSocket
.socket
, &fdsetRecv
))
1278 AcceptConnection(hListenSocket
);
1283 // Service each socket
1285 std::vector
<CNode
*> vNodesCopy
;
1288 vNodesCopy
= vNodes
;
1289 for (CNode
* pnode
: vNodesCopy
)
1292 for (CNode
* pnode
: vNodesCopy
)
1300 bool recvSet
= false;
1301 bool sendSet
= false;
1302 bool errorSet
= false;
1304 LOCK(pnode
->cs_hSocket
);
1305 if (pnode
->hSocket
== INVALID_SOCKET
)
1307 recvSet
= FD_ISSET(pnode
->hSocket
, &fdsetRecv
);
1308 sendSet
= FD_ISSET(pnode
->hSocket
, &fdsetSend
);
1309 errorSet
= FD_ISSET(pnode
->hSocket
, &fdsetError
);
1311 if (recvSet
|| errorSet
)
1313 // typical socket buffer is 8K-64K
1314 char pchBuf
[0x10000];
1317 LOCK(pnode
->cs_hSocket
);
1318 if (pnode
->hSocket
== INVALID_SOCKET
)
1320 nBytes
= recv(pnode
->hSocket
, pchBuf
, sizeof(pchBuf
), MSG_DONTWAIT
);
1324 bool notify
= false;
1325 if (!pnode
->ReceiveMsgBytes(pchBuf
, nBytes
, notify
))
1326 pnode
->CloseSocketDisconnect();
1327 RecordBytesRecv(nBytes
);
1329 size_t nSizeAdded
= 0;
1330 auto it(pnode
->vRecvMsg
.begin());
1331 for (; it
!= pnode
->vRecvMsg
.end(); ++it
) {
1332 if (!it
->complete())
1334 nSizeAdded
+= it
->vRecv
.size() + CMessageHeader::HEADER_SIZE
;
1337 LOCK(pnode
->cs_vProcessMsg
);
1338 pnode
->vProcessMsg
.splice(pnode
->vProcessMsg
.end(), pnode
->vRecvMsg
, pnode
->vRecvMsg
.begin(), it
);
1339 pnode
->nProcessQueueSize
+= nSizeAdded
;
1340 pnode
->fPauseRecv
= pnode
->nProcessQueueSize
> nReceiveFloodSize
;
1342 WakeMessageHandler();
1345 else if (nBytes
== 0)
1347 // socket closed gracefully
1348 if (!pnode
->fDisconnect
) {
1349 LogPrint(BCLog::NET
, "socket closed\n");
1351 pnode
->CloseSocketDisconnect();
1353 else if (nBytes
< 0)
1356 int nErr
= WSAGetLastError();
1357 if (nErr
!= WSAEWOULDBLOCK
&& nErr
!= WSAEMSGSIZE
&& nErr
!= WSAEINTR
&& nErr
!= WSAEINPROGRESS
)
1359 if (!pnode
->fDisconnect
)
1360 LogPrintf("socket recv error %s\n", NetworkErrorString(nErr
));
1361 pnode
->CloseSocketDisconnect();
1371 LOCK(pnode
->cs_vSend
);
1372 size_t nBytes
= SocketSendData(pnode
);
1374 RecordBytesSent(nBytes
);
1379 // Inactivity checking
1381 int64_t nTime
= GetSystemTimeInSeconds();
1382 if (nTime
- pnode
->nTimeConnected
> 60)
1384 if (pnode
->nLastRecv
== 0 || pnode
->nLastSend
== 0)
1386 LogPrint(BCLog::NET
, "socket no message in first 60 seconds, %d %d from %d\n", pnode
->nLastRecv
!= 0, pnode
->nLastSend
!= 0, pnode
->GetId());
1387 pnode
->fDisconnect
= true;
1389 else if (nTime
- pnode
->nLastSend
> TIMEOUT_INTERVAL
)
1391 LogPrintf("socket sending timeout: %is\n", nTime
- pnode
->nLastSend
);
1392 pnode
->fDisconnect
= true;
1394 else if (nTime
- pnode
->nLastRecv
> (pnode
->nVersion
> BIP0031_VERSION
? TIMEOUT_INTERVAL
: 90*60))
1396 LogPrintf("socket receive timeout: %is\n", nTime
- pnode
->nLastRecv
);
1397 pnode
->fDisconnect
= true;
1399 else if (pnode
->nPingNonceSent
&& pnode
->nPingUsecStart
+ TIMEOUT_INTERVAL
* 1000000 < GetTimeMicros())
1401 LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode
->nPingUsecStart
));
1402 pnode
->fDisconnect
= true;
1404 else if (!pnode
->fSuccessfullyConnected
)
1406 LogPrintf("version handshake timeout from %d\n", pnode
->GetId());
1407 pnode
->fDisconnect
= true;
1413 for (CNode
* pnode
: vNodesCopy
)
1419 void CConnman::WakeMessageHandler()
1422 std::lock_guard
<std::mutex
> lock(mutexMsgProc
);
1423 fMsgProcWake
= true;
1425 condMsgProc
.notify_one();
1434 void ThreadMapPort()
1436 std::string port
= strprintf("%u", GetListenPort());
1437 const char * multicastif
= nullptr;
1438 const char * minissdpdpath
= nullptr;
1439 struct UPNPDev
* devlist
= nullptr;
1442 #ifndef UPNPDISCOVER_SUCCESS
1444 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0);
1445 #elif MINIUPNPC_API_VERSION < 14
1448 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0, 0, &error
);
1450 /* miniupnpc 1.9.20150730 */
1452 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0, 0, 2, &error
);
1455 struct UPNPUrls urls
;
1456 struct IGDdatas data
;
1459 r
= UPNP_GetValidIGD(devlist
, &urls
, &data
, lanaddr
, sizeof(lanaddr
));
1463 char externalIPAddress
[40];
1464 r
= UPNP_GetExternalIPAddress(urls
.controlURL
, data
.first
.servicetype
, externalIPAddress
);
1465 if(r
!= UPNPCOMMAND_SUCCESS
)
1466 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r
);
1469 if(externalIPAddress
[0])
1472 if(LookupHost(externalIPAddress
, resolved
, false)) {
1473 LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved
.ToString().c_str());
1474 AddLocal(resolved
, LOCAL_UPNP
);
1478 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1482 std::string strDesc
= "Bitcoin " + FormatFullVersion();
1486 #ifndef UPNPDISCOVER_SUCCESS
1488 r
= UPNP_AddPortMapping(urls
.controlURL
, data
.first
.servicetype
,
1489 port
.c_str(), port
.c_str(), lanaddr
, strDesc
.c_str(), "TCP", 0);
1492 r
= UPNP_AddPortMapping(urls
.controlURL
, data
.first
.servicetype
,
1493 port
.c_str(), port
.c_str(), lanaddr
, strDesc
.c_str(), "TCP", 0, "0");
1496 if(r
!=UPNPCOMMAND_SUCCESS
)
1497 LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1498 port
, port
, lanaddr
, r
, strupnperror(r
));
1500 LogPrintf("UPnP Port Mapping successful.\n");
1502 MilliSleep(20*60*1000); // Refresh every 20 minutes
1505 catch (const boost::thread_interrupted
&)
1507 r
= UPNP_DeletePortMapping(urls
.controlURL
, data
.first
.servicetype
, port
.c_str(), "TCP", 0);
1508 LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r
);
1509 freeUPNPDevlist(devlist
); devlist
= nullptr;
1510 FreeUPNPUrls(&urls
);
1514 LogPrintf("No valid UPnP IGDs found\n");
1515 freeUPNPDevlist(devlist
); devlist
= nullptr;
1517 FreeUPNPUrls(&urls
);
1521 void MapPort(bool fUseUPnP
)
1523 static boost::thread
* upnp_thread
= nullptr;
1528 upnp_thread
->interrupt();
1529 upnp_thread
->join();
1532 upnp_thread
= new boost::thread(boost::bind(&TraceThread
<void (*)()>, "upnp", &ThreadMapPort
));
1534 else if (upnp_thread
) {
1535 upnp_thread
->interrupt();
1536 upnp_thread
->join();
1538 upnp_thread
= nullptr;
1545 // Intentionally left blank.
1554 static std::string
GetDNSHost(const CDNSSeedData
& data
, ServiceFlags
* requiredServiceBits
)
1556 //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
1557 if (!data
.supportsServiceBitsFiltering
|| *requiredServiceBits
== NODE_NETWORK
) {
1558 *requiredServiceBits
= NODE_NETWORK
;
1562 // See chainparams.cpp, most dnsseeds only support one or two possible servicebits hostnames
1563 return strprintf("x%x.%s", *requiredServiceBits
, data
.host
);
1567 void CConnman::ThreadDNSAddressSeed()
1569 // goal: only query DNS seeds if address need is acute
1570 // Avoiding DNS seeds when we don't need them improves user privacy by
1571 // creating fewer identifying DNS requests, reduces trust by giving seeds
1572 // less influence on the network topology, and reduces traffic to the seeds.
1573 if ((addrman
.size() > 0) &&
1574 (!gArgs
.GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED
))) {
1575 if (!interruptNet
.sleep_for(std::chrono::seconds(11)))
1580 for (auto pnode
: vNodes
) {
1581 nRelevant
+= pnode
->fSuccessfullyConnected
&& ((pnode
->nServices
& nRelevantServices
) == nRelevantServices
);
1583 if (nRelevant
>= 2) {
1584 LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1589 const std::vector
<CDNSSeedData
> &vSeeds
= Params().DNSSeeds();
1592 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1594 for (const CDNSSeedData
&seed
: vSeeds
) {
1598 if (HaveNameProxy()) {
1599 AddOneShot(seed
.host
);
1601 std::vector
<CNetAddr
> vIPs
;
1602 std::vector
<CAddress
> vAdd
;
1603 ServiceFlags requiredServiceBits
= nRelevantServices
;
1604 std::string host
= GetDNSHost(seed
, &requiredServiceBits
);
1605 CNetAddr resolveSource
;
1606 if (!resolveSource
.SetInternal(host
)) {
1609 if (LookupHost(host
.c_str(), vIPs
, 0, true))
1611 for (const CNetAddr
& ip
: vIPs
)
1613 int nOneDay
= 24*3600;
1614 CAddress addr
= CAddress(CService(ip
, Params().GetDefaultPort()), requiredServiceBits
);
1615 addr
.nTime
= GetTime() - 3*nOneDay
- GetRand(4*nOneDay
); // use a random age between 3 and 7 days old
1616 vAdd
.push_back(addr
);
1619 addrman
.Add(vAdd
, resolveSource
);
1624 LogPrintf("%d addresses found from DNS seeds\n", found
);
1638 void CConnman::DumpAddresses()
1640 int64_t nStart
= GetTimeMillis();
1645 LogPrint(BCLog::NET
, "Flushed %d addresses to peers.dat %dms\n",
1646 addrman
.size(), GetTimeMillis() - nStart
);
1649 void CConnman::DumpData()
1655 void CConnman::ProcessOneShot()
1657 std::string strDest
;
1660 if (vOneShots
.empty())
1662 strDest
= vOneShots
.front();
1663 vOneShots
.pop_front();
1666 CSemaphoreGrant
grant(*semOutbound
, true);
1668 if (!OpenNetworkConnection(addr
, false, &grant
, strDest
.c_str(), true))
1669 AddOneShot(strDest
);
1673 void CConnman::ThreadOpenConnections(const std::vector
<std::string
> connect
)
1675 // Connect to specific addresses
1676 if (!connect
.empty())
1678 for (int64_t nLoop
= 0;; nLoop
++)
1681 for (const std::string
& strAddr
: connect
)
1683 CAddress
addr(CService(), NODE_NONE
);
1684 OpenNetworkConnection(addr
, false, nullptr, strAddr
.c_str());
1685 for (int i
= 0; i
< 10 && i
< nLoop
; i
++)
1687 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1691 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1696 // Initiate network connections
1697 int64_t nStart
= GetTime();
1699 // Minimum time before next feeler connection (in microseconds).
1700 int64_t nNextFeeler
= PoissonNextSend(nStart
*1000*1000, FEELER_INTERVAL
);
1701 while (!interruptNet
)
1705 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1708 CSemaphoreGrant
grant(*semOutbound
);
1712 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1713 if (addrman
.size() == 0 && (GetTime() - nStart
> 60)) {
1714 static bool done
= false;
1716 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1718 local
.SetInternal("fixedseeds");
1719 addrman
.Add(convertSeed6(Params().FixedSeeds()), local
);
1725 // Choose an address to connect to based on most recently seen
1727 CAddress addrConnect
;
1729 // Only connect out to one peer per network group (/16 for IPv4).
1730 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1732 int nOutboundRelevant
= 0;
1733 std::set
<std::vector
<unsigned char> > setConnected
;
1736 for (CNode
* pnode
: vNodes
) {
1737 if (!pnode
->fInbound
&& !pnode
->fAddnode
) {
1739 // Count the peers that have all relevant services
1740 if (pnode
->fSuccessfullyConnected
&& !pnode
->fFeeler
&& ((pnode
->nServices
& nRelevantServices
) == nRelevantServices
)) {
1741 nOutboundRelevant
++;
1743 // Netgroups for inbound and addnode peers are not excluded because our goal here
1744 // is to not use multiple of our limited outbound slots on a single netgroup
1745 // but inbound and addnode peers do not use our outbound slots. Inbound peers
1746 // also have the added issue that they're attacker controlled and could be used
1747 // to prevent us from connecting to particular hosts if we used them here.
1748 setConnected
.insert(pnode
->addr
.GetGroup());
1754 // Feeler Connections
1757 // * Increase the number of connectable addresses in the tried table.
1760 // * Choose a random address from new and attempt to connect to it if we can connect
1761 // successfully it is added to tried.
1762 // * Start attempting feeler connections only after node finishes making outbound
1764 // * Only make a feeler connection once every few minutes.
1766 bool fFeeler
= false;
1767 if (nOutbound
>= nMaxOutbound
) {
1768 int64_t nTime
= GetTimeMicros(); // The current time right now (in microseconds).
1769 if (nTime
> nNextFeeler
) {
1770 nNextFeeler
= PoissonNextSend(nTime
, FEELER_INTERVAL
);
1777 int64_t nANow
= GetAdjustedTime();
1779 while (!interruptNet
)
1781 CAddrInfo addr
= addrman
.Select(fFeeler
);
1783 // if we selected an invalid address, restart
1784 if (!addr
.IsValid() || setConnected
.count(addr
.GetGroup()) || IsLocal(addr
))
1787 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1788 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1789 // already-connected network ranges, ...) before trying new addrman addresses.
1794 if (IsLimited(addr
))
1797 // only connect to full nodes
1798 if ((addr
.nServices
& REQUIRED_SERVICES
) != REQUIRED_SERVICES
)
1801 // only consider very recently tried nodes after 30 failed attempts
1802 if (nANow
- addr
.nLastTry
< 600 && nTries
< 30)
1805 // only consider nodes missing relevant services after 40 failed attempts and only if less than half the outbound are up.
1806 ServiceFlags nRequiredServices
= nRelevantServices
;
1807 if (nTries
>= 40 && nOutbound
< (nMaxOutbound
>> 1)) {
1808 nRequiredServices
= REQUIRED_SERVICES
;
1811 if ((addr
.nServices
& nRequiredServices
) != nRequiredServices
) {
1815 // do not allow non-default ports, unless after 50 invalid addresses selected already
1816 if (addr
.GetPort() != Params().GetDefaultPort() && nTries
< 50)
1821 // regardless of the services assumed to be available, only require the minimum if half or more outbound have relevant services
1822 if (nOutboundRelevant
>= (nMaxOutbound
>> 1)) {
1823 addrConnect
.nServices
= REQUIRED_SERVICES
;
1825 addrConnect
.nServices
= nRequiredServices
;
1830 if (addrConnect
.IsValid()) {
1833 // Add small amount of random noise before connection to avoid synchronization.
1834 int randsleep
= GetRandInt(FEELER_SLEEP_WINDOW
* 1000);
1835 if (!interruptNet
.sleep_for(std::chrono::milliseconds(randsleep
)))
1837 LogPrint(BCLog::NET
, "Making feeler connection to %s\n", addrConnect
.ToString());
1840 OpenNetworkConnection(addrConnect
, (int)setConnected
.size() >= std::min(nMaxConnections
- 1, 2), &grant
, nullptr, false, fFeeler
);
1845 std::vector
<AddedNodeInfo
> CConnman::GetAddedNodeInfo()
1847 std::vector
<AddedNodeInfo
> ret
;
1849 std::list
<std::string
> lAddresses(0);
1851 LOCK(cs_vAddedNodes
);
1852 ret
.reserve(vAddedNodes
.size());
1853 for (const std::string
& strAddNode
: vAddedNodes
)
1854 lAddresses
.push_back(strAddNode
);
1858 // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
1859 std::map
<CService
, bool> mapConnected
;
1860 std::map
<std::string
, std::pair
<bool, CService
>> mapConnectedByName
;
1863 for (const CNode
* pnode
: vNodes
) {
1864 if (pnode
->addr
.IsValid()) {
1865 mapConnected
[pnode
->addr
] = pnode
->fInbound
;
1867 std::string addrName
= pnode
->GetAddrName();
1868 if (!addrName
.empty()) {
1869 mapConnectedByName
[std::move(addrName
)] = std::make_pair(pnode
->fInbound
, static_cast<const CService
&>(pnode
->addr
));
1874 for (const std::string
& strAddNode
: lAddresses
) {
1875 CService
service(LookupNumeric(strAddNode
.c_str(), Params().GetDefaultPort()));
1876 if (service
.IsValid()) {
1877 // strAddNode is an IP:port
1878 auto it
= mapConnected
.find(service
);
1879 if (it
!= mapConnected
.end()) {
1880 ret
.push_back(AddedNodeInfo
{strAddNode
, service
, true, it
->second
});
1882 ret
.push_back(AddedNodeInfo
{strAddNode
, CService(), false, false});
1885 // strAddNode is a name
1886 auto it
= mapConnectedByName
.find(strAddNode
);
1887 if (it
!= mapConnectedByName
.end()) {
1888 ret
.push_back(AddedNodeInfo
{strAddNode
, it
->second
.second
, true, it
->second
.first
});
1890 ret
.push_back(AddedNodeInfo
{strAddNode
, CService(), false, false});
1898 void CConnman::ThreadOpenAddedConnections()
1901 LOCK(cs_vAddedNodes
);
1902 vAddedNodes
= gArgs
.GetArgs("-addnode");
1907 CSemaphoreGrant
grant(*semAddnode
);
1908 std::vector
<AddedNodeInfo
> vInfo
= GetAddedNodeInfo();
1910 for (const AddedNodeInfo
& info
: vInfo
) {
1911 if (!info
.fConnected
) {
1912 if (!grant
.TryAcquire()) {
1913 // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
1914 // the addednodeinfo state might change.
1917 // If strAddedNode is an IP/port, decode it immediately, so
1918 // OpenNetworkConnection can detect existing connections to that IP/port.
1920 CService
service(LookupNumeric(info
.strAddedNode
.c_str(), Params().GetDefaultPort()));
1921 OpenNetworkConnection(CAddress(service
, NODE_NONE
), false, &grant
, info
.strAddedNode
.c_str(), false, false, true);
1922 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1926 // Retry every 60 seconds if a connection was attempted, otherwise two seconds
1927 if (!interruptNet
.sleep_for(std::chrono::seconds(tried
? 60 : 2)))
1932 // if successful, this moves the passed grant to the constructed node
1933 bool CConnman::OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
, const char *pszDest
, bool fOneShot
, bool fFeeler
, bool fAddnode
)
1936 // Initiate outbound network connection
1941 if (!fNetworkActive
) {
1945 if (IsLocal(addrConnect
) ||
1946 FindNode((CNetAddr
)addrConnect
) || IsBanned(addrConnect
) ||
1947 FindNode(addrConnect
.ToStringIPPort()))
1949 } else if (FindNode(std::string(pszDest
)))
1952 CNode
* pnode
= ConnectNode(addrConnect
, pszDest
, fCountFailure
);
1957 grantOutbound
->MoveTo(pnode
->grantOutbound
);
1959 pnode
->fOneShot
= true;
1961 pnode
->fFeeler
= true;
1963 pnode
->fAddnode
= true;
1965 m_msgproc
->InitializeNode(pnode
);
1968 vNodes
.push_back(pnode
);
1974 void CConnman::ThreadMessageHandler()
1976 while (!flagInterruptMsgProc
)
1978 std::vector
<CNode
*> vNodesCopy
;
1981 vNodesCopy
= vNodes
;
1982 for (CNode
* pnode
: vNodesCopy
) {
1987 bool fMoreWork
= false;
1989 for (CNode
* pnode
: vNodesCopy
)
1991 if (pnode
->fDisconnect
)
1995 bool fMoreNodeWork
= m_msgproc
->ProcessMessages(pnode
, flagInterruptMsgProc
);
1996 fMoreWork
|= (fMoreNodeWork
&& !pnode
->fPauseSend
);
1997 if (flagInterruptMsgProc
)
2001 LOCK(pnode
->cs_sendProcessing
);
2002 m_msgproc
->SendMessages(pnode
, flagInterruptMsgProc
);
2005 if (flagInterruptMsgProc
)
2011 for (CNode
* pnode
: vNodesCopy
)
2015 std::unique_lock
<std::mutex
> lock(mutexMsgProc
);
2017 condMsgProc
.wait_until(lock
, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake
; });
2019 fMsgProcWake
= false;
2028 bool CConnman::BindListenPort(const CService
&addrBind
, std::string
& strError
, bool fWhitelisted
)
2033 // Create socket for listening for incoming connections
2034 struct sockaddr_storage sockaddr
;
2035 socklen_t len
= sizeof(sockaddr
);
2036 if (!addrBind
.GetSockAddr((struct sockaddr
*)&sockaddr
, &len
))
2038 strError
= strprintf("Error: Bind address family for %s not supported", addrBind
.ToString());
2039 LogPrintf("%s\n", strError
);
2043 SOCKET hListenSocket
= socket(((struct sockaddr
*)&sockaddr
)->sa_family
, SOCK_STREAM
, IPPROTO_TCP
);
2044 if (hListenSocket
== INVALID_SOCKET
)
2046 strError
= strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2047 LogPrintf("%s\n", strError
);
2050 if (!IsSelectableSocket(hListenSocket
))
2052 strError
= "Error: Couldn't create a listenable socket for incoming connections";
2053 LogPrintf("%s\n", strError
);
2060 // Different way of disabling SIGPIPE on BSD
2061 setsockopt(hListenSocket
, SOL_SOCKET
, SO_NOSIGPIPE
, (void*)&nOne
, sizeof(int));
2063 // Allow binding if the port is still in TIME_WAIT state after
2064 // the program was closed and restarted.
2065 setsockopt(hListenSocket
, SOL_SOCKET
, SO_REUSEADDR
, (void*)&nOne
, sizeof(int));
2066 // Disable Nagle's algorithm
2067 setsockopt(hListenSocket
, IPPROTO_TCP
, TCP_NODELAY
, (void*)&nOne
, sizeof(int));
2069 setsockopt(hListenSocket
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&nOne
, sizeof(int));
2070 setsockopt(hListenSocket
, IPPROTO_TCP
, TCP_NODELAY
, (const char*)&nOne
, sizeof(int));
2073 // Set to non-blocking, incoming connections will also inherit this
2074 if (!SetSocketNonBlocking(hListenSocket
, true)) {
2075 CloseSocket(hListenSocket
);
2076 strError
= strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
2077 LogPrintf("%s\n", strError
);
2081 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2082 // and enable it by default or not. Try to enable it, if possible.
2083 if (addrBind
.IsIPv6()) {
2086 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_V6ONLY
, (const char*)&nOne
, sizeof(int));
2088 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_V6ONLY
, (void*)&nOne
, sizeof(int));
2092 int nProtLevel
= PROTECTION_LEVEL_UNRESTRICTED
;
2093 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_PROTECTION_LEVEL
, (const char*)&nProtLevel
, sizeof(int));
2097 if (::bind(hListenSocket
, (struct sockaddr
*)&sockaddr
, len
) == SOCKET_ERROR
)
2099 int nErr
= WSAGetLastError();
2100 if (nErr
== WSAEADDRINUSE
)
2101 strError
= strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind
.ToString(), _(PACKAGE_NAME
));
2103 strError
= strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind
.ToString(), NetworkErrorString(nErr
));
2104 LogPrintf("%s\n", strError
);
2105 CloseSocket(hListenSocket
);
2108 LogPrintf("Bound to %s\n", addrBind
.ToString());
2110 // Listen for incoming connections
2111 if (listen(hListenSocket
, SOMAXCONN
) == SOCKET_ERROR
)
2113 strError
= strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2114 LogPrintf("%s\n", strError
);
2115 CloseSocket(hListenSocket
);
2119 vhListenSocket
.push_back(ListenSocket(hListenSocket
, fWhitelisted
));
2121 if (addrBind
.IsRoutable() && fDiscover
&& !fWhitelisted
)
2122 AddLocal(addrBind
, LOCAL_BIND
);
2127 void Discover(boost::thread_group
& threadGroup
)
2133 // Get local host IP
2134 char pszHostName
[256] = "";
2135 if (gethostname(pszHostName
, sizeof(pszHostName
)) != SOCKET_ERROR
)
2137 std::vector
<CNetAddr
> vaddr
;
2138 if (LookupHost(pszHostName
, vaddr
, 0, true))
2140 for (const CNetAddr
&addr
: vaddr
)
2142 if (AddLocal(addr
, LOCAL_IF
))
2143 LogPrintf("%s: %s - %s\n", __func__
, pszHostName
, addr
.ToString());
2148 // Get local host ip
2149 struct ifaddrs
* myaddrs
;
2150 if (getifaddrs(&myaddrs
) == 0)
2152 for (struct ifaddrs
* ifa
= myaddrs
; ifa
!= nullptr; ifa
= ifa
->ifa_next
)
2154 if (ifa
->ifa_addr
== nullptr) continue;
2155 if ((ifa
->ifa_flags
& IFF_UP
) == 0) continue;
2156 if (strcmp(ifa
->ifa_name
, "lo") == 0) continue;
2157 if (strcmp(ifa
->ifa_name
, "lo0") == 0) continue;
2158 if (ifa
->ifa_addr
->sa_family
== AF_INET
)
2160 struct sockaddr_in
* s4
= (struct sockaddr_in
*)(ifa
->ifa_addr
);
2161 CNetAddr
addr(s4
->sin_addr
);
2162 if (AddLocal(addr
, LOCAL_IF
))
2163 LogPrintf("%s: IPv4 %s: %s\n", __func__
, ifa
->ifa_name
, addr
.ToString());
2165 else if (ifa
->ifa_addr
->sa_family
== AF_INET6
)
2167 struct sockaddr_in6
* s6
= (struct sockaddr_in6
*)(ifa
->ifa_addr
);
2168 CNetAddr
addr(s6
->sin6_addr
);
2169 if (AddLocal(addr
, LOCAL_IF
))
2170 LogPrintf("%s: IPv6 %s: %s\n", __func__
, ifa
->ifa_name
, addr
.ToString());
2173 freeifaddrs(myaddrs
);
2178 void CConnman::SetNetworkActive(bool active
)
2180 LogPrint(BCLog::NET
, "SetNetworkActive: %s\n", active
);
2182 if (fNetworkActive
== active
) {
2186 fNetworkActive
= active
;
2188 if (!fNetworkActive
) {
2190 // Close sockets to all nodes
2191 for (CNode
* pnode
: vNodes
) {
2192 pnode
->CloseSocketDisconnect();
2196 uiInterface
.NotifyNetworkActiveChanged(fNetworkActive
);
2199 CConnman::CConnman(uint64_t nSeed0In
, uint64_t nSeed1In
) : nSeed0(nSeed0In
), nSeed1(nSeed1In
)
2201 fNetworkActive
= true;
2202 setBannedIsDirty
= false;
2203 fAddressesInitialized
= false;
2205 nSendBufferMaxSize
= 0;
2206 nReceiveFloodSize
= 0;
2207 semOutbound
= nullptr;
2208 semAddnode
= nullptr;
2209 flagInterruptMsgProc
= false;
2211 Options connOptions
;
2215 NodeId
CConnman::GetNewNodeId()
2217 return nLastNodeId
.fetch_add(1, std::memory_order_relaxed
);
2221 bool CConnman::Bind(const CService
&addr
, unsigned int flags
) {
2222 if (!(flags
& BF_EXPLICIT
) && IsLimited(addr
))
2224 std::string strError
;
2225 if (!BindListenPort(addr
, strError
, (flags
& BF_WHITELIST
) != 0)) {
2226 if ((flags
& BF_REPORT_ERROR
) && clientInterface
) {
2227 clientInterface
->ThreadSafeMessageBox(strError
, "", CClientUIInterface::MSG_ERROR
);
2234 bool CConnman::InitBinds(const std::vector
<CService
>& binds
, const std::vector
<CService
>& whiteBinds
) {
2235 bool fBound
= false;
2236 for (const auto& addrBind
: binds
) {
2237 fBound
|= Bind(addrBind
, (BF_EXPLICIT
| BF_REPORT_ERROR
));
2239 for (const auto& addrBind
: whiteBinds
) {
2240 fBound
|= Bind(addrBind
, (BF_EXPLICIT
| BF_REPORT_ERROR
| BF_WHITELIST
));
2242 if (binds
.empty() && whiteBinds
.empty()) {
2243 struct in_addr inaddr_any
;
2244 inaddr_any
.s_addr
= INADDR_ANY
;
2245 fBound
|= Bind(CService(in6addr_any
, GetListenPort()), BF_NONE
);
2246 fBound
|= Bind(CService(inaddr_any
, GetListenPort()), !fBound
? BF_REPORT_ERROR
: BF_NONE
);
2251 bool CConnman::Start(CScheduler
& scheduler
, const Options
& connOptions
)
2255 nTotalBytesRecv
= 0;
2256 nTotalBytesSent
= 0;
2257 nMaxOutboundTotalBytesSentInCycle
= 0;
2258 nMaxOutboundCycleStartTime
= 0;
2260 if (fListen
&& !InitBinds(connOptions
.vBinds
, connOptions
.vWhiteBinds
)) {
2261 if (clientInterface
) {
2262 clientInterface
->ThreadSafeMessageBox(
2263 _("Failed to listen on any port. Use -listen=0 if you want this."),
2264 "", CClientUIInterface::MSG_ERROR
);
2269 for (const auto& strDest
: connOptions
.vSeedNodes
) {
2270 AddOneShot(strDest
);
2273 if (clientInterface
) {
2274 clientInterface
->InitMessage(_("Loading P2P addresses..."));
2276 // Load addresses from peers.dat
2277 int64_t nStart
= GetTimeMillis();
2280 if (adb
.Read(addrman
))
2281 LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman
.size(), GetTimeMillis() - nStart
);
2283 addrman
.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2284 LogPrintf("Invalid or missing peers.dat; recreating\n");
2288 if (clientInterface
)
2289 clientInterface
->InitMessage(_("Loading banlist..."));
2290 // Load addresses from banlist.dat
2291 nStart
= GetTimeMillis();
2294 if (bandb
.Read(banmap
)) {
2295 SetBanned(banmap
); // thread save setter
2296 SetBannedSetDirty(false); // no need to write down, just read data
2297 SweepBanned(); // sweep out unused entries
2299 LogPrint(BCLog::NET
, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
2300 banmap
.size(), GetTimeMillis() - nStart
);
2302 LogPrintf("Invalid or missing banlist.dat; recreating\n");
2303 SetBannedSetDirty(true); // force write
2307 uiInterface
.InitMessage(_("Starting network threads..."));
2309 fAddressesInitialized
= true;
2311 if (semOutbound
== nullptr) {
2312 // initialize semaphore
2313 semOutbound
= new CSemaphore(std::min((nMaxOutbound
+ nMaxFeeler
), nMaxConnections
));
2315 if (semAddnode
== nullptr) {
2316 // initialize semaphore
2317 semAddnode
= new CSemaphore(nMaxAddnode
);
2324 InterruptSocks5(false);
2325 interruptNet
.reset();
2326 flagInterruptMsgProc
= false;
2329 std::unique_lock
<std::mutex
> lock(mutexMsgProc
);
2330 fMsgProcWake
= false;
2333 // Send and receive from sockets, accept connections
2334 threadSocketHandler
= std::thread(&TraceThread
<std::function
<void()> >, "net", std::function
<void()>(std::bind(&CConnman::ThreadSocketHandler
, this)));
2336 if (!gArgs
.GetBoolArg("-dnsseed", true))
2337 LogPrintf("DNS seeding disabled\n");
2339 threadDNSAddressSeed
= std::thread(&TraceThread
<std::function
<void()> >, "dnsseed", std::function
<void()>(std::bind(&CConnman::ThreadDNSAddressSeed
, this)));
2341 // Initiate outbound connections from -addnode
2342 threadOpenAddedConnections
= std::thread(&TraceThread
<std::function
<void()> >, "addcon", std::function
<void()>(std::bind(&CConnman::ThreadOpenAddedConnections
, this)));
2344 if (connOptions
.m_use_addrman_outgoing
&& !connOptions
.m_specified_outgoing
.empty()) {
2345 if (clientInterface
) {
2346 clientInterface
->ThreadSafeMessageBox(
2347 _("Cannot provide specific connections and have addrman find outgoing connections at the same."),
2348 "", CClientUIInterface::MSG_ERROR
);
2352 if (connOptions
.m_use_addrman_outgoing
|| !connOptions
.m_specified_outgoing
.empty())
2353 threadOpenConnections
= std::thread(&TraceThread
<std::function
<void()> >, "opencon", std::function
<void()>(std::bind(&CConnman::ThreadOpenConnections
, this, connOptions
.m_specified_outgoing
)));
2356 threadMessageHandler
= std::thread(&TraceThread
<std::function
<void()> >, "msghand", std::function
<void()>(std::bind(&CConnman::ThreadMessageHandler
, this)));
2358 // Dump network addresses
2359 scheduler
.scheduleEvery(std::bind(&CConnman::DumpData
, this), DUMP_ADDRESSES_INTERVAL
* 1000);
2372 // Shutdown Windows Sockets
2377 instance_of_cnetcleanup
;
2379 void CConnman::Interrupt()
2382 std::lock_guard
<std::mutex
> lock(mutexMsgProc
);
2383 flagInterruptMsgProc
= true;
2385 condMsgProc
.notify_all();
2388 InterruptSocks5(true);
2391 for (int i
=0; i
<(nMaxOutbound
+ nMaxFeeler
); i
++) {
2392 semOutbound
->post();
2397 for (int i
=0; i
<nMaxAddnode
; i
++) {
2403 void CConnman::Stop()
2405 if (threadMessageHandler
.joinable())
2406 threadMessageHandler
.join();
2407 if (threadOpenConnections
.joinable())
2408 threadOpenConnections
.join();
2409 if (threadOpenAddedConnections
.joinable())
2410 threadOpenAddedConnections
.join();
2411 if (threadDNSAddressSeed
.joinable())
2412 threadDNSAddressSeed
.join();
2413 if (threadSocketHandler
.joinable())
2414 threadSocketHandler
.join();
2416 if (fAddressesInitialized
)
2419 fAddressesInitialized
= false;
2423 for (CNode
* pnode
: vNodes
)
2424 pnode
->CloseSocketDisconnect();
2425 for (ListenSocket
& hListenSocket
: vhListenSocket
)
2426 if (hListenSocket
.socket
!= INVALID_SOCKET
)
2427 if (!CloseSocket(hListenSocket
.socket
))
2428 LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2430 // clean up some globals (to help leak detection)
2431 for (CNode
*pnode
: vNodes
) {
2434 for (CNode
*pnode
: vNodesDisconnected
) {
2438 vNodesDisconnected
.clear();
2439 vhListenSocket
.clear();
2441 semOutbound
= nullptr;
2443 semAddnode
= nullptr;
2446 void CConnman::DeleteNode(CNode
* pnode
)
2449 bool fUpdateConnectionTime
= false;
2450 m_msgproc
->FinalizeNode(pnode
->GetId(), fUpdateConnectionTime
);
2451 if(fUpdateConnectionTime
) {
2452 addrman
.Connected(pnode
->addr
);
2457 CConnman::~CConnman()
2463 size_t CConnman::GetAddressCount() const
2465 return addrman
.size();
2468 void CConnman::SetServices(const CService
&addr
, ServiceFlags nServices
)
2470 addrman
.SetServices(addr
, nServices
);
2473 void CConnman::MarkAddressGood(const CAddress
& addr
)
2478 void CConnman::AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
)
2480 addrman
.Add(vAddr
, addrFrom
, nTimePenalty
);
2483 std::vector
<CAddress
> CConnman::GetAddresses()
2485 return addrman
.GetAddr();
2488 bool CConnman::AddNode(const std::string
& strNode
)
2490 LOCK(cs_vAddedNodes
);
2491 for(std::vector
<std::string
>::const_iterator it
= vAddedNodes
.begin(); it
!= vAddedNodes
.end(); ++it
) {
2496 vAddedNodes
.push_back(strNode
);
2500 bool CConnman::RemoveAddedNode(const std::string
& strNode
)
2502 LOCK(cs_vAddedNodes
);
2503 for(std::vector
<std::string
>::iterator it
= vAddedNodes
.begin(); it
!= vAddedNodes
.end(); ++it
) {
2504 if (strNode
== *it
) {
2505 vAddedNodes
.erase(it
);
2512 size_t CConnman::GetNodeCount(NumConnections flags
)
2515 if (flags
== CConnman::CONNECTIONS_ALL
) // Shortcut if we want total
2516 return vNodes
.size();
2519 for(std::vector
<CNode
*>::const_iterator it
= vNodes
.begin(); it
!= vNodes
.end(); ++it
)
2520 if (flags
& ((*it
)->fInbound
? CONNECTIONS_IN
: CONNECTIONS_OUT
))
2526 void CConnman::GetNodeStats(std::vector
<CNodeStats
>& vstats
)
2530 vstats
.reserve(vNodes
.size());
2531 for(std::vector
<CNode
*>::iterator it
= vNodes
.begin(); it
!= vNodes
.end(); ++it
) {
2533 vstats
.emplace_back();
2534 pnode
->copyStats(vstats
.back());
2538 bool CConnman::DisconnectNode(const std::string
& strNode
)
2541 if (CNode
* pnode
= FindNode(strNode
)) {
2542 pnode
->fDisconnect
= true;
2547 bool CConnman::DisconnectNode(NodeId id
)
2550 for(CNode
* pnode
: vNodes
) {
2551 if (id
== pnode
->GetId()) {
2552 pnode
->fDisconnect
= true;
2559 void CConnman::RecordBytesRecv(uint64_t bytes
)
2561 LOCK(cs_totalBytesRecv
);
2562 nTotalBytesRecv
+= bytes
;
2565 void CConnman::RecordBytesSent(uint64_t bytes
)
2567 LOCK(cs_totalBytesSent
);
2568 nTotalBytesSent
+= bytes
;
2570 uint64_t now
= GetTime();
2571 if (nMaxOutboundCycleStartTime
+ nMaxOutboundTimeframe
< now
)
2573 // timeframe expired, reset cycle
2574 nMaxOutboundCycleStartTime
= now
;
2575 nMaxOutboundTotalBytesSentInCycle
= 0;
2578 // TODO, exclude whitebind peers
2579 nMaxOutboundTotalBytesSentInCycle
+= bytes
;
2582 void CConnman::SetMaxOutboundTarget(uint64_t limit
)
2584 LOCK(cs_totalBytesSent
);
2585 nMaxOutboundLimit
= limit
;
2588 uint64_t CConnman::GetMaxOutboundTarget()
2590 LOCK(cs_totalBytesSent
);
2591 return nMaxOutboundLimit
;
2594 uint64_t CConnman::GetMaxOutboundTimeframe()
2596 LOCK(cs_totalBytesSent
);
2597 return nMaxOutboundTimeframe
;
2600 uint64_t CConnman::GetMaxOutboundTimeLeftInCycle()
2602 LOCK(cs_totalBytesSent
);
2603 if (nMaxOutboundLimit
== 0)
2606 if (nMaxOutboundCycleStartTime
== 0)
2607 return nMaxOutboundTimeframe
;
2609 uint64_t cycleEndTime
= nMaxOutboundCycleStartTime
+ nMaxOutboundTimeframe
;
2610 uint64_t now
= GetTime();
2611 return (cycleEndTime
< now
) ? 0 : cycleEndTime
- GetTime();
2614 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe
)
2616 LOCK(cs_totalBytesSent
);
2617 if (nMaxOutboundTimeframe
!= timeframe
)
2619 // reset measure-cycle in case of changing
2621 nMaxOutboundCycleStartTime
= GetTime();
2623 nMaxOutboundTimeframe
= timeframe
;
2626 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit
)
2628 LOCK(cs_totalBytesSent
);
2629 if (nMaxOutboundLimit
== 0)
2632 if (historicalBlockServingLimit
)
2634 // keep a large enough buffer to at least relay each block once
2635 uint64_t timeLeftInCycle
= GetMaxOutboundTimeLeftInCycle();
2636 uint64_t buffer
= timeLeftInCycle
/ 600 * MAX_BLOCK_SERIALIZED_SIZE
;
2637 if (buffer
>= nMaxOutboundLimit
|| nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
- buffer
)
2640 else if (nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
)
2646 uint64_t CConnman::GetOutboundTargetBytesLeft()
2648 LOCK(cs_totalBytesSent
);
2649 if (nMaxOutboundLimit
== 0)
2652 return (nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
) ? 0 : nMaxOutboundLimit
- nMaxOutboundTotalBytesSentInCycle
;
2655 uint64_t CConnman::GetTotalBytesRecv()
2657 LOCK(cs_totalBytesRecv
);
2658 return nTotalBytesRecv
;
2661 uint64_t CConnman::GetTotalBytesSent()
2663 LOCK(cs_totalBytesSent
);
2664 return nTotalBytesSent
;
2667 ServiceFlags
CConnman::GetLocalServices() const
2669 return nLocalServices
;
2672 void CConnman::SetBestHeight(int height
)
2674 nBestHeight
.store(height
, std::memory_order_release
);
2677 int CConnman::GetBestHeight() const
2679 return nBestHeight
.load(std::memory_order_acquire
);
2682 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize
; }
2684 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
) :
2685 nTimeConnected(GetSystemTimeInSeconds()),
2687 addrBind(addrBindIn
),
2688 fInbound(fInboundIn
),
2689 nKeyedNetGroup(nKeyedNetGroupIn
),
2690 addrKnown(5000, 0.001),
2691 filterInventoryKnown(50000, 0.000001),
2693 nLocalHostNonce(nLocalHostNonceIn
),
2694 nLocalServices(nLocalServicesIn
),
2695 nMyStartingHeight(nMyStartingHeightIn
),
2698 nServices
= NODE_NONE
;
2699 nServicesExpected
= NODE_NONE
;
2700 hSocket
= hSocketIn
;
2701 nRecvVersion
= INIT_PROTO_VERSION
;
2707 addrName
= addrNameIn
== "" ? addr
.ToStringIPPort() : addrNameIn
;
2710 fWhitelisted
= false;
2713 fClient
= false; // set by version message
2715 fSuccessfullyConnected
= false;
2716 fDisconnect
= false;
2720 hashContinue
= uint256();
2721 nStartingHeight
= -1;
2722 filterInventoryKnown
.reset();
2723 fSendMempool
= false;
2725 nNextLocalAddrSend
= 0;
2730 pfilter
= new CBloomFilter();
2731 timeLastMempoolReq
= 0;
2737 fPingQueued
= false;
2738 nMinPingUsecTime
= std::numeric_limits
<int64_t>::max();
2740 lastSentFeeFilter
= 0;
2741 nextSendTimeFeeFilter
= 0;
2744 nProcessQueueSize
= 0;
2746 for (const std::string
&msg
: getAllNetMessageTypes())
2747 mapRecvBytesPerMsgCmd
[msg
] = 0;
2748 mapRecvBytesPerMsgCmd
[NET_MESSAGE_COMMAND_OTHER
] = 0;
2751 LogPrint(BCLog::NET
, "Added connection to %s peer=%d\n", addrName
, id
);
2753 LogPrint(BCLog::NET
, "Added connection peer=%d\n", id
);
2759 CloseSocket(hSocket
);
2765 void CNode::AskFor(const CInv
& inv
)
2767 if (mapAskFor
.size() > MAPASKFOR_MAX_SZ
|| setAskFor
.size() > SETASKFOR_MAX_SZ
)
2769 // a peer may not have multiple non-responded queue positions for a single inv item
2770 if (!setAskFor
.insert(inv
.hash
).second
)
2773 // We're using mapAskFor as a priority queue,
2774 // the key is the earliest time the request can be sent
2775 int64_t nRequestTime
;
2776 limitedmap
<uint256
, int64_t>::const_iterator it
= mapAlreadyAskedFor
.find(inv
.hash
);
2777 if (it
!= mapAlreadyAskedFor
.end())
2778 nRequestTime
= it
->second
;
2781 LogPrint(BCLog::NET
, "askfor %s %d (%s) peer=%d\n", inv
.ToString(), nRequestTime
, DateTimeStrFormat("%H:%M:%S", nRequestTime
/1000000), id
);
2783 // Make sure not to reuse time indexes to keep things in the same order
2784 int64_t nNow
= GetTimeMicros() - 1000000;
2785 static int64_t nLastTime
;
2787 nNow
= std::max(nNow
, nLastTime
);
2790 // Each retry is 2 minutes after the last
2791 nRequestTime
= std::max(nRequestTime
+ 2 * 60 * 1000000, nNow
);
2792 if (it
!= mapAlreadyAskedFor
.end())
2793 mapAlreadyAskedFor
.update(it
, nRequestTime
);
2795 mapAlreadyAskedFor
.insert(std::make_pair(inv
.hash
, nRequestTime
));
2796 mapAskFor
.insert(std::make_pair(nRequestTime
, inv
));
2799 bool CConnman::NodeFullyConnected(const CNode
* pnode
)
2801 return pnode
&& pnode
->fSuccessfullyConnected
&& !pnode
->fDisconnect
;
2804 void CConnman::PushMessage(CNode
* pnode
, CSerializedNetMsg
&& msg
)
2806 size_t nMessageSize
= msg
.data
.size();
2807 size_t nTotalSize
= nMessageSize
+ CMessageHeader::HEADER_SIZE
;
2808 LogPrint(BCLog::NET
, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg
.command
.c_str()), nMessageSize
, pnode
->GetId());
2810 std::vector
<unsigned char> serializedHeader
;
2811 serializedHeader
.reserve(CMessageHeader::HEADER_SIZE
);
2812 uint256 hash
= Hash(msg
.data
.data(), msg
.data
.data() + nMessageSize
);
2813 CMessageHeader
hdr(Params().MessageStart(), msg
.command
.c_str(), nMessageSize
);
2814 memcpy(hdr
.pchChecksum
, hash
.begin(), CMessageHeader::CHECKSUM_SIZE
);
2816 CVectorWriter
{SER_NETWORK
, INIT_PROTO_VERSION
, serializedHeader
, 0, hdr
};
2818 size_t nBytesSent
= 0;
2820 LOCK(pnode
->cs_vSend
);
2821 bool optimisticSend(pnode
->vSendMsg
.empty());
2823 //log total amount of bytes per command
2824 pnode
->mapSendBytesPerMsgCmd
[msg
.command
] += nTotalSize
;
2825 pnode
->nSendSize
+= nTotalSize
;
2827 if (pnode
->nSendSize
> nSendBufferMaxSize
)
2828 pnode
->fPauseSend
= true;
2829 pnode
->vSendMsg
.push_back(std::move(serializedHeader
));
2831 pnode
->vSendMsg
.push_back(std::move(msg
.data
));
2833 // If write queue empty, attempt "optimistic write"
2834 if (optimisticSend
== true)
2835 nBytesSent
= SocketSendData(pnode
);
2838 RecordBytesSent(nBytesSent
);
2841 bool CConnman::ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
)
2843 CNode
* found
= nullptr;
2845 for (auto&& pnode
: vNodes
) {
2846 if(pnode
->GetId() == id
) {
2851 return found
!= nullptr && NodeFullyConnected(found
) && func(found
);
2854 int64_t PoissonNextSend(int64_t nNow
, int average_interval_seconds
) {
2855 return nNow
+ (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds
* -1000000.0 + 0.5);
2858 CSipHasher
CConnman::GetDeterministicRandomizer(uint64_t id
) const
2860 return CSipHasher(nSeed0
, nSeed1
).Write(id
);
2863 uint64_t CConnman::CalculateKeyedNetGroup(const CAddress
& ad
) const
2865 std::vector
<unsigned char> vchNetGroup(ad
.GetGroup());
2867 return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP
).Write(vchNetGroup
.data(), vchNetGroup
.size()).Finalize();