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 const static std::string NET_MESSAGE_COMMAND_OTHER
= "*other*";
69 static const uint64_t RANDOMIZER_ID_NETGROUP
= 0x6c0edd8036ef4036ULL
; // SHA256("netgroup")[0:8]
70 static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE
= 0xd93e69e2bbfa5735ULL
; // SHA256("localhostnonce")[0:8]
72 // Global state variables
74 bool fDiscover
= true;
76 bool fRelayTxes
= true;
77 CCriticalSection cs_mapLocalHost
;
78 std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
79 static bool vfLimited
[NET_MAX
] = {};
80 std::string strSubVersion
;
82 limitedmap
<uint256
, int64_t> mapAlreadyAskedFor(MAX_INV_SZ
);
84 // Signals for message handling
85 static CNodeSignals g_signals
;
86 CNodeSignals
& GetNodeSignals() { return g_signals
; }
88 void CConnman::AddOneShot(const std::string
& strDest
)
91 vOneShots
.push_back(strDest
);
94 unsigned short GetListenPort()
96 return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
99 // find 'best' local address for a particular peer
100 bool GetLocal(CService
& addr
, const CNetAddr
*paddrPeer
)
106 int nBestReachability
= -1;
108 LOCK(cs_mapLocalHost
);
109 for (std::map
<CNetAddr
, LocalServiceInfo
>::iterator it
= mapLocalHost
.begin(); it
!= mapLocalHost
.end(); it
++)
111 int nScore
= (*it
).second
.nScore
;
112 int nReachability
= (*it
).first
.GetReachabilityFrom(paddrPeer
);
113 if (nReachability
> nBestReachability
|| (nReachability
== nBestReachability
&& nScore
> nBestScore
))
115 addr
= CService((*it
).first
, (*it
).second
.nPort
);
116 nBestReachability
= nReachability
;
121 return nBestScore
>= 0;
124 //! Convert the pnSeeds6 array into usable address objects.
125 static std::vector
<CAddress
> convertSeed6(const std::vector
<SeedSpec6
> &vSeedsIn
)
127 // It'll only connect to one or two seed nodes because once it connects,
128 // it'll get a pile of addresses with newer timestamps.
129 // Seed nodes are given a random 'last seen time' of between one and two
131 const int64_t nOneWeek
= 7*24*60*60;
132 std::vector
<CAddress
> vSeedsOut
;
133 vSeedsOut
.reserve(vSeedsIn
.size());
134 for (std::vector
<SeedSpec6
>::const_iterator
i(vSeedsIn
.begin()); i
!= vSeedsIn
.end(); ++i
)
137 memcpy(&ip
, i
->addr
, sizeof(ip
));
138 CAddress
addr(CService(ip
, i
->port
), NODE_NETWORK
);
139 addr
.nTime
= GetTime() - GetRand(nOneWeek
) - nOneWeek
;
140 vSeedsOut
.push_back(addr
);
145 // get best local address for a particular peer as a CAddress
146 // Otherwise, return the unroutable 0.0.0.0 but filled in with
147 // the normal parameters, since the IP may be changed to a useful
149 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
)
151 CAddress
ret(CService(CNetAddr(),GetListenPort()), nLocalServices
);
153 if (GetLocal(addr
, paddrPeer
))
155 ret
= CAddress(addr
, nLocalServices
);
157 ret
.nTime
= GetAdjustedTime();
161 int GetnScore(const CService
& addr
)
163 LOCK(cs_mapLocalHost
);
164 if (mapLocalHost
.count(addr
) == LOCAL_NONE
)
166 return mapLocalHost
[addr
].nScore
;
169 // Is our peer's addrLocal potentially useful as an external IP source?
170 bool IsPeerAddrLocalGood(CNode
*pnode
)
172 CService addrLocal
= pnode
->GetAddrLocal();
173 return fDiscover
&& pnode
->addr
.IsRoutable() && addrLocal
.IsRoutable() &&
174 !IsLimited(addrLocal
.GetNetwork());
177 // pushes our own address to a peer
178 void AdvertiseLocal(CNode
*pnode
)
180 if (fListen
&& pnode
->fSuccessfullyConnected
)
182 CAddress addrLocal
= GetLocalAddress(&pnode
->addr
, pnode
->GetLocalServices());
183 // If discovery is enabled, sometimes give our peer the address it
184 // tells us that it sees us as in case it has a better idea of our
185 // address than we do.
186 if (IsPeerAddrLocalGood(pnode
) && (!addrLocal
.IsRoutable() ||
187 GetRand((GetnScore(addrLocal
) > LOCAL_MANUAL
) ? 8:2) == 0))
189 addrLocal
.SetIP(pnode
->GetAddrLocal());
191 if (addrLocal
.IsRoutable())
193 LogPrint(BCLog::NET
, "AdvertiseLocal: advertising address %s\n", addrLocal
.ToString());
194 FastRandomContext insecure_rand
;
195 pnode
->PushAddress(addrLocal
, insecure_rand
);
200 // learn a new local address
201 bool AddLocal(const CService
& addr
, int nScore
)
203 if (!addr
.IsRoutable())
206 if (!fDiscover
&& nScore
< LOCAL_MANUAL
)
212 LogPrintf("AddLocal(%s,%i)\n", addr
.ToString(), nScore
);
215 LOCK(cs_mapLocalHost
);
216 bool fAlready
= mapLocalHost
.count(addr
) > 0;
217 LocalServiceInfo
&info
= mapLocalHost
[addr
];
218 if (!fAlready
|| nScore
>= info
.nScore
) {
219 info
.nScore
= nScore
+ (fAlready
? 1 : 0);
220 info
.nPort
= addr
.GetPort();
227 bool AddLocal(const CNetAddr
&addr
, int nScore
)
229 return AddLocal(CService(addr
, GetListenPort()), nScore
);
232 bool RemoveLocal(const CService
& addr
)
234 LOCK(cs_mapLocalHost
);
235 LogPrintf("RemoveLocal(%s)\n", addr
.ToString());
236 mapLocalHost
.erase(addr
);
240 /** Make a particular network entirely off-limits (no automatic connects to it) */
241 void SetLimited(enum Network net
, bool fLimited
)
243 if (net
== NET_UNROUTABLE
)
245 LOCK(cs_mapLocalHost
);
246 vfLimited
[net
] = fLimited
;
249 bool IsLimited(enum Network net
)
251 LOCK(cs_mapLocalHost
);
252 return vfLimited
[net
];
255 bool IsLimited(const CNetAddr
&addr
)
257 return IsLimited(addr
.GetNetwork());
260 /** vote for a local address */
261 bool SeenLocal(const CService
& addr
)
264 LOCK(cs_mapLocalHost
);
265 if (mapLocalHost
.count(addr
) == 0)
267 mapLocalHost
[addr
].nScore
++;
273 /** check whether a given address is potentially local */
274 bool IsLocal(const CService
& addr
)
276 LOCK(cs_mapLocalHost
);
277 return mapLocalHost
.count(addr
) > 0;
280 /** check whether a given network is one we can probably connect to */
281 bool IsReachable(enum Network net
)
283 LOCK(cs_mapLocalHost
);
284 return !vfLimited
[net
];
287 /** check whether a given address is in a network we can probably connect to */
288 bool IsReachable(const CNetAddr
& addr
)
290 enum Network net
= addr
.GetNetwork();
291 return IsReachable(net
);
295 CNode
* CConnman::FindNode(const CNetAddr
& ip
)
298 BOOST_FOREACH(CNode
* pnode
, vNodes
)
299 if ((CNetAddr
)pnode
->addr
== ip
)
304 CNode
* CConnman::FindNode(const CSubNet
& subNet
)
307 BOOST_FOREACH(CNode
* pnode
, vNodes
)
308 if (subNet
.Match((CNetAddr
)pnode
->addr
))
313 CNode
* CConnman::FindNode(const std::string
& addrName
)
316 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
317 if (pnode
->GetAddrName() == addrName
) {
324 CNode
* CConnman::FindNode(const CService
& addr
)
327 BOOST_FOREACH(CNode
* pnode
, vNodes
)
328 if ((CService
)pnode
->addr
== addr
)
333 bool CConnman::CheckIncomingNonce(uint64_t nonce
)
336 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
337 if (!pnode
->fSuccessfullyConnected
&& !pnode
->fInbound
&& pnode
->GetLocalNonce() == nonce
)
343 /** Get the bind address for a socket as CAddress */
344 static CAddress
GetBindAddress(SOCKET sock
)
347 struct sockaddr_storage sockaddr_bind
;
348 socklen_t sockaddr_bind_len
= sizeof(sockaddr_bind
);
349 if (sock
!= INVALID_SOCKET
) {
350 if (!getsockname(sock
, (struct sockaddr
*)&sockaddr_bind
, &sockaddr_bind_len
)) {
351 addr_bind
.SetSockAddr((const struct sockaddr
*)&sockaddr_bind
);
353 LogPrint(BCLog::NET
, "Warning: getsockname failed\n");
359 CNode
* CConnman::ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
)
361 if (pszDest
== NULL
) {
362 if (IsLocal(addrConnect
))
365 // Look for an existing connection
366 CNode
* pnode
= FindNode((CService
)addrConnect
);
369 LogPrintf("Failed to open new connection, already connected\n");
375 LogPrint(BCLog::NET
, "trying connection %s lastseen=%.1fhrs\n",
376 pszDest
? pszDest
: addrConnect
.ToString(),
377 pszDest
? 0.0 : (double)(GetAdjustedTime() - addrConnect
.nTime
)/3600.0);
381 bool proxyConnectionFailed
= false;
382 if (pszDest
? ConnectSocketByName(addrConnect
, hSocket
, pszDest
, Params().GetDefaultPort(), nConnectTimeout
, &proxyConnectionFailed
) :
383 ConnectSocket(addrConnect
, hSocket
, nConnectTimeout
, &proxyConnectionFailed
))
385 if (!IsSelectableSocket(hSocket
)) {
386 LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
387 CloseSocket(hSocket
);
391 if (pszDest
&& addrConnect
.IsValid()) {
392 // It is possible that we already have a connection to the IP/port pszDest resolved to.
393 // In that case, drop the connection that was just created, and return the existing CNode instead.
394 // Also store the name we used to connect in that CNode, so that future FindNode() calls to that
395 // name catch this early.
397 CNode
* pnode
= FindNode((CService
)addrConnect
);
400 pnode
->MaybeSetAddrName(std::string(pszDest
));
401 CloseSocket(hSocket
);
402 LogPrintf("Failed to open new connection, already connected\n");
407 addrman
.Attempt(addrConnect
, fCountFailure
);
410 NodeId id
= GetNewNodeId();
411 uint64_t nonce
= GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE
).Write(id
).Finalize();
412 CAddress addr_bind
= GetBindAddress(hSocket
);
413 CNode
* pnode
= new CNode(id
, nLocalServices
, GetBestHeight(), hSocket
, addrConnect
, CalculateKeyedNetGroup(addrConnect
), nonce
, addr_bind
, pszDest
? pszDest
: "", false);
414 pnode
->nServicesExpected
= ServiceFlags(addrConnect
.nServices
& nRelevantServices
);
418 } else if (!proxyConnectionFailed
) {
419 // If connecting to the node failed, and failure is not caused by a problem connecting to
420 // the proxy, mark this as an attempt.
421 addrman
.Attempt(addrConnect
, fCountFailure
);
427 void CConnman::DumpBanlist()
429 SweepBanned(); // clean unused entries (if bantime has expired)
431 if (!BannedSetIsDirty())
434 int64_t nStart
= GetTimeMillis();
439 if (bandb
.Write(banmap
)) {
440 SetBannedSetDirty(false);
443 LogPrint(BCLog::NET
, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
444 banmap
.size(), GetTimeMillis() - nStart
);
447 void CNode::CloseSocketDisconnect()
451 if (hSocket
!= INVALID_SOCKET
)
453 LogPrint(BCLog::NET
, "disconnecting peer=%d\n", id
);
454 CloseSocket(hSocket
);
458 void CConnman::ClearBanned()
463 setBannedIsDirty
= true;
465 DumpBanlist(); //store banlist to disk
467 clientInterface
->BannedListChanged();
470 bool CConnman::IsBanned(CNetAddr ip
)
472 bool fResult
= false;
475 for (banmap_t::iterator it
= setBanned
.begin(); it
!= setBanned
.end(); it
++)
477 CSubNet subNet
= (*it
).first
;
478 CBanEntry banEntry
= (*it
).second
;
480 if(subNet
.Match(ip
) && GetTime() < banEntry
.nBanUntil
)
487 bool CConnman::IsBanned(CSubNet subnet
)
489 bool fResult
= false;
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
= 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 BOOST_FOREACH(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 LOCK(cs_vWhitelistedRange
);
609 BOOST_FOREACH(const CSubNet
& subnet
, vWhitelistedRange
) {
610 if (subnet
.Match(addr
))
616 void CConnman::AddWhitelistedRange(const CSubNet
&subnet
) {
617 LOCK(cs_vWhitelistedRange
);
618 vWhitelistedRange
.push_back(subnet
);
622 std::string
CNode::GetAddrName() const {
627 void CNode::MaybeSetAddrName(const std::string
& addrNameIn
) {
629 if (addrName
.empty()) {
630 addrName
= addrNameIn
;
634 CService
CNode::GetAddrLocal() const {
639 void CNode::SetAddrLocal(const CService
& addrLocalIn
) {
641 if (addrLocal
.IsValid()) {
642 error("Addr local already set for node: %i. Refusing to change from %s to %s", id
, addrLocal
.ToString(), addrLocalIn
.ToString());
644 addrLocal
= addrLocalIn
;
649 #define X(name) stats.name = name
650 void CNode::copyStats(CNodeStats
&stats
)
652 stats
.nodeid
= this->GetId();
664 stats
.addrName
= GetAddrName();
675 X(mapSendBytesPerMsgCmd
);
680 X(mapRecvBytesPerMsgCmd
);
685 // It is common for nodes with good ping times to suddenly become lagged,
686 // due to a new block arriving or other large transfer.
687 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
688 // since pingtime does not update until the ping is complete, which might take a while.
689 // So, if a ping is taking an unusually long time in flight,
690 // the caller can immediately detect that this is happening.
691 int64_t nPingUsecWait
= 0;
692 if ((0 != nPingNonceSent
) && (0 != nPingUsecStart
)) {
693 nPingUsecWait
= GetTimeMicros() - nPingUsecStart
;
696 // 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 :)
697 stats
.dPingTime
= (((double)nPingUsecTime
) / 1e6
);
698 stats
.dMinPing
= (((double)nMinPingUsecTime
) / 1e6
);
699 stats
.dPingWait
= (((double)nPingUsecWait
) / 1e6
);
701 // Leave string empty if addrLocal invalid (not filled in yet)
702 CService addrLocalUnlocked
= GetAddrLocal();
703 stats
.addrLocal
= addrLocalUnlocked
.IsValid() ? addrLocalUnlocked
.ToString() : "";
707 bool CNode::ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
)
710 int64_t nTimeMicros
= GetTimeMicros();
712 nLastRecv
= nTimeMicros
/ 1000000;
713 nRecvBytes
+= nBytes
;
716 // get current incomplete message, or create a new one
717 if (vRecvMsg
.empty() ||
718 vRecvMsg
.back().complete())
719 vRecvMsg
.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK
, INIT_PROTO_VERSION
));
721 CNetMessage
& msg
= vRecvMsg
.back();
723 // absorb network data
726 handled
= msg
.readHeader(pch
, nBytes
);
728 handled
= msg
.readData(pch
, nBytes
);
733 if (msg
.in_data
&& msg
.hdr
.nMessageSize
> MAX_PROTOCOL_MESSAGE_LENGTH
) {
734 LogPrint(BCLog::NET
, "Oversized message from peer=%i, disconnecting\n", GetId());
741 if (msg
.complete()) {
743 //store received bytes per message command
744 //to prevent a memory DOS, only allow valid commands
745 mapMsgCmdSize::iterator i
= mapRecvBytesPerMsgCmd
.find(msg
.hdr
.pchCommand
);
746 if (i
== mapRecvBytesPerMsgCmd
.end())
747 i
= mapRecvBytesPerMsgCmd
.find(NET_MESSAGE_COMMAND_OTHER
);
748 assert(i
!= mapRecvBytesPerMsgCmd
.end());
749 i
->second
+= msg
.hdr
.nMessageSize
+ CMessageHeader::HEADER_SIZE
;
751 msg
.nTime
= nTimeMicros
;
759 void CNode::SetSendVersion(int nVersionIn
)
761 // Send version may only be changed in the version message, and
762 // only one version message is allowed per session. We can therefore
763 // treat this value as const and even atomic as long as it's only used
764 // once a version message has been successfully processed. Any attempt to
765 // set this twice is an error.
766 if (nSendVersion
!= 0) {
767 error("Send version already set for node: %i. Refusing to change from %i to %i", id
, nSendVersion
, nVersionIn
);
769 nSendVersion
= nVersionIn
;
773 int CNode::GetSendVersion() const
775 // The send version should always be explicitly set to
776 // INIT_PROTO_VERSION rather than using this value until SetSendVersion
778 if (nSendVersion
== 0) {
779 error("Requesting unset send version for node: %i. Using %i", id
, INIT_PROTO_VERSION
);
780 return INIT_PROTO_VERSION
;
786 int CNetMessage::readHeader(const char *pch
, unsigned int nBytes
)
788 // copy data to temporary parsing buffer
789 unsigned int nRemaining
= 24 - nHdrPos
;
790 unsigned int nCopy
= std::min(nRemaining
, nBytes
);
792 memcpy(&hdrbuf
[nHdrPos
], pch
, nCopy
);
795 // if header incomplete, exit
799 // deserialize to CMessageHeader
803 catch (const std::exception
&) {
807 // reject messages larger than MAX_SIZE
808 if (hdr
.nMessageSize
> MAX_SIZE
)
811 // switch state to reading message data
817 int CNetMessage::readData(const char *pch
, unsigned int nBytes
)
819 unsigned int nRemaining
= hdr
.nMessageSize
- nDataPos
;
820 unsigned int nCopy
= std::min(nRemaining
, nBytes
);
822 if (vRecv
.size() < nDataPos
+ nCopy
) {
823 // Allocate up to 256 KiB ahead, but never more than the total message size.
824 vRecv
.resize(std::min(hdr
.nMessageSize
, nDataPos
+ nCopy
+ 256 * 1024));
827 hasher
.Write((const unsigned char*)pch
, nCopy
);
828 memcpy(&vRecv
[nDataPos
], pch
, nCopy
);
834 const uint256
& CNetMessage::GetMessageHash() const
837 if (data_hash
.IsNull())
838 hasher
.Finalize(data_hash
.begin());
850 // requires LOCK(cs_vSend)
851 size_t CConnman::SocketSendData(CNode
*pnode
) const
853 auto it
= pnode
->vSendMsg
.begin();
854 size_t nSentSize
= 0;
856 while (it
!= pnode
->vSendMsg
.end()) {
857 const auto &data
= *it
;
858 assert(data
.size() > pnode
->nSendOffset
);
861 LOCK(pnode
->cs_hSocket
);
862 if (pnode
->hSocket
== INVALID_SOCKET
)
864 nBytes
= send(pnode
->hSocket
, reinterpret_cast<const char*>(data
.data()) + pnode
->nSendOffset
, data
.size() - pnode
->nSendOffset
, MSG_NOSIGNAL
| MSG_DONTWAIT
);
867 pnode
->nLastSend
= GetSystemTimeInSeconds();
868 pnode
->nSendBytes
+= nBytes
;
869 pnode
->nSendOffset
+= nBytes
;
871 if (pnode
->nSendOffset
== data
.size()) {
872 pnode
->nSendOffset
= 0;
873 pnode
->nSendSize
-= data
.size();
874 pnode
->fPauseSend
= pnode
->nSendSize
> nSendBufferMaxSize
;
877 // could not send full message; stop sending more
883 int nErr
= WSAGetLastError();
884 if (nErr
!= WSAEWOULDBLOCK
&& nErr
!= WSAEMSGSIZE
&& nErr
!= WSAEINTR
&& nErr
!= WSAEINPROGRESS
)
886 LogPrintf("socket send error %s\n", NetworkErrorString(nErr
));
887 pnode
->CloseSocketDisconnect();
890 // couldn't send anything at all
895 if (it
== pnode
->vSendMsg
.end()) {
896 assert(pnode
->nSendOffset
== 0);
897 assert(pnode
->nSendSize
== 0);
899 pnode
->vSendMsg
.erase(pnode
->vSendMsg
.begin(), it
);
903 struct NodeEvictionCandidate
906 int64_t nTimeConnected
;
907 int64_t nMinPingUsecTime
;
908 int64_t nLastBlockTime
;
910 bool fRelevantServices
;
914 uint64_t nKeyedNetGroup
;
917 static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
919 return a
.nMinPingUsecTime
> b
.nMinPingUsecTime
;
922 static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
924 return a
.nTimeConnected
> b
.nTimeConnected
;
927 static bool CompareNetGroupKeyed(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
) {
928 return a
.nKeyedNetGroup
< b
.nKeyedNetGroup
;
931 static bool CompareNodeBlockTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
933 // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
934 if (a
.nLastBlockTime
!= b
.nLastBlockTime
) return a
.nLastBlockTime
< b
.nLastBlockTime
;
935 if (a
.fRelevantServices
!= b
.fRelevantServices
) return b
.fRelevantServices
;
936 return a
.nTimeConnected
> b
.nTimeConnected
;
939 static bool CompareNodeTXTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
941 // 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.
942 if (a
.nLastTXTime
!= b
.nLastTXTime
) return a
.nLastTXTime
< b
.nLastTXTime
;
943 if (a
.fRelayTxes
!= b
.fRelayTxes
) return b
.fRelayTxes
;
944 if (a
.fBloomFilter
!= b
.fBloomFilter
) return a
.fBloomFilter
;
945 return a
.nTimeConnected
> b
.nTimeConnected
;
948 /** Try to find a connection to evict when the node is full.
949 * Extreme care must be taken to avoid opening the node to attacker
950 * triggered network partitioning.
951 * The strategy used here is to protect a small number of peers
952 * for each of several distinct characteristics which are difficult
953 * to forge. In order to partition a node the attacker must be
954 * simultaneously better at all of them than honest peers.
956 bool CConnman::AttemptToEvictConnection()
958 std::vector
<NodeEvictionCandidate
> vEvictionCandidates
;
962 BOOST_FOREACH(CNode
*node
, vNodes
) {
963 if (node
->fWhitelisted
)
967 if (node
->fDisconnect
)
969 NodeEvictionCandidate candidate
= {node
->GetId(), node
->nTimeConnected
, node
->nMinPingUsecTime
,
970 node
->nLastBlockTime
, node
->nLastTXTime
,
971 (node
->nServices
& nRelevantServices
) == nRelevantServices
,
972 node
->fRelayTxes
, node
->pfilter
!= NULL
, node
->addr
, node
->nKeyedNetGroup
};
973 vEvictionCandidates
.push_back(candidate
);
977 if (vEvictionCandidates
.empty()) return false;
979 // Protect connections with certain characteristics
981 // Deterministically select 4 peers to protect by netgroup.
982 // An attacker cannot predict which netgroups will be protected
983 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNetGroupKeyed
);
984 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
986 if (vEvictionCandidates
.empty()) return false;
988 // Protect the 8 nodes with the lowest minimum ping time.
989 // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
990 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), ReverseCompareNodeMinPingTime
);
991 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(8, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
993 if (vEvictionCandidates
.empty()) return false;
995 // Protect 4 nodes that most recently sent us transactions.
996 // An attacker cannot manipulate this metric without performing useful work.
997 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNodeTXTime
);
998 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
1000 if (vEvictionCandidates
.empty()) return false;
1002 // Protect 4 nodes that most recently sent us blocks.
1003 // An attacker cannot manipulate this metric without performing useful work.
1004 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNodeBlockTime
);
1005 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
1007 if (vEvictionCandidates
.empty()) return false;
1009 // Protect the half of the remaining nodes which have been connected the longest.
1010 // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
1011 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), ReverseCompareNodeTimeConnected
);
1012 vEvictionCandidates
.erase(vEvictionCandidates
.end() - static_cast<int>(vEvictionCandidates
.size() / 2), vEvictionCandidates
.end());
1014 if (vEvictionCandidates
.empty()) return false;
1016 // Identify the network group with the most connections and youngest member.
1017 // (vEvictionCandidates is already sorted by reverse connect time)
1018 uint64_t naMostConnections
;
1019 unsigned int nMostConnections
= 0;
1020 int64_t nMostConnectionsTime
= 0;
1021 std::map
<uint64_t, std::vector
<NodeEvictionCandidate
> > mapNetGroupNodes
;
1022 BOOST_FOREACH(const NodeEvictionCandidate
&node
, vEvictionCandidates
) {
1023 mapNetGroupNodes
[node
.nKeyedNetGroup
].push_back(node
);
1024 int64_t grouptime
= mapNetGroupNodes
[node
.nKeyedNetGroup
][0].nTimeConnected
;
1025 size_t groupsize
= mapNetGroupNodes
[node
.nKeyedNetGroup
].size();
1027 if (groupsize
> nMostConnections
|| (groupsize
== nMostConnections
&& grouptime
> nMostConnectionsTime
)) {
1028 nMostConnections
= groupsize
;
1029 nMostConnectionsTime
= grouptime
;
1030 naMostConnections
= node
.nKeyedNetGroup
;
1034 // Reduce to the network group with the most connections
1035 vEvictionCandidates
= std::move(mapNetGroupNodes
[naMostConnections
]);
1037 // Disconnect from the network group with the most connections
1038 NodeId evicted
= vEvictionCandidates
.front().id
;
1040 for(std::vector
<CNode
*>::const_iterator
it(vNodes
.begin()); it
!= vNodes
.end(); ++it
) {
1041 if ((*it
)->GetId() == evicted
) {
1042 (*it
)->fDisconnect
= true;
1049 void CConnman::AcceptConnection(const ListenSocket
& hListenSocket
) {
1050 struct sockaddr_storage sockaddr
;
1051 socklen_t len
= sizeof(sockaddr
);
1052 SOCKET hSocket
= accept(hListenSocket
.socket
, (struct sockaddr
*)&sockaddr
, &len
);
1055 int nMaxInbound
= nMaxConnections
- (nMaxOutbound
+ nMaxFeeler
);
1057 if (hSocket
!= INVALID_SOCKET
) {
1058 if (!addr
.SetSockAddr((const struct sockaddr
*)&sockaddr
)) {
1059 LogPrintf("Warning: Unknown socket family\n");
1063 bool whitelisted
= hListenSocket
.whitelisted
|| IsWhitelistedRange(addr
);
1066 BOOST_FOREACH(CNode
* pnode
, vNodes
)
1067 if (pnode
->fInbound
)
1071 if (hSocket
== INVALID_SOCKET
)
1073 int nErr
= WSAGetLastError();
1074 if (nErr
!= WSAEWOULDBLOCK
)
1075 LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr
));
1079 if (!fNetworkActive
) {
1080 LogPrintf("connection from %s dropped: not accepting new connections\n", addr
.ToString());
1081 CloseSocket(hSocket
);
1085 if (!IsSelectableSocket(hSocket
))
1087 LogPrintf("connection from %s dropped: non-selectable socket\n", addr
.ToString());
1088 CloseSocket(hSocket
);
1092 // According to the internet TCP_NODELAY is not carried into accepted sockets
1093 // on all platforms. Set it again here just to be sure.
1094 SetSocketNoDelay(hSocket
);
1096 if (IsBanned(addr
) && !whitelisted
)
1098 LogPrintf("connection from %s dropped (banned)\n", addr
.ToString());
1099 CloseSocket(hSocket
);
1103 if (nInbound
>= nMaxInbound
)
1105 if (!AttemptToEvictConnection()) {
1106 // No connection to evict, disconnect the new connection
1107 LogPrint(BCLog::NET
, "failed to find an eviction candidate - connection dropped (full)\n");
1108 CloseSocket(hSocket
);
1113 NodeId id
= GetNewNodeId();
1114 uint64_t nonce
= GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE
).Write(id
).Finalize();
1115 CAddress addr_bind
= GetBindAddress(hSocket
);
1117 CNode
* pnode
= new CNode(id
, nLocalServices
, GetBestHeight(), hSocket
, addr
, CalculateKeyedNetGroup(addr
), nonce
, addr_bind
, "", true);
1119 pnode
->fWhitelisted
= whitelisted
;
1120 GetNodeSignals().InitializeNode(pnode
, *this);
1122 LogPrint(BCLog::NET
, "connection from %s accepted\n", addr
.ToString());
1126 vNodes
.push_back(pnode
);
1130 void CConnman::ThreadSocketHandler()
1132 unsigned int nPrevNodeCount
= 0;
1133 while (!interruptNet
)
1140 // Disconnect unused nodes
1141 std::vector
<CNode
*> vNodesCopy
= vNodes
;
1142 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1144 if (pnode
->fDisconnect
)
1146 // remove from vNodes
1147 vNodes
.erase(remove(vNodes
.begin(), vNodes
.end(), pnode
), vNodes
.end());
1149 // release outbound grant (if any)
1150 pnode
->grantOutbound
.Release();
1152 // close socket and cleanup
1153 pnode
->CloseSocketDisconnect();
1155 // hold in disconnected pool until all refs are released
1157 vNodesDisconnected
.push_back(pnode
);
1162 // Delete disconnected nodes
1163 std::list
<CNode
*> vNodesDisconnectedCopy
= vNodesDisconnected
;
1164 BOOST_FOREACH(CNode
* pnode
, vNodesDisconnectedCopy
)
1166 // wait until threads are done using it
1167 if (pnode
->GetRefCount() <= 0) {
1168 bool fDelete
= false;
1170 TRY_LOCK(pnode
->cs_inventory
, lockInv
);
1172 TRY_LOCK(pnode
->cs_vSend
, lockSend
);
1179 vNodesDisconnected
.remove(pnode
);
1188 vNodesSize
= vNodes
.size();
1190 if(vNodesSize
!= nPrevNodeCount
) {
1191 nPrevNodeCount
= vNodesSize
;
1193 clientInterface
->NotifyNumConnectionsChanged(nPrevNodeCount
);
1197 // Find which sockets have data to receive
1199 struct timeval timeout
;
1201 timeout
.tv_usec
= 50000; // frequency to poll pnode->vSend
1206 FD_ZERO(&fdsetRecv
);
1207 FD_ZERO(&fdsetSend
);
1208 FD_ZERO(&fdsetError
);
1209 SOCKET hSocketMax
= 0;
1210 bool have_fds
= false;
1212 BOOST_FOREACH(const ListenSocket
& hListenSocket
, vhListenSocket
) {
1213 FD_SET(hListenSocket
.socket
, &fdsetRecv
);
1214 hSocketMax
= std::max(hSocketMax
, hListenSocket
.socket
);
1220 BOOST_FOREACH(CNode
* pnode
, vNodes
)
1222 // Implement the following logic:
1223 // * If there is data to send, select() for sending data. As this only
1224 // happens when optimistic write failed, we choose to first drain the
1225 // write buffer in this case before receiving more. This avoids
1226 // needlessly queueing received data, if the remote peer is not themselves
1227 // receiving data. This means properly utilizing TCP flow control signalling.
1228 // * Otherwise, if there is space left in the receive buffer, select() for
1230 // * Hand off all complete messages to the processor, to be handled without
1233 bool select_recv
= !pnode
->fPauseRecv
;
1236 LOCK(pnode
->cs_vSend
);
1237 select_send
= !pnode
->vSendMsg
.empty();
1240 LOCK(pnode
->cs_hSocket
);
1241 if (pnode
->hSocket
== INVALID_SOCKET
)
1244 FD_SET(pnode
->hSocket
, &fdsetError
);
1245 hSocketMax
= std::max(hSocketMax
, pnode
->hSocket
);
1249 FD_SET(pnode
->hSocket
, &fdsetSend
);
1253 FD_SET(pnode
->hSocket
, &fdsetRecv
);
1258 int nSelect
= select(have_fds
? hSocketMax
+ 1 : 0,
1259 &fdsetRecv
, &fdsetSend
, &fdsetError
, &timeout
);
1263 if (nSelect
== SOCKET_ERROR
)
1267 int nErr
= WSAGetLastError();
1268 LogPrintf("socket select error %s\n", NetworkErrorString(nErr
));
1269 for (unsigned int i
= 0; i
<= hSocketMax
; i
++)
1270 FD_SET(i
, &fdsetRecv
);
1272 FD_ZERO(&fdsetSend
);
1273 FD_ZERO(&fdsetError
);
1274 if (!interruptNet
.sleep_for(std::chrono::milliseconds(timeout
.tv_usec
/1000)))
1279 // Accept new connections
1281 BOOST_FOREACH(const ListenSocket
& hListenSocket
, vhListenSocket
)
1283 if (hListenSocket
.socket
!= INVALID_SOCKET
&& FD_ISSET(hListenSocket
.socket
, &fdsetRecv
))
1285 AcceptConnection(hListenSocket
);
1290 // Service each socket
1292 std::vector
<CNode
*> vNodesCopy
;
1295 vNodesCopy
= vNodes
;
1296 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1299 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1307 bool recvSet
= false;
1308 bool sendSet
= false;
1309 bool errorSet
= false;
1311 LOCK(pnode
->cs_hSocket
);
1312 if (pnode
->hSocket
== INVALID_SOCKET
)
1314 recvSet
= FD_ISSET(pnode
->hSocket
, &fdsetRecv
);
1315 sendSet
= FD_ISSET(pnode
->hSocket
, &fdsetSend
);
1316 errorSet
= FD_ISSET(pnode
->hSocket
, &fdsetError
);
1318 if (recvSet
|| errorSet
)
1320 // typical socket buffer is 8K-64K
1321 char pchBuf
[0x10000];
1324 LOCK(pnode
->cs_hSocket
);
1325 if (pnode
->hSocket
== INVALID_SOCKET
)
1327 nBytes
= recv(pnode
->hSocket
, pchBuf
, sizeof(pchBuf
), MSG_DONTWAIT
);
1331 bool notify
= false;
1332 if (!pnode
->ReceiveMsgBytes(pchBuf
, nBytes
, notify
))
1333 pnode
->CloseSocketDisconnect();
1334 RecordBytesRecv(nBytes
);
1336 size_t nSizeAdded
= 0;
1337 auto it(pnode
->vRecvMsg
.begin());
1338 for (; it
!= pnode
->vRecvMsg
.end(); ++it
) {
1339 if (!it
->complete())
1341 nSizeAdded
+= it
->vRecv
.size() + CMessageHeader::HEADER_SIZE
;
1344 LOCK(pnode
->cs_vProcessMsg
);
1345 pnode
->vProcessMsg
.splice(pnode
->vProcessMsg
.end(), pnode
->vRecvMsg
, pnode
->vRecvMsg
.begin(), it
);
1346 pnode
->nProcessQueueSize
+= nSizeAdded
;
1347 pnode
->fPauseRecv
= pnode
->nProcessQueueSize
> nReceiveFloodSize
;
1349 WakeMessageHandler();
1352 else if (nBytes
== 0)
1354 // socket closed gracefully
1355 if (!pnode
->fDisconnect
) {
1356 LogPrint(BCLog::NET
, "socket closed\n");
1358 pnode
->CloseSocketDisconnect();
1360 else if (nBytes
< 0)
1363 int nErr
= WSAGetLastError();
1364 if (nErr
!= WSAEWOULDBLOCK
&& nErr
!= WSAEMSGSIZE
&& nErr
!= WSAEINTR
&& nErr
!= WSAEINPROGRESS
)
1366 if (!pnode
->fDisconnect
)
1367 LogPrintf("socket recv error %s\n", NetworkErrorString(nErr
));
1368 pnode
->CloseSocketDisconnect();
1378 LOCK(pnode
->cs_vSend
);
1379 size_t nBytes
= SocketSendData(pnode
);
1381 RecordBytesSent(nBytes
);
1386 // Inactivity checking
1388 int64_t nTime
= GetSystemTimeInSeconds();
1389 if (nTime
- pnode
->nTimeConnected
> 60)
1391 if (pnode
->nLastRecv
== 0 || pnode
->nLastSend
== 0)
1393 LogPrint(BCLog::NET
, "socket no message in first 60 seconds, %d %d from %d\n", pnode
->nLastRecv
!= 0, pnode
->nLastSend
!= 0, pnode
->GetId());
1394 pnode
->fDisconnect
= true;
1396 else if (nTime
- pnode
->nLastSend
> TIMEOUT_INTERVAL
)
1398 LogPrintf("socket sending timeout: %is\n", nTime
- pnode
->nLastSend
);
1399 pnode
->fDisconnect
= true;
1401 else if (nTime
- pnode
->nLastRecv
> (pnode
->nVersion
> BIP0031_VERSION
? TIMEOUT_INTERVAL
: 90*60))
1403 LogPrintf("socket receive timeout: %is\n", nTime
- pnode
->nLastRecv
);
1404 pnode
->fDisconnect
= true;
1406 else if (pnode
->nPingNonceSent
&& pnode
->nPingUsecStart
+ TIMEOUT_INTERVAL
* 1000000 < GetTimeMicros())
1408 LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode
->nPingUsecStart
));
1409 pnode
->fDisconnect
= true;
1411 else if (!pnode
->fSuccessfullyConnected
)
1413 LogPrintf("version handshake timeout from %d\n", pnode
->GetId());
1414 pnode
->fDisconnect
= true;
1420 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1426 void CConnman::WakeMessageHandler()
1429 std::lock_guard
<std::mutex
> lock(mutexMsgProc
);
1430 fMsgProcWake
= true;
1432 condMsgProc
.notify_one();
1441 void ThreadMapPort()
1443 std::string port
= strprintf("%u", GetListenPort());
1444 const char * multicastif
= 0;
1445 const char * minissdpdpath
= 0;
1446 struct UPNPDev
* devlist
= 0;
1449 #ifndef UPNPDISCOVER_SUCCESS
1451 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0);
1452 #elif MINIUPNPC_API_VERSION < 14
1455 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0, 0, &error
);
1457 /* miniupnpc 1.9.20150730 */
1459 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0, 0, 2, &error
);
1462 struct UPNPUrls urls
;
1463 struct IGDdatas data
;
1466 r
= UPNP_GetValidIGD(devlist
, &urls
, &data
, lanaddr
, sizeof(lanaddr
));
1470 char externalIPAddress
[40];
1471 r
= UPNP_GetExternalIPAddress(urls
.controlURL
, data
.first
.servicetype
, externalIPAddress
);
1472 if(r
!= UPNPCOMMAND_SUCCESS
)
1473 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r
);
1476 if(externalIPAddress
[0])
1479 if(LookupHost(externalIPAddress
, resolved
, false)) {
1480 LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved
.ToString().c_str());
1481 AddLocal(resolved
, LOCAL_UPNP
);
1485 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1489 std::string strDesc
= "Bitcoin " + FormatFullVersion();
1493 #ifndef UPNPDISCOVER_SUCCESS
1495 r
= UPNP_AddPortMapping(urls
.controlURL
, data
.first
.servicetype
,
1496 port
.c_str(), port
.c_str(), lanaddr
, strDesc
.c_str(), "TCP", 0);
1499 r
= UPNP_AddPortMapping(urls
.controlURL
, data
.first
.servicetype
,
1500 port
.c_str(), port
.c_str(), lanaddr
, strDesc
.c_str(), "TCP", 0, "0");
1503 if(r
!=UPNPCOMMAND_SUCCESS
)
1504 LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1505 port
, port
, lanaddr
, r
, strupnperror(r
));
1507 LogPrintf("UPnP Port Mapping successful.\n");
1509 MilliSleep(20*60*1000); // Refresh every 20 minutes
1512 catch (const boost::thread_interrupted
&)
1514 r
= UPNP_DeletePortMapping(urls
.controlURL
, data
.first
.servicetype
, port
.c_str(), "TCP", 0);
1515 LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r
);
1516 freeUPNPDevlist(devlist
); devlist
= 0;
1517 FreeUPNPUrls(&urls
);
1521 LogPrintf("No valid UPnP IGDs found\n");
1522 freeUPNPDevlist(devlist
); devlist
= 0;
1524 FreeUPNPUrls(&urls
);
1528 void MapPort(bool fUseUPnP
)
1530 static boost::thread
* upnp_thread
= NULL
;
1535 upnp_thread
->interrupt();
1536 upnp_thread
->join();
1539 upnp_thread
= new boost::thread(boost::bind(&TraceThread
<void (*)()>, "upnp", &ThreadMapPort
));
1541 else if (upnp_thread
) {
1542 upnp_thread
->interrupt();
1543 upnp_thread
->join();
1552 // Intentionally left blank.
1561 static std::string
GetDNSHost(const CDNSSeedData
& data
, ServiceFlags
* requiredServiceBits
)
1563 //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
1564 if (!data
.supportsServiceBitsFiltering
|| *requiredServiceBits
== NODE_NETWORK
) {
1565 *requiredServiceBits
= NODE_NETWORK
;
1569 // See chainparams.cpp, most dnsseeds only support one or two possible servicebits hostnames
1570 return strprintf("x%x.%s", *requiredServiceBits
, data
.host
);
1574 void CConnman::ThreadDNSAddressSeed()
1576 // goal: only query DNS seeds if address need is acute
1577 // Avoiding DNS seeds when we don't need them improves user privacy by
1578 // creating fewer identifying DNS requests, reduces trust by giving seeds
1579 // less influence on the network topology, and reduces traffic to the seeds.
1580 if ((addrman
.size() > 0) &&
1581 (!GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED
))) {
1582 if (!interruptNet
.sleep_for(std::chrono::seconds(11)))
1587 for (auto pnode
: vNodes
) {
1588 nRelevant
+= pnode
->fSuccessfullyConnected
&& ((pnode
->nServices
& nRelevantServices
) == nRelevantServices
);
1590 if (nRelevant
>= 2) {
1591 LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1596 const std::vector
<CDNSSeedData
> &vSeeds
= Params().DNSSeeds();
1599 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1601 BOOST_FOREACH(const CDNSSeedData
&seed
, vSeeds
) {
1605 if (HaveNameProxy()) {
1606 AddOneShot(seed
.host
);
1608 std::vector
<CNetAddr
> vIPs
;
1609 std::vector
<CAddress
> vAdd
;
1610 ServiceFlags requiredServiceBits
= nRelevantServices
;
1611 if (LookupHost(GetDNSHost(seed
, &requiredServiceBits
).c_str(), vIPs
, 0, true))
1613 BOOST_FOREACH(const CNetAddr
& ip
, vIPs
)
1615 int nOneDay
= 24*3600;
1616 CAddress addr
= CAddress(CService(ip
, Params().GetDefaultPort()), requiredServiceBits
);
1617 addr
.nTime
= GetTime() - 3*nOneDay
- GetRand(4*nOneDay
); // use a random age between 3 and 7 days old
1618 vAdd
.push_back(addr
);
1625 // TODO: The seed name resolve may fail, yielding an IP of [::], which results in
1626 // addrman assigning the same source to results from different seeds.
1627 // This should switch to a hard-coded stable dummy IP for each seed name, so that the
1628 // resolve is not required at all.
1629 if (!vIPs
.empty()) {
1630 CService seedSource
;
1631 Lookup(seed
.name
.c_str(), seedSource
, 0, true);
1632 addrman
.Add(vAdd
, seedSource
);
1637 LogPrintf("%d addresses found from DNS seeds\n", found
);
1651 void CConnman::DumpAddresses()
1653 int64_t nStart
= GetTimeMillis();
1658 LogPrint(BCLog::NET
, "Flushed %d addresses to peers.dat %dms\n",
1659 addrman
.size(), GetTimeMillis() - nStart
);
1662 void CConnman::DumpData()
1668 void CConnman::ProcessOneShot()
1670 std::string strDest
;
1673 if (vOneShots
.empty())
1675 strDest
= vOneShots
.front();
1676 vOneShots
.pop_front();
1679 CSemaphoreGrant
grant(*semOutbound
, true);
1681 if (!OpenNetworkConnection(addr
, false, &grant
, strDest
.c_str(), true))
1682 AddOneShot(strDest
);
1686 void CConnman::ThreadOpenConnections()
1688 // Connect to specific addresses
1689 if (gArgs
.IsArgSet("-connect") && gArgs
.GetArgs("-connect").size() > 0)
1691 for (int64_t nLoop
= 0;; nLoop
++)
1694 BOOST_FOREACH(const std::string
& strAddr
, gArgs
.GetArgs("-connect"))
1696 CAddress
addr(CService(), NODE_NONE
);
1697 OpenNetworkConnection(addr
, false, NULL
, strAddr
.c_str());
1698 for (int i
= 0; i
< 10 && i
< nLoop
; i
++)
1700 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1704 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1709 // Initiate network connections
1710 int64_t nStart
= GetTime();
1712 // Minimum time before next feeler connection (in microseconds).
1713 int64_t nNextFeeler
= PoissonNextSend(nStart
*1000*1000, FEELER_INTERVAL
);
1714 while (!interruptNet
)
1718 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1721 CSemaphoreGrant
grant(*semOutbound
);
1725 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1726 if (addrman
.size() == 0 && (GetTime() - nStart
> 60)) {
1727 static bool done
= false;
1729 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1731 LookupHost("127.0.0.1", local
, false);
1732 addrman
.Add(convertSeed6(Params().FixedSeeds()), local
);
1738 // Choose an address to connect to based on most recently seen
1740 CAddress addrConnect
;
1742 // Only connect out to one peer per network group (/16 for IPv4).
1743 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1745 int nOutboundRelevant
= 0;
1746 std::set
<std::vector
<unsigned char> > setConnected
;
1749 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
1750 if (!pnode
->fInbound
&& !pnode
->fAddnode
) {
1752 // Count the peers that have all relevant services
1753 if (pnode
->fSuccessfullyConnected
&& !pnode
->fFeeler
&& ((pnode
->nServices
& nRelevantServices
) == nRelevantServices
)) {
1754 nOutboundRelevant
++;
1756 // Netgroups for inbound and addnode peers are not excluded because our goal here
1757 // is to not use multiple of our limited outbound slots on a single netgroup
1758 // but inbound and addnode peers do not use our outbound slots. Inbound peers
1759 // also have the added issue that they're attacker controlled and could be used
1760 // to prevent us from connecting to particular hosts if we used them here.
1761 setConnected
.insert(pnode
->addr
.GetGroup());
1767 // Feeler Connections
1770 // * Increase the number of connectable addresses in the tried table.
1773 // * Choose a random address from new and attempt to connect to it if we can connect
1774 // successfully it is added to tried.
1775 // * Start attempting feeler connections only after node finishes making outbound
1777 // * Only make a feeler connection once every few minutes.
1779 bool fFeeler
= false;
1780 if (nOutbound
>= nMaxOutbound
) {
1781 int64_t nTime
= GetTimeMicros(); // The current time right now (in microseconds).
1782 if (nTime
> nNextFeeler
) {
1783 nNextFeeler
= PoissonNextSend(nTime
, FEELER_INTERVAL
);
1790 int64_t nANow
= GetAdjustedTime();
1792 while (!interruptNet
)
1794 CAddrInfo addr
= addrman
.Select(fFeeler
);
1796 // if we selected an invalid address, restart
1797 if (!addr
.IsValid() || setConnected
.count(addr
.GetGroup()) || IsLocal(addr
))
1800 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1801 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1802 // already-connected network ranges, ...) before trying new addrman addresses.
1807 if (IsLimited(addr
))
1810 // only connect to full nodes
1811 if ((addr
.nServices
& REQUIRED_SERVICES
) != REQUIRED_SERVICES
)
1814 // only consider very recently tried nodes after 30 failed attempts
1815 if (nANow
- addr
.nLastTry
< 600 && nTries
< 30)
1818 // only consider nodes missing relevant services after 40 failed attempts and only if less than half the outbound are up.
1819 ServiceFlags nRequiredServices
= nRelevantServices
;
1820 if (nTries
>= 40 && nOutbound
< (nMaxOutbound
>> 1)) {
1821 nRequiredServices
= REQUIRED_SERVICES
;
1824 if ((addr
.nServices
& nRequiredServices
) != nRequiredServices
) {
1828 // do not allow non-default ports, unless after 50 invalid addresses selected already
1829 if (addr
.GetPort() != Params().GetDefaultPort() && nTries
< 50)
1834 // regardless of the services assumed to be available, only require the minimum if half or more outbound have relevant services
1835 if (nOutboundRelevant
>= (nMaxOutbound
>> 1)) {
1836 addrConnect
.nServices
= REQUIRED_SERVICES
;
1838 addrConnect
.nServices
= nRequiredServices
;
1843 if (addrConnect
.IsValid()) {
1846 // Add small amount of random noise before connection to avoid synchronization.
1847 int randsleep
= GetRandInt(FEELER_SLEEP_WINDOW
* 1000);
1848 if (!interruptNet
.sleep_for(std::chrono::milliseconds(randsleep
)))
1850 LogPrint(BCLog::NET
, "Making feeler connection to %s\n", addrConnect
.ToString());
1853 OpenNetworkConnection(addrConnect
, (int)setConnected
.size() >= std::min(nMaxConnections
- 1, 2), &grant
, NULL
, false, fFeeler
);
1858 std::vector
<AddedNodeInfo
> CConnman::GetAddedNodeInfo()
1860 std::vector
<AddedNodeInfo
> ret
;
1862 std::list
<std::string
> lAddresses(0);
1864 LOCK(cs_vAddedNodes
);
1865 ret
.reserve(vAddedNodes
.size());
1866 BOOST_FOREACH(const std::string
& strAddNode
, vAddedNodes
)
1867 lAddresses
.push_back(strAddNode
);
1871 // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
1872 std::map
<CService
, bool> mapConnected
;
1873 std::map
<std::string
, std::pair
<bool, CService
>> mapConnectedByName
;
1876 for (const CNode
* pnode
: vNodes
) {
1877 if (pnode
->addr
.IsValid()) {
1878 mapConnected
[pnode
->addr
] = pnode
->fInbound
;
1880 std::string addrName
= pnode
->GetAddrName();
1881 if (!addrName
.empty()) {
1882 mapConnectedByName
[std::move(addrName
)] = std::make_pair(pnode
->fInbound
, static_cast<const CService
&>(pnode
->addr
));
1887 BOOST_FOREACH(const std::string
& strAddNode
, lAddresses
) {
1888 CService
service(LookupNumeric(strAddNode
.c_str(), Params().GetDefaultPort()));
1889 if (service
.IsValid()) {
1890 // strAddNode is an IP:port
1891 auto it
= mapConnected
.find(service
);
1892 if (it
!= mapConnected
.end()) {
1893 ret
.push_back(AddedNodeInfo
{strAddNode
, service
, true, it
->second
});
1895 ret
.push_back(AddedNodeInfo
{strAddNode
, CService(), false, false});
1898 // strAddNode is a name
1899 auto it
= mapConnectedByName
.find(strAddNode
);
1900 if (it
!= mapConnectedByName
.end()) {
1901 ret
.push_back(AddedNodeInfo
{strAddNode
, it
->second
.second
, true, it
->second
.first
});
1903 ret
.push_back(AddedNodeInfo
{strAddNode
, CService(), false, false});
1911 void CConnman::ThreadOpenAddedConnections()
1914 LOCK(cs_vAddedNodes
);
1915 if (gArgs
.IsArgSet("-addnode"))
1916 vAddedNodes
= gArgs
.GetArgs("-addnode");
1921 CSemaphoreGrant
grant(*semAddnode
);
1922 std::vector
<AddedNodeInfo
> vInfo
= GetAddedNodeInfo();
1924 for (const AddedNodeInfo
& info
: vInfo
) {
1925 if (!info
.fConnected
) {
1926 if (!grant
.TryAcquire()) {
1927 // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
1928 // the addednodeinfo state might change.
1931 // If strAddedNode is an IP/port, decode it immediately, so
1932 // OpenNetworkConnection can detect existing connections to that IP/port.
1934 CService
service(LookupNumeric(info
.strAddedNode
.c_str(), Params().GetDefaultPort()));
1935 OpenNetworkConnection(CAddress(service
, NODE_NONE
), false, &grant
, info
.strAddedNode
.c_str(), false, false, true);
1936 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1940 // Retry every 60 seconds if a connection was attempted, otherwise two seconds
1941 if (!interruptNet
.sleep_for(std::chrono::seconds(tried
? 60 : 2)))
1946 // if successful, this moves the passed grant to the constructed node
1947 bool CConnman::OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
, const char *pszDest
, bool fOneShot
, bool fFeeler
, bool fAddnode
)
1950 // Initiate outbound network connection
1955 if (!fNetworkActive
) {
1959 if (IsLocal(addrConnect
) ||
1960 FindNode((CNetAddr
)addrConnect
) || IsBanned(addrConnect
) ||
1961 FindNode(addrConnect
.ToStringIPPort()))
1963 } else if (FindNode(std::string(pszDest
)))
1966 CNode
* pnode
= ConnectNode(addrConnect
, pszDest
, fCountFailure
);
1971 grantOutbound
->MoveTo(pnode
->grantOutbound
);
1973 pnode
->fOneShot
= true;
1975 pnode
->fFeeler
= true;
1977 pnode
->fAddnode
= true;
1979 GetNodeSignals().InitializeNode(pnode
, *this);
1982 vNodes
.push_back(pnode
);
1988 void CConnman::ThreadMessageHandler()
1990 while (!flagInterruptMsgProc
)
1992 std::vector
<CNode
*> vNodesCopy
;
1995 vNodesCopy
= vNodes
;
1996 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
) {
2001 bool fMoreWork
= false;
2003 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
2005 if (pnode
->fDisconnect
)
2009 bool fMoreNodeWork
= GetNodeSignals().ProcessMessages(pnode
, *this, flagInterruptMsgProc
);
2010 fMoreWork
|= (fMoreNodeWork
&& !pnode
->fPauseSend
);
2011 if (flagInterruptMsgProc
)
2016 LOCK(pnode
->cs_sendProcessing
);
2017 GetNodeSignals().SendMessages(pnode
, *this, flagInterruptMsgProc
);
2019 if (flagInterruptMsgProc
)
2025 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
2029 std::unique_lock
<std::mutex
> lock(mutexMsgProc
);
2031 condMsgProc
.wait_until(lock
, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake
; });
2033 fMsgProcWake
= false;
2042 bool CConnman::BindListenPort(const CService
&addrBind
, std::string
& strError
, bool fWhitelisted
)
2047 // Create socket for listening for incoming connections
2048 struct sockaddr_storage sockaddr
;
2049 socklen_t len
= sizeof(sockaddr
);
2050 if (!addrBind
.GetSockAddr((struct sockaddr
*)&sockaddr
, &len
))
2052 strError
= strprintf("Error: Bind address family for %s not supported", addrBind
.ToString());
2053 LogPrintf("%s\n", strError
);
2057 SOCKET hListenSocket
= socket(((struct sockaddr
*)&sockaddr
)->sa_family
, SOCK_STREAM
, IPPROTO_TCP
);
2058 if (hListenSocket
== INVALID_SOCKET
)
2060 strError
= strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2061 LogPrintf("%s\n", strError
);
2064 if (!IsSelectableSocket(hListenSocket
))
2066 strError
= "Error: Couldn't create a listenable socket for incoming connections";
2067 LogPrintf("%s\n", strError
);
2074 // Different way of disabling SIGPIPE on BSD
2075 setsockopt(hListenSocket
, SOL_SOCKET
, SO_NOSIGPIPE
, (void*)&nOne
, sizeof(int));
2077 // Allow binding if the port is still in TIME_WAIT state after
2078 // the program was closed and restarted.
2079 setsockopt(hListenSocket
, SOL_SOCKET
, SO_REUSEADDR
, (void*)&nOne
, sizeof(int));
2080 // Disable Nagle's algorithm
2081 setsockopt(hListenSocket
, IPPROTO_TCP
, TCP_NODELAY
, (void*)&nOne
, sizeof(int));
2083 setsockopt(hListenSocket
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&nOne
, sizeof(int));
2084 setsockopt(hListenSocket
, IPPROTO_TCP
, TCP_NODELAY
, (const char*)&nOne
, sizeof(int));
2087 // Set to non-blocking, incoming connections will also inherit this
2088 if (!SetSocketNonBlocking(hListenSocket
, true)) {
2089 strError
= strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
2090 LogPrintf("%s\n", strError
);
2094 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2095 // and enable it by default or not. Try to enable it, if possible.
2096 if (addrBind
.IsIPv6()) {
2099 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_V6ONLY
, (const char*)&nOne
, sizeof(int));
2101 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_V6ONLY
, (void*)&nOne
, sizeof(int));
2105 int nProtLevel
= PROTECTION_LEVEL_UNRESTRICTED
;
2106 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_PROTECTION_LEVEL
, (const char*)&nProtLevel
, sizeof(int));
2110 if (::bind(hListenSocket
, (struct sockaddr
*)&sockaddr
, len
) == SOCKET_ERROR
)
2112 int nErr
= WSAGetLastError();
2113 if (nErr
== WSAEADDRINUSE
)
2114 strError
= strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind
.ToString(), _(PACKAGE_NAME
));
2116 strError
= strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind
.ToString(), NetworkErrorString(nErr
));
2117 LogPrintf("%s\n", strError
);
2118 CloseSocket(hListenSocket
);
2121 LogPrintf("Bound to %s\n", addrBind
.ToString());
2123 // Listen for incoming connections
2124 if (listen(hListenSocket
, SOMAXCONN
) == SOCKET_ERROR
)
2126 strError
= strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2127 LogPrintf("%s\n", strError
);
2128 CloseSocket(hListenSocket
);
2132 vhListenSocket
.push_back(ListenSocket(hListenSocket
, fWhitelisted
));
2134 if (addrBind
.IsRoutable() && fDiscover
&& !fWhitelisted
)
2135 AddLocal(addrBind
, LOCAL_BIND
);
2140 void Discover(boost::thread_group
& threadGroup
)
2146 // Get local host IP
2147 char pszHostName
[256] = "";
2148 if (gethostname(pszHostName
, sizeof(pszHostName
)) != SOCKET_ERROR
)
2150 std::vector
<CNetAddr
> vaddr
;
2151 if (LookupHost(pszHostName
, vaddr
, 0, true))
2153 BOOST_FOREACH (const CNetAddr
&addr
, vaddr
)
2155 if (AddLocal(addr
, LOCAL_IF
))
2156 LogPrintf("%s: %s - %s\n", __func__
, pszHostName
, addr
.ToString());
2161 // Get local host ip
2162 struct ifaddrs
* myaddrs
;
2163 if (getifaddrs(&myaddrs
) == 0)
2165 for (struct ifaddrs
* ifa
= myaddrs
; ifa
!= NULL
; ifa
= ifa
->ifa_next
)
2167 if (ifa
->ifa_addr
== NULL
) continue;
2168 if ((ifa
->ifa_flags
& IFF_UP
) == 0) continue;
2169 if (strcmp(ifa
->ifa_name
, "lo") == 0) continue;
2170 if (strcmp(ifa
->ifa_name
, "lo0") == 0) continue;
2171 if (ifa
->ifa_addr
->sa_family
== AF_INET
)
2173 struct sockaddr_in
* s4
= (struct sockaddr_in
*)(ifa
->ifa_addr
);
2174 CNetAddr
addr(s4
->sin_addr
);
2175 if (AddLocal(addr
, LOCAL_IF
))
2176 LogPrintf("%s: IPv4 %s: %s\n", __func__
, ifa
->ifa_name
, addr
.ToString());
2178 else if (ifa
->ifa_addr
->sa_family
== AF_INET6
)
2180 struct sockaddr_in6
* s6
= (struct sockaddr_in6
*)(ifa
->ifa_addr
);
2181 CNetAddr
addr(s6
->sin6_addr
);
2182 if (AddLocal(addr
, LOCAL_IF
))
2183 LogPrintf("%s: IPv6 %s: %s\n", __func__
, ifa
->ifa_name
, addr
.ToString());
2186 freeifaddrs(myaddrs
);
2191 void CConnman::SetNetworkActive(bool active
)
2193 LogPrint(BCLog::NET
, "SetNetworkActive: %s\n", active
);
2196 fNetworkActive
= false;
2199 // Close sockets to all nodes
2200 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
2201 pnode
->CloseSocketDisconnect();
2204 fNetworkActive
= true;
2207 uiInterface
.NotifyNetworkActiveChanged(fNetworkActive
);
2210 CConnman::CConnman(uint64_t nSeed0In
, uint64_t nSeed1In
) : nSeed0(nSeed0In
), nSeed1(nSeed1In
)
2212 fNetworkActive
= true;
2213 setBannedIsDirty
= false;
2214 fAddressesInitialized
= false;
2216 nSendBufferMaxSize
= 0;
2217 nReceiveFloodSize
= 0;
2220 nMaxConnections
= 0;
2224 clientInterface
= NULL
;
2225 flagInterruptMsgProc
= false;
2228 NodeId
CConnman::GetNewNodeId()
2230 return nLastNodeId
.fetch_add(1, std::memory_order_relaxed
);
2233 bool CConnman::Start(CScheduler
& scheduler
, std::string
& strNodeError
, Options connOptions
)
2235 nTotalBytesRecv
= 0;
2236 nTotalBytesSent
= 0;
2237 nMaxOutboundTotalBytesSentInCycle
= 0;
2238 nMaxOutboundCycleStartTime
= 0;
2240 nRelevantServices
= connOptions
.nRelevantServices
;
2241 nLocalServices
= connOptions
.nLocalServices
;
2242 nMaxConnections
= connOptions
.nMaxConnections
;
2243 nMaxOutbound
= std::min((connOptions
.nMaxOutbound
), nMaxConnections
);
2244 nMaxAddnode
= connOptions
.nMaxAddnode
;
2245 nMaxFeeler
= connOptions
.nMaxFeeler
;
2247 nSendBufferMaxSize
= connOptions
.nSendBufferMaxSize
;
2248 nReceiveFloodSize
= connOptions
.nReceiveFloodSize
;
2250 nMaxOutboundLimit
= connOptions
.nMaxOutboundLimit
;
2251 nMaxOutboundTimeframe
= connOptions
.nMaxOutboundTimeframe
;
2253 SetBestHeight(connOptions
.nBestHeight
);
2255 for (const auto& strDest
: connOptions
.vSeedNodes
) {
2256 AddOneShot(strDest
);
2259 clientInterface
= connOptions
.uiInterface
;
2260 if (clientInterface
) {
2261 clientInterface
->InitMessage(_("Loading P2P addresses..."));
2263 // Load addresses from peers.dat
2264 int64_t nStart
= GetTimeMillis();
2267 if (adb
.Read(addrman
))
2268 LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman
.size(), GetTimeMillis() - nStart
);
2270 addrman
.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2271 LogPrintf("Invalid or missing peers.dat; recreating\n");
2275 if (clientInterface
)
2276 clientInterface
->InitMessage(_("Loading banlist..."));
2277 // Load addresses from banlist.dat
2278 nStart
= GetTimeMillis();
2281 if (bandb
.Read(banmap
)) {
2282 SetBanned(banmap
); // thread save setter
2283 SetBannedSetDirty(false); // no need to write down, just read data
2284 SweepBanned(); // sweep out unused entries
2286 LogPrint(BCLog::NET
, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
2287 banmap
.size(), GetTimeMillis() - nStart
);
2289 LogPrintf("Invalid or missing banlist.dat; recreating\n");
2290 SetBannedSetDirty(true); // force write
2294 uiInterface
.InitMessage(_("Starting network threads..."));
2296 fAddressesInitialized
= true;
2298 if (semOutbound
== NULL
) {
2299 // initialize semaphore
2300 semOutbound
= new CSemaphore(std::min((nMaxOutbound
+ nMaxFeeler
), nMaxConnections
));
2302 if (semAddnode
== NULL
) {
2303 // initialize semaphore
2304 semAddnode
= new CSemaphore(nMaxAddnode
);
2310 InterruptSocks5(false);
2311 interruptNet
.reset();
2312 flagInterruptMsgProc
= false;
2315 std::unique_lock
<std::mutex
> lock(mutexMsgProc
);
2316 fMsgProcWake
= false;
2319 // Send and receive from sockets, accept connections
2320 threadSocketHandler
= std::thread(&TraceThread
<std::function
<void()> >, "net", std::function
<void()>(std::bind(&CConnman::ThreadSocketHandler
, this)));
2322 if (!GetBoolArg("-dnsseed", true))
2323 LogPrintf("DNS seeding disabled\n");
2325 threadDNSAddressSeed
= std::thread(&TraceThread
<std::function
<void()> >, "dnsseed", std::function
<void()>(std::bind(&CConnman::ThreadDNSAddressSeed
, this)));
2327 // Initiate outbound connections from -addnode
2328 threadOpenAddedConnections
= std::thread(&TraceThread
<std::function
<void()> >, "addcon", std::function
<void()>(std::bind(&CConnman::ThreadOpenAddedConnections
, this)));
2330 // Initiate outbound connections unless connect=0
2331 if (!gArgs
.IsArgSet("-connect") || gArgs
.GetArgs("-connect").size() != 1 || gArgs
.GetArgs("-connect")[0] != "0")
2332 threadOpenConnections
= std::thread(&TraceThread
<std::function
<void()> >, "opencon", std::function
<void()>(std::bind(&CConnman::ThreadOpenConnections
, this)));
2335 threadMessageHandler
= std::thread(&TraceThread
<std::function
<void()> >, "msghand", std::function
<void()>(std::bind(&CConnman::ThreadMessageHandler
, this)));
2337 // Dump network addresses
2338 scheduler
.scheduleEvery(std::bind(&CConnman::DumpData
, this), DUMP_ADDRESSES_INTERVAL
* 1000);
2351 // Shutdown Windows Sockets
2356 instance_of_cnetcleanup
;
2358 void CConnman::Interrupt()
2361 std::lock_guard
<std::mutex
> lock(mutexMsgProc
);
2362 flagInterruptMsgProc
= true;
2364 condMsgProc
.notify_all();
2367 InterruptSocks5(true);
2370 for (int i
=0; i
<(nMaxOutbound
+ nMaxFeeler
); i
++) {
2371 semOutbound
->post();
2376 for (int i
=0; i
<nMaxAddnode
; i
++) {
2382 void CConnman::Stop()
2384 if (threadMessageHandler
.joinable())
2385 threadMessageHandler
.join();
2386 if (threadOpenConnections
.joinable())
2387 threadOpenConnections
.join();
2388 if (threadOpenAddedConnections
.joinable())
2389 threadOpenAddedConnections
.join();
2390 if (threadDNSAddressSeed
.joinable())
2391 threadDNSAddressSeed
.join();
2392 if (threadSocketHandler
.joinable())
2393 threadSocketHandler
.join();
2395 if (fAddressesInitialized
)
2398 fAddressesInitialized
= false;
2402 BOOST_FOREACH(CNode
* pnode
, vNodes
)
2403 pnode
->CloseSocketDisconnect();
2404 BOOST_FOREACH(ListenSocket
& hListenSocket
, vhListenSocket
)
2405 if (hListenSocket
.socket
!= INVALID_SOCKET
)
2406 if (!CloseSocket(hListenSocket
.socket
))
2407 LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2409 // clean up some globals (to help leak detection)
2410 BOOST_FOREACH(CNode
*pnode
, vNodes
) {
2413 BOOST_FOREACH(CNode
*pnode
, vNodesDisconnected
) {
2417 vNodesDisconnected
.clear();
2418 vhListenSocket
.clear();
2425 void CConnman::DeleteNode(CNode
* pnode
)
2428 bool fUpdateConnectionTime
= false;
2429 GetNodeSignals().FinalizeNode(pnode
->GetId(), fUpdateConnectionTime
);
2430 if(fUpdateConnectionTime
)
2431 addrman
.Connected(pnode
->addr
);
2435 CConnman::~CConnman()
2441 size_t CConnman::GetAddressCount() const
2443 return addrman
.size();
2446 void CConnman::SetServices(const CService
&addr
, ServiceFlags nServices
)
2448 addrman
.SetServices(addr
, nServices
);
2451 void CConnman::MarkAddressGood(const CAddress
& addr
)
2456 void CConnman::AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
)
2458 addrman
.Add(vAddr
, addrFrom
, nTimePenalty
);
2461 std::vector
<CAddress
> CConnman::GetAddresses()
2463 return addrman
.GetAddr();
2466 bool CConnman::AddNode(const std::string
& strNode
)
2468 LOCK(cs_vAddedNodes
);
2469 for(std::vector
<std::string
>::const_iterator it
= vAddedNodes
.begin(); it
!= vAddedNodes
.end(); ++it
) {
2474 vAddedNodes
.push_back(strNode
);
2478 bool CConnman::RemoveAddedNode(const std::string
& strNode
)
2480 LOCK(cs_vAddedNodes
);
2481 for(std::vector
<std::string
>::iterator it
= vAddedNodes
.begin(); it
!= vAddedNodes
.end(); ++it
) {
2482 if (strNode
== *it
) {
2483 vAddedNodes
.erase(it
);
2490 size_t CConnman::GetNodeCount(NumConnections flags
)
2493 if (flags
== CConnman::CONNECTIONS_ALL
) // Shortcut if we want total
2494 return vNodes
.size();
2497 for(std::vector
<CNode
*>::const_iterator it
= vNodes
.begin(); it
!= vNodes
.end(); ++it
)
2498 if (flags
& ((*it
)->fInbound
? CONNECTIONS_IN
: CONNECTIONS_OUT
))
2504 void CConnman::GetNodeStats(std::vector
<CNodeStats
>& vstats
)
2508 vstats
.reserve(vNodes
.size());
2509 for(std::vector
<CNode
*>::iterator it
= vNodes
.begin(); it
!= vNodes
.end(); ++it
) {
2511 vstats
.emplace_back();
2512 pnode
->copyStats(vstats
.back());
2516 bool CConnman::DisconnectNode(const std::string
& strNode
)
2519 if (CNode
* pnode
= FindNode(strNode
)) {
2520 pnode
->fDisconnect
= true;
2525 bool CConnman::DisconnectNode(NodeId id
)
2528 for(CNode
* pnode
: vNodes
) {
2529 if (id
== pnode
->GetId()) {
2530 pnode
->fDisconnect
= true;
2537 void CConnman::RecordBytesRecv(uint64_t bytes
)
2539 LOCK(cs_totalBytesRecv
);
2540 nTotalBytesRecv
+= bytes
;
2543 void CConnman::RecordBytesSent(uint64_t bytes
)
2545 LOCK(cs_totalBytesSent
);
2546 nTotalBytesSent
+= bytes
;
2548 uint64_t now
= GetTime();
2549 if (nMaxOutboundCycleStartTime
+ nMaxOutboundTimeframe
< now
)
2551 // timeframe expired, reset cycle
2552 nMaxOutboundCycleStartTime
= now
;
2553 nMaxOutboundTotalBytesSentInCycle
= 0;
2556 // TODO, exclude whitebind peers
2557 nMaxOutboundTotalBytesSentInCycle
+= bytes
;
2560 void CConnman::SetMaxOutboundTarget(uint64_t limit
)
2562 LOCK(cs_totalBytesSent
);
2563 nMaxOutboundLimit
= limit
;
2566 uint64_t CConnman::GetMaxOutboundTarget()
2568 LOCK(cs_totalBytesSent
);
2569 return nMaxOutboundLimit
;
2572 uint64_t CConnman::GetMaxOutboundTimeframe()
2574 LOCK(cs_totalBytesSent
);
2575 return nMaxOutboundTimeframe
;
2578 uint64_t CConnman::GetMaxOutboundTimeLeftInCycle()
2580 LOCK(cs_totalBytesSent
);
2581 if (nMaxOutboundLimit
== 0)
2584 if (nMaxOutboundCycleStartTime
== 0)
2585 return nMaxOutboundTimeframe
;
2587 uint64_t cycleEndTime
= nMaxOutboundCycleStartTime
+ nMaxOutboundTimeframe
;
2588 uint64_t now
= GetTime();
2589 return (cycleEndTime
< now
) ? 0 : cycleEndTime
- GetTime();
2592 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe
)
2594 LOCK(cs_totalBytesSent
);
2595 if (nMaxOutboundTimeframe
!= timeframe
)
2597 // reset measure-cycle in case of changing
2599 nMaxOutboundCycleStartTime
= GetTime();
2601 nMaxOutboundTimeframe
= timeframe
;
2604 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit
)
2606 LOCK(cs_totalBytesSent
);
2607 if (nMaxOutboundLimit
== 0)
2610 if (historicalBlockServingLimit
)
2612 // keep a large enough buffer to at least relay each block once
2613 uint64_t timeLeftInCycle
= GetMaxOutboundTimeLeftInCycle();
2614 uint64_t buffer
= timeLeftInCycle
/ 600 * MAX_BLOCK_SERIALIZED_SIZE
;
2615 if (buffer
>= nMaxOutboundLimit
|| nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
- buffer
)
2618 else if (nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
)
2624 uint64_t CConnman::GetOutboundTargetBytesLeft()
2626 LOCK(cs_totalBytesSent
);
2627 if (nMaxOutboundLimit
== 0)
2630 return (nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
) ? 0 : nMaxOutboundLimit
- nMaxOutboundTotalBytesSentInCycle
;
2633 uint64_t CConnman::GetTotalBytesRecv()
2635 LOCK(cs_totalBytesRecv
);
2636 return nTotalBytesRecv
;
2639 uint64_t CConnman::GetTotalBytesSent()
2641 LOCK(cs_totalBytesSent
);
2642 return nTotalBytesSent
;
2645 ServiceFlags
CConnman::GetLocalServices() const
2647 return nLocalServices
;
2650 void CConnman::SetBestHeight(int height
)
2652 nBestHeight
.store(height
, std::memory_order_release
);
2655 int CConnman::GetBestHeight() const
2657 return nBestHeight
.load(std::memory_order_acquire
);
2660 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize
; }
2661 unsigned int CConnman::GetSendBufferSize() const{ return nSendBufferMaxSize
; }
2663 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
) :
2664 nTimeConnected(GetSystemTimeInSeconds()),
2666 addrBind(addrBindIn
),
2667 fInbound(fInboundIn
),
2668 nKeyedNetGroup(nKeyedNetGroupIn
),
2669 addrKnown(5000, 0.001),
2670 filterInventoryKnown(50000, 0.000001),
2672 nLocalHostNonce(nLocalHostNonceIn
),
2673 nLocalServices(nLocalServicesIn
),
2674 nMyStartingHeight(nMyStartingHeightIn
),
2677 nServices
= NODE_NONE
;
2678 nServicesExpected
= NODE_NONE
;
2679 hSocket
= hSocketIn
;
2680 nRecvVersion
= INIT_PROTO_VERSION
;
2686 addrName
= addrNameIn
== "" ? addr
.ToStringIPPort() : addrNameIn
;
2689 fWhitelisted
= false;
2692 fClient
= false; // set by version message
2694 fSuccessfullyConnected
= false;
2695 fDisconnect
= false;
2699 hashContinue
= uint256();
2700 nStartingHeight
= -1;
2701 filterInventoryKnown
.reset();
2702 fSendMempool
= false;
2704 nNextLocalAddrSend
= 0;
2709 pfilter
= new CBloomFilter();
2710 timeLastMempoolReq
= 0;
2716 fPingQueued
= false;
2717 nMinPingUsecTime
= std::numeric_limits
<int64_t>::max();
2719 lastSentFeeFilter
= 0;
2720 nextSendTimeFeeFilter
= 0;
2723 nProcessQueueSize
= 0;
2725 BOOST_FOREACH(const std::string
&msg
, getAllNetMessageTypes())
2726 mapRecvBytesPerMsgCmd
[msg
] = 0;
2727 mapRecvBytesPerMsgCmd
[NET_MESSAGE_COMMAND_OTHER
] = 0;
2730 LogPrint(BCLog::NET
, "Added connection to %s peer=%d\n", addrName
, id
);
2732 LogPrint(BCLog::NET
, "Added connection peer=%d\n", id
);
2738 CloseSocket(hSocket
);
2744 void CNode::AskFor(const CInv
& inv
)
2746 if (mapAskFor
.size() > MAPASKFOR_MAX_SZ
|| setAskFor
.size() > SETASKFOR_MAX_SZ
)
2748 // a peer may not have multiple non-responded queue positions for a single inv item
2749 if (!setAskFor
.insert(inv
.hash
).second
)
2752 // We're using mapAskFor as a priority queue,
2753 // the key is the earliest time the request can be sent
2754 int64_t nRequestTime
;
2755 limitedmap
<uint256
, int64_t>::const_iterator it
= mapAlreadyAskedFor
.find(inv
.hash
);
2756 if (it
!= mapAlreadyAskedFor
.end())
2757 nRequestTime
= it
->second
;
2760 LogPrint(BCLog::NET
, "askfor %s %d (%s) peer=%d\n", inv
.ToString(), nRequestTime
, DateTimeStrFormat("%H:%M:%S", nRequestTime
/1000000), id
);
2762 // Make sure not to reuse time indexes to keep things in the same order
2763 int64_t nNow
= GetTimeMicros() - 1000000;
2764 static int64_t nLastTime
;
2766 nNow
= std::max(nNow
, nLastTime
);
2769 // Each retry is 2 minutes after the last
2770 nRequestTime
= std::max(nRequestTime
+ 2 * 60 * 1000000, nNow
);
2771 if (it
!= mapAlreadyAskedFor
.end())
2772 mapAlreadyAskedFor
.update(it
, nRequestTime
);
2774 mapAlreadyAskedFor
.insert(std::make_pair(inv
.hash
, nRequestTime
));
2775 mapAskFor
.insert(std::make_pair(nRequestTime
, inv
));
2778 bool CConnman::NodeFullyConnected(const CNode
* pnode
)
2780 return pnode
&& pnode
->fSuccessfullyConnected
&& !pnode
->fDisconnect
;
2783 void CConnman::PushMessage(CNode
* pnode
, CSerializedNetMsg
&& msg
)
2785 size_t nMessageSize
= msg
.data
.size();
2786 size_t nTotalSize
= nMessageSize
+ CMessageHeader::HEADER_SIZE
;
2787 LogPrint(BCLog::NET
, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg
.command
.c_str()), nMessageSize
, pnode
->GetId());
2789 std::vector
<unsigned char> serializedHeader
;
2790 serializedHeader
.reserve(CMessageHeader::HEADER_SIZE
);
2791 uint256 hash
= Hash(msg
.data
.data(), msg
.data
.data() + nMessageSize
);
2792 CMessageHeader
hdr(Params().MessageStart(), msg
.command
.c_str(), nMessageSize
);
2793 memcpy(hdr
.pchChecksum
, hash
.begin(), CMessageHeader::CHECKSUM_SIZE
);
2795 CVectorWriter
{SER_NETWORK
, INIT_PROTO_VERSION
, serializedHeader
, 0, hdr
};
2797 size_t nBytesSent
= 0;
2799 LOCK(pnode
->cs_vSend
);
2800 bool optimisticSend(pnode
->vSendMsg
.empty());
2802 //log total amount of bytes per command
2803 pnode
->mapSendBytesPerMsgCmd
[msg
.command
] += nTotalSize
;
2804 pnode
->nSendSize
+= nTotalSize
;
2806 if (pnode
->nSendSize
> nSendBufferMaxSize
)
2807 pnode
->fPauseSend
= true;
2808 pnode
->vSendMsg
.push_back(std::move(serializedHeader
));
2810 pnode
->vSendMsg
.push_back(std::move(msg
.data
));
2812 // If write queue empty, attempt "optimistic write"
2813 if (optimisticSend
== true)
2814 nBytesSent
= SocketSendData(pnode
);
2817 RecordBytesSent(nBytesSent
);
2820 bool CConnman::ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
)
2822 CNode
* found
= nullptr;
2824 for (auto&& pnode
: vNodes
) {
2825 if(pnode
->GetId() == id
) {
2830 return found
!= nullptr && NodeFullyConnected(found
) && func(found
);
2833 int64_t PoissonNextSend(int64_t nNow
, int average_interval_seconds
) {
2834 return nNow
+ (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds
* -1000000.0 + 0.5);
2837 CSipHasher
CConnman::GetDeterministicRandomizer(uint64_t id
) const
2839 return CSipHasher(nSeed0
, nSeed1
).Write(id
);
2842 uint64_t CConnman::CalculateKeyedNetGroup(const CAddress
& ad
) const
2844 std::vector
<unsigned char> vchNetGroup(ad
.GetGroup());
2846 return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP
).Write(&vchNetGroup
[0], vchNetGroup
.size()).Finalize();