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) && !defined(MSG_NOSIGNAL)
48 #define MSG_NOSIGNAL 0
51 // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
52 // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
54 #ifndef PROTECTION_LEVEL_UNRESTRICTED
55 #define PROTECTION_LEVEL_UNRESTRICTED 10
57 #ifndef IPV6_PROTECTION_LEVEL
58 #define IPV6_PROTECTION_LEVEL 23
62 const static std::string NET_MESSAGE_COMMAND_OTHER
= "*other*";
64 static const uint64_t RANDOMIZER_ID_NETGROUP
= 0x6c0edd8036ef4036ULL
; // SHA256("netgroup")[0:8]
65 static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE
= 0xd93e69e2bbfa5735ULL
; // SHA256("localhostnonce")[0:8]
67 // Global state variables
69 bool fDiscover
= true;
71 bool fRelayTxes
= true;
72 CCriticalSection cs_mapLocalHost
;
73 std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
74 static bool vfLimited
[NET_MAX
] = {};
75 std::string strSubVersion
;
77 limitedmap
<uint256
, int64_t> mapAlreadyAskedFor(MAX_INV_SZ
);
79 // Signals for message handling
80 static CNodeSignals g_signals
;
81 CNodeSignals
& GetNodeSignals() { return g_signals
; }
83 void CConnman::AddOneShot(const std::string
& strDest
)
86 vOneShots
.push_back(strDest
);
89 unsigned short GetListenPort()
91 return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
94 // find 'best' local address for a particular peer
95 bool GetLocal(CService
& addr
, const CNetAddr
*paddrPeer
)
101 int nBestReachability
= -1;
103 LOCK(cs_mapLocalHost
);
104 for (std::map
<CNetAddr
, LocalServiceInfo
>::iterator it
= mapLocalHost
.begin(); it
!= mapLocalHost
.end(); it
++)
106 int nScore
= (*it
).second
.nScore
;
107 int nReachability
= (*it
).first
.GetReachabilityFrom(paddrPeer
);
108 if (nReachability
> nBestReachability
|| (nReachability
== nBestReachability
&& nScore
> nBestScore
))
110 addr
= CService((*it
).first
, (*it
).second
.nPort
);
111 nBestReachability
= nReachability
;
116 return nBestScore
>= 0;
119 //! Convert the pnSeeds6 array into usable address objects.
120 static std::vector
<CAddress
> convertSeed6(const std::vector
<SeedSpec6
> &vSeedsIn
)
122 // It'll only connect to one or two seed nodes because once it connects,
123 // it'll get a pile of addresses with newer timestamps.
124 // Seed nodes are given a random 'last seen time' of between one and two
126 const int64_t nOneWeek
= 7*24*60*60;
127 std::vector
<CAddress
> vSeedsOut
;
128 vSeedsOut
.reserve(vSeedsIn
.size());
129 for (std::vector
<SeedSpec6
>::const_iterator
i(vSeedsIn
.begin()); i
!= vSeedsIn
.end(); ++i
)
132 memcpy(&ip
, i
->addr
, sizeof(ip
));
133 CAddress
addr(CService(ip
, i
->port
), NODE_NETWORK
);
134 addr
.nTime
= GetTime() - GetRand(nOneWeek
) - nOneWeek
;
135 vSeedsOut
.push_back(addr
);
140 // get best local address for a particular peer as a CAddress
141 // Otherwise, return the unroutable 0.0.0.0 but filled in with
142 // the normal parameters, since the IP may be changed to a useful
144 CAddress
GetLocalAddress(const CNetAddr
*paddrPeer
, ServiceFlags nLocalServices
)
146 CAddress
ret(CService(CNetAddr(),GetListenPort()), NODE_NONE
);
148 if (GetLocal(addr
, paddrPeer
))
150 ret
= CAddress(addr
, nLocalServices
);
152 ret
.nTime
= GetAdjustedTime();
156 int GetnScore(const CService
& addr
)
158 LOCK(cs_mapLocalHost
);
159 if (mapLocalHost
.count(addr
) == LOCAL_NONE
)
161 return mapLocalHost
[addr
].nScore
;
164 // Is our peer's addrLocal potentially useful as an external IP source?
165 bool IsPeerAddrLocalGood(CNode
*pnode
)
167 CService addrLocal
= pnode
->GetAddrLocal();
168 return fDiscover
&& pnode
->addr
.IsRoutable() && addrLocal
.IsRoutable() &&
169 !IsLimited(addrLocal
.GetNetwork());
172 // pushes our own address to a peer
173 void AdvertiseLocal(CNode
*pnode
)
175 if (fListen
&& pnode
->fSuccessfullyConnected
)
177 CAddress addrLocal
= GetLocalAddress(&pnode
->addr
, pnode
->GetLocalServices());
178 // If discovery is enabled, sometimes give our peer the address it
179 // tells us that it sees us as in case it has a better idea of our
180 // address than we do.
181 if (IsPeerAddrLocalGood(pnode
) && (!addrLocal
.IsRoutable() ||
182 GetRand((GetnScore(addrLocal
) > LOCAL_MANUAL
) ? 8:2) == 0))
184 addrLocal
.SetIP(pnode
->GetAddrLocal());
186 if (addrLocal
.IsRoutable())
188 LogPrint("net", "AdvertiseLocal: advertising address %s\n", addrLocal
.ToString());
189 FastRandomContext insecure_rand
;
190 pnode
->PushAddress(addrLocal
, insecure_rand
);
195 // learn a new local address
196 bool AddLocal(const CService
& addr
, int nScore
)
198 if (!addr
.IsRoutable())
201 if (!fDiscover
&& nScore
< LOCAL_MANUAL
)
207 LogPrintf("AddLocal(%s,%i)\n", addr
.ToString(), nScore
);
210 LOCK(cs_mapLocalHost
);
211 bool fAlready
= mapLocalHost
.count(addr
) > 0;
212 LocalServiceInfo
&info
= mapLocalHost
[addr
];
213 if (!fAlready
|| nScore
>= info
.nScore
) {
214 info
.nScore
= nScore
+ (fAlready
? 1 : 0);
215 info
.nPort
= addr
.GetPort();
222 bool AddLocal(const CNetAddr
&addr
, int nScore
)
224 return AddLocal(CService(addr
, GetListenPort()), nScore
);
227 bool RemoveLocal(const CService
& addr
)
229 LOCK(cs_mapLocalHost
);
230 LogPrintf("RemoveLocal(%s)\n", addr
.ToString());
231 mapLocalHost
.erase(addr
);
235 /** Make a particular network entirely off-limits (no automatic connects to it) */
236 void SetLimited(enum Network net
, bool fLimited
)
238 if (net
== NET_UNROUTABLE
)
240 LOCK(cs_mapLocalHost
);
241 vfLimited
[net
] = fLimited
;
244 bool IsLimited(enum Network net
)
246 LOCK(cs_mapLocalHost
);
247 return vfLimited
[net
];
250 bool IsLimited(const CNetAddr
&addr
)
252 return IsLimited(addr
.GetNetwork());
255 /** vote for a local address */
256 bool SeenLocal(const CService
& addr
)
259 LOCK(cs_mapLocalHost
);
260 if (mapLocalHost
.count(addr
) == 0)
262 mapLocalHost
[addr
].nScore
++;
268 /** check whether a given address is potentially local */
269 bool IsLocal(const CService
& addr
)
271 LOCK(cs_mapLocalHost
);
272 return mapLocalHost
.count(addr
) > 0;
275 /** check whether a given network is one we can probably connect to */
276 bool IsReachable(enum Network net
)
278 LOCK(cs_mapLocalHost
);
279 return !vfLimited
[net
];
282 /** check whether a given address is in a network we can probably connect to */
283 bool IsReachable(const CNetAddr
& addr
)
285 enum Network net
= addr
.GetNetwork();
286 return IsReachable(net
);
290 CNode
* CConnman::FindNode(const CNetAddr
& ip
)
293 BOOST_FOREACH(CNode
* pnode
, vNodes
)
294 if ((CNetAddr
)pnode
->addr
== ip
)
299 CNode
* CConnman::FindNode(const CSubNet
& subNet
)
302 BOOST_FOREACH(CNode
* pnode
, vNodes
)
303 if (subNet
.Match((CNetAddr
)pnode
->addr
))
308 CNode
* CConnman::FindNode(const std::string
& addrName
)
311 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
312 if (pnode
->GetAddrName() == addrName
) {
319 CNode
* CConnman::FindNode(const CService
& addr
)
322 BOOST_FOREACH(CNode
* pnode
, vNodes
)
323 if ((CService
)pnode
->addr
== addr
)
328 bool CConnman::CheckIncomingNonce(uint64_t nonce
)
331 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
332 if (!pnode
->fSuccessfullyConnected
&& !pnode
->fInbound
&& pnode
->GetLocalNonce() == nonce
)
338 CNode
* CConnman::ConnectNode(CAddress addrConnect
, const char *pszDest
, bool fCountFailure
)
340 if (pszDest
== NULL
) {
341 if (IsLocal(addrConnect
))
344 // Look for an existing connection
345 CNode
* pnode
= FindNode((CService
)addrConnect
);
348 LogPrintf("Failed to open new connection, already connected\n");
354 LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
355 pszDest
? pszDest
: addrConnect
.ToString(),
356 pszDest
? 0.0 : (double)(GetAdjustedTime() - addrConnect
.nTime
)/3600.0);
360 bool proxyConnectionFailed
= false;
361 if (pszDest
? ConnectSocketByName(addrConnect
, hSocket
, pszDest
, Params().GetDefaultPort(), nConnectTimeout
, &proxyConnectionFailed
) :
362 ConnectSocket(addrConnect
, hSocket
, nConnectTimeout
, &proxyConnectionFailed
))
364 if (!IsSelectableSocket(hSocket
)) {
365 LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
366 CloseSocket(hSocket
);
370 if (pszDest
&& addrConnect
.IsValid()) {
371 // It is possible that we already have a connection to the IP/port pszDest resolved to.
372 // In that case, drop the connection that was just created, and return the existing CNode instead.
373 // Also store the name we used to connect in that CNode, so that future FindNode() calls to that
374 // name catch this early.
376 CNode
* pnode
= FindNode((CService
)addrConnect
);
379 pnode
->MaybeSetAddrName(std::string(pszDest
));
380 CloseSocket(hSocket
);
381 LogPrintf("Failed to open new connection, already connected\n");
386 addrman
.Attempt(addrConnect
, fCountFailure
);
389 NodeId id
= GetNewNodeId();
390 uint64_t nonce
= GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE
).Write(id
).Finalize();
391 CNode
* pnode
= new CNode(id
, nLocalServices
, GetBestHeight(), hSocket
, addrConnect
, CalculateKeyedNetGroup(addrConnect
), nonce
, pszDest
? pszDest
: "", false);
392 pnode
->nServicesExpected
= ServiceFlags(addrConnect
.nServices
& nRelevantServices
);
396 } else if (!proxyConnectionFailed
) {
397 // If connecting to the node failed, and failure is not caused by a problem connecting to
398 // the proxy, mark this as an attempt.
399 addrman
.Attempt(addrConnect
, fCountFailure
);
405 void CConnman::DumpBanlist()
407 SweepBanned(); // clean unused entries (if bantime has expired)
409 if (!BannedSetIsDirty())
412 int64_t nStart
= GetTimeMillis();
416 SetBannedSetDirty(false);
418 if (!bandb
.Write(banmap
))
419 SetBannedSetDirty(true);
421 LogPrint("net", "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
422 banmap
.size(), GetTimeMillis() - nStart
);
425 void CNode::CloseSocketDisconnect()
429 if (hSocket
!= INVALID_SOCKET
)
431 LogPrint("net", "disconnecting peer=%d\n", id
);
432 CloseSocket(hSocket
);
436 void CConnman::ClearBanned()
441 setBannedIsDirty
= true;
443 DumpBanlist(); //store banlist to disk
445 clientInterface
->BannedListChanged();
448 bool CConnman::IsBanned(CNetAddr ip
)
450 bool fResult
= false;
453 for (banmap_t::iterator it
= setBanned
.begin(); it
!= setBanned
.end(); it
++)
455 CSubNet subNet
= (*it
).first
;
456 CBanEntry banEntry
= (*it
).second
;
458 if(subNet
.Match(ip
) && GetTime() < banEntry
.nBanUntil
)
465 bool CConnman::IsBanned(CSubNet subnet
)
467 bool fResult
= false;
470 banmap_t::iterator i
= setBanned
.find(subnet
);
471 if (i
!= setBanned
.end())
473 CBanEntry banEntry
= (*i
).second
;
474 if (GetTime() < banEntry
.nBanUntil
)
481 void CConnman::Ban(const CNetAddr
& addr
, const BanReason
&banReason
, int64_t bantimeoffset
, bool sinceUnixEpoch
) {
482 CSubNet
subNet(addr
);
483 Ban(subNet
, banReason
, bantimeoffset
, sinceUnixEpoch
);
486 void CConnman::Ban(const CSubNet
& subNet
, const BanReason
&banReason
, int64_t bantimeoffset
, bool sinceUnixEpoch
) {
487 CBanEntry
banEntry(GetTime());
488 banEntry
.banReason
= banReason
;
489 if (bantimeoffset
<= 0)
491 bantimeoffset
= GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME
);
492 sinceUnixEpoch
= false;
494 banEntry
.nBanUntil
= (sinceUnixEpoch
? 0 : GetTime() )+bantimeoffset
;
498 if (setBanned
[subNet
].nBanUntil
< banEntry
.nBanUntil
) {
499 setBanned
[subNet
] = banEntry
;
500 setBannedIsDirty
= true;
506 clientInterface
->BannedListChanged();
509 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
510 if (subNet
.Match((CNetAddr
)pnode
->addr
))
511 pnode
->fDisconnect
= true;
514 if(banReason
== BanReasonManuallyAdded
)
515 DumpBanlist(); //store banlist to disk immediately if user requested ban
518 bool CConnman::Unban(const CNetAddr
&addr
) {
519 CSubNet
subNet(addr
);
520 return Unban(subNet
);
523 bool CConnman::Unban(const CSubNet
&subNet
) {
526 if (!setBanned
.erase(subNet
))
528 setBannedIsDirty
= true;
531 clientInterface
->BannedListChanged();
532 DumpBanlist(); //store banlist to disk immediately
536 void CConnman::GetBanned(banmap_t
&banMap
)
539 banMap
= setBanned
; //create a thread safe copy
542 void CConnman::SetBanned(const banmap_t
&banMap
)
546 setBannedIsDirty
= true;
549 void CConnman::SweepBanned()
551 int64_t now
= GetTime();
554 banmap_t::iterator it
= setBanned
.begin();
555 while(it
!= setBanned
.end())
557 CSubNet subNet
= (*it
).first
;
558 CBanEntry banEntry
= (*it
).second
;
559 if(now
> banEntry
.nBanUntil
)
561 setBanned
.erase(it
++);
562 setBannedIsDirty
= true;
563 LogPrint("net", "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__
, subNet
.ToString());
570 bool CConnman::BannedSetIsDirty()
573 return setBannedIsDirty
;
576 void CConnman::SetBannedSetDirty(bool dirty
)
578 LOCK(cs_setBanned
); //reuse setBanned lock for the isDirty flag
579 setBannedIsDirty
= dirty
;
583 bool CConnman::IsWhitelistedRange(const CNetAddr
&addr
) {
584 LOCK(cs_vWhitelistedRange
);
585 BOOST_FOREACH(const CSubNet
& subnet
, vWhitelistedRange
) {
586 if (subnet
.Match(addr
))
592 void CConnman::AddWhitelistedRange(const CSubNet
&subnet
) {
593 LOCK(cs_vWhitelistedRange
);
594 vWhitelistedRange
.push_back(subnet
);
598 std::string
CNode::GetAddrName() const {
603 void CNode::MaybeSetAddrName(const std::string
& addrNameIn
) {
605 if (addrName
.empty()) {
606 addrName
= addrNameIn
;
610 CService
CNode::GetAddrLocal() const {
615 void CNode::SetAddrLocal(const CService
& addrLocalIn
) {
617 if (addrLocal
.IsValid()) {
618 error("Addr local already set for node: %i. Refusing to change from %s to %s", id
, addrLocal
.ToString(), addrLocalIn
.ToString());
620 addrLocal
= addrLocalIn
;
625 #define X(name) stats.name = name
626 void CNode::copyStats(CNodeStats
&stats
)
628 stats
.nodeid
= this->GetId();
639 stats
.addrName
= GetAddrName();
650 X(mapSendBytesPerMsgCmd
);
655 X(mapRecvBytesPerMsgCmd
);
660 // It is common for nodes with good ping times to suddenly become lagged,
661 // due to a new block arriving or other large transfer.
662 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
663 // since pingtime does not update until the ping is complete, which might take a while.
664 // So, if a ping is taking an unusually long time in flight,
665 // the caller can immediately detect that this is happening.
666 int64_t nPingUsecWait
= 0;
667 if ((0 != nPingNonceSent
) && (0 != nPingUsecStart
)) {
668 nPingUsecWait
= GetTimeMicros() - nPingUsecStart
;
671 // 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 :)
672 stats
.dPingTime
= (((double)nPingUsecTime
) / 1e6
);
673 stats
.dMinPing
= (((double)nMinPingUsecTime
) / 1e6
);
674 stats
.dPingWait
= (((double)nPingUsecWait
) / 1e6
);
676 // Leave string empty if addrLocal invalid (not filled in yet)
677 CService addrLocalUnlocked
= GetAddrLocal();
678 stats
.addrLocal
= addrLocalUnlocked
.IsValid() ? addrLocalUnlocked
.ToString() : "";
682 bool CNode::ReceiveMsgBytes(const char *pch
, unsigned int nBytes
, bool& complete
)
685 int64_t nTimeMicros
= GetTimeMicros();
687 nLastRecv
= nTimeMicros
/ 1000000;
688 nRecvBytes
+= nBytes
;
691 // get current incomplete message, or create a new one
692 if (vRecvMsg
.empty() ||
693 vRecvMsg
.back().complete())
694 vRecvMsg
.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK
, INIT_PROTO_VERSION
));
696 CNetMessage
& msg
= vRecvMsg
.back();
698 // absorb network data
701 handled
= msg
.readHeader(pch
, nBytes
);
703 handled
= msg
.readData(pch
, nBytes
);
708 if (msg
.in_data
&& msg
.hdr
.nMessageSize
> MAX_PROTOCOL_MESSAGE_LENGTH
) {
709 LogPrint("net", "Oversized message from peer=%i, disconnecting\n", GetId());
716 if (msg
.complete()) {
718 //store received bytes per message command
719 //to prevent a memory DOS, only allow valid commands
720 mapMsgCmdSize::iterator i
= mapRecvBytesPerMsgCmd
.find(msg
.hdr
.pchCommand
);
721 if (i
== mapRecvBytesPerMsgCmd
.end())
722 i
= mapRecvBytesPerMsgCmd
.find(NET_MESSAGE_COMMAND_OTHER
);
723 assert(i
!= mapRecvBytesPerMsgCmd
.end());
724 i
->second
+= msg
.hdr
.nMessageSize
+ CMessageHeader::HEADER_SIZE
;
726 msg
.nTime
= nTimeMicros
;
734 void CNode::SetSendVersion(int nVersionIn
)
736 // Send version may only be changed in the version message, and
737 // only one version message is allowed per session. We can therefore
738 // treat this value as const and even atomic as long as it's only used
739 // once a version message has been successfully processed. Any attempt to
740 // set this twice is an error.
741 if (nSendVersion
!= 0) {
742 error("Send version already set for node: %i. Refusing to change from %i to %i", id
, nSendVersion
, nVersionIn
);
744 nSendVersion
= nVersionIn
;
748 int CNode::GetSendVersion() const
750 // The send version should always be explicitly set to
751 // INIT_PROTO_VERSION rather than using this value until SetSendVersion
753 if (nSendVersion
== 0) {
754 error("Requesting unset send version for node: %i. Using %i", id
, INIT_PROTO_VERSION
);
755 return INIT_PROTO_VERSION
;
761 int CNetMessage::readHeader(const char *pch
, unsigned int nBytes
)
763 // copy data to temporary parsing buffer
764 unsigned int nRemaining
= 24 - nHdrPos
;
765 unsigned int nCopy
= std::min(nRemaining
, nBytes
);
767 memcpy(&hdrbuf
[nHdrPos
], pch
, nCopy
);
770 // if header incomplete, exit
774 // deserialize to CMessageHeader
778 catch (const std::exception
&) {
782 // reject messages larger than MAX_SIZE
783 if (hdr
.nMessageSize
> MAX_SIZE
)
786 // switch state to reading message data
792 int CNetMessage::readData(const char *pch
, unsigned int nBytes
)
794 unsigned int nRemaining
= hdr
.nMessageSize
- nDataPos
;
795 unsigned int nCopy
= std::min(nRemaining
, nBytes
);
797 if (vRecv
.size() < nDataPos
+ nCopy
) {
798 // Allocate up to 256 KiB ahead, but never more than the total message size.
799 vRecv
.resize(std::min(hdr
.nMessageSize
, nDataPos
+ nCopy
+ 256 * 1024));
802 hasher
.Write((const unsigned char*)pch
, nCopy
);
803 memcpy(&vRecv
[nDataPos
], pch
, nCopy
);
809 const uint256
& CNetMessage::GetMessageHash() const
812 if (data_hash
.IsNull())
813 hasher
.Finalize(data_hash
.begin());
825 // requires LOCK(cs_vSend)
826 size_t CConnman::SocketSendData(CNode
*pnode
) const
828 auto it
= pnode
->vSendMsg
.begin();
829 size_t nSentSize
= 0;
831 while (it
!= pnode
->vSendMsg
.end()) {
832 const auto &data
= *it
;
833 assert(data
.size() > pnode
->nSendOffset
);
836 LOCK(pnode
->cs_hSocket
);
837 if (pnode
->hSocket
== INVALID_SOCKET
)
839 nBytes
= send(pnode
->hSocket
, reinterpret_cast<const char*>(data
.data()) + pnode
->nSendOffset
, data
.size() - pnode
->nSendOffset
, MSG_NOSIGNAL
| MSG_DONTWAIT
);
842 pnode
->nLastSend
= GetSystemTimeInSeconds();
843 pnode
->nSendBytes
+= nBytes
;
844 pnode
->nSendOffset
+= nBytes
;
846 if (pnode
->nSendOffset
== data
.size()) {
847 pnode
->nSendOffset
= 0;
848 pnode
->nSendSize
-= data
.size();
849 pnode
->fPauseSend
= pnode
->nSendSize
> nSendBufferMaxSize
;
852 // could not send full message; stop sending more
858 int nErr
= WSAGetLastError();
859 if (nErr
!= WSAEWOULDBLOCK
&& nErr
!= WSAEMSGSIZE
&& nErr
!= WSAEINTR
&& nErr
!= WSAEINPROGRESS
)
861 LogPrintf("socket send error %s\n", NetworkErrorString(nErr
));
862 pnode
->CloseSocketDisconnect();
865 // couldn't send anything at all
870 if (it
== pnode
->vSendMsg
.end()) {
871 assert(pnode
->nSendOffset
== 0);
872 assert(pnode
->nSendSize
== 0);
874 pnode
->vSendMsg
.erase(pnode
->vSendMsg
.begin(), it
);
878 struct NodeEvictionCandidate
881 int64_t nTimeConnected
;
882 int64_t nMinPingUsecTime
;
883 int64_t nLastBlockTime
;
885 bool fRelevantServices
;
889 uint64_t nKeyedNetGroup
;
892 static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
894 return a
.nMinPingUsecTime
> b
.nMinPingUsecTime
;
897 static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
899 return a
.nTimeConnected
> b
.nTimeConnected
;
902 static bool CompareNetGroupKeyed(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
) {
903 return a
.nKeyedNetGroup
< b
.nKeyedNetGroup
;
906 static bool CompareNodeBlockTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
908 // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
909 if (a
.nLastBlockTime
!= b
.nLastBlockTime
) return a
.nLastBlockTime
< b
.nLastBlockTime
;
910 if (a
.fRelevantServices
!= b
.fRelevantServices
) return b
.fRelevantServices
;
911 return a
.nTimeConnected
> b
.nTimeConnected
;
914 static bool CompareNodeTXTime(const NodeEvictionCandidate
&a
, const NodeEvictionCandidate
&b
)
916 // 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.
917 if (a
.nLastTXTime
!= b
.nLastTXTime
) return a
.nLastTXTime
< b
.nLastTXTime
;
918 if (a
.fRelayTxes
!= b
.fRelayTxes
) return b
.fRelayTxes
;
919 if (a
.fBloomFilter
!= b
.fBloomFilter
) return a
.fBloomFilter
;
920 return a
.nTimeConnected
> b
.nTimeConnected
;
923 /** Try to find a connection to evict when the node is full.
924 * Extreme care must be taken to avoid opening the node to attacker
925 * triggered network partitioning.
926 * The strategy used here is to protect a small number of peers
927 * for each of several distinct characteristics which are difficult
928 * to forge. In order to partition a node the attacker must be
929 * simultaneously better at all of them than honest peers.
931 bool CConnman::AttemptToEvictConnection()
933 std::vector
<NodeEvictionCandidate
> vEvictionCandidates
;
937 BOOST_FOREACH(CNode
*node
, vNodes
) {
938 if (node
->fWhitelisted
)
942 if (node
->fDisconnect
)
944 NodeEvictionCandidate candidate
= {node
->id
, node
->nTimeConnected
, node
->nMinPingUsecTime
,
945 node
->nLastBlockTime
, node
->nLastTXTime
,
946 (node
->nServices
& nRelevantServices
) == nRelevantServices
,
947 node
->fRelayTxes
, node
->pfilter
!= NULL
, node
->addr
, node
->nKeyedNetGroup
};
948 vEvictionCandidates
.push_back(candidate
);
952 if (vEvictionCandidates
.empty()) return false;
954 // Protect connections with certain characteristics
956 // Deterministically select 4 peers to protect by netgroup.
957 // An attacker cannot predict which netgroups will be protected
958 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNetGroupKeyed
);
959 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
961 if (vEvictionCandidates
.empty()) return false;
963 // Protect the 8 nodes with the lowest minimum ping time.
964 // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
965 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), ReverseCompareNodeMinPingTime
);
966 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(8, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
968 if (vEvictionCandidates
.empty()) return false;
970 // Protect 4 nodes that most recently sent us transactions.
971 // An attacker cannot manipulate this metric without performing useful work.
972 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNodeTXTime
);
973 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
975 if (vEvictionCandidates
.empty()) return false;
977 // Protect 4 nodes that most recently sent us blocks.
978 // An attacker cannot manipulate this metric without performing useful work.
979 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), CompareNodeBlockTime
);
980 vEvictionCandidates
.erase(vEvictionCandidates
.end() - std::min(4, static_cast<int>(vEvictionCandidates
.size())), vEvictionCandidates
.end());
982 if (vEvictionCandidates
.empty()) return false;
984 // Protect the half of the remaining nodes which have been connected the longest.
985 // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
986 std::sort(vEvictionCandidates
.begin(), vEvictionCandidates
.end(), ReverseCompareNodeTimeConnected
);
987 vEvictionCandidates
.erase(vEvictionCandidates
.end() - static_cast<int>(vEvictionCandidates
.size() / 2), vEvictionCandidates
.end());
989 if (vEvictionCandidates
.empty()) return false;
991 // Identify the network group with the most connections and youngest member.
992 // (vEvictionCandidates is already sorted by reverse connect time)
993 uint64_t naMostConnections
;
994 unsigned int nMostConnections
= 0;
995 int64_t nMostConnectionsTime
= 0;
996 std::map
<uint64_t, std::vector
<NodeEvictionCandidate
> > mapNetGroupNodes
;
997 BOOST_FOREACH(const NodeEvictionCandidate
&node
, vEvictionCandidates
) {
998 mapNetGroupNodes
[node
.nKeyedNetGroup
].push_back(node
);
999 int64_t grouptime
= mapNetGroupNodes
[node
.nKeyedNetGroup
][0].nTimeConnected
;
1000 size_t groupsize
= mapNetGroupNodes
[node
.nKeyedNetGroup
].size();
1002 if (groupsize
> nMostConnections
|| (groupsize
== nMostConnections
&& grouptime
> nMostConnectionsTime
)) {
1003 nMostConnections
= groupsize
;
1004 nMostConnectionsTime
= grouptime
;
1005 naMostConnections
= node
.nKeyedNetGroup
;
1009 // Reduce to the network group with the most connections
1010 vEvictionCandidates
= std::move(mapNetGroupNodes
[naMostConnections
]);
1012 // Disconnect from the network group with the most connections
1013 NodeId evicted
= vEvictionCandidates
.front().id
;
1015 for(std::vector
<CNode
*>::const_iterator
it(vNodes
.begin()); it
!= vNodes
.end(); ++it
) {
1016 if ((*it
)->GetId() == evicted
) {
1017 (*it
)->fDisconnect
= true;
1024 void CConnman::AcceptConnection(const ListenSocket
& hListenSocket
) {
1025 struct sockaddr_storage sockaddr
;
1026 socklen_t len
= sizeof(sockaddr
);
1027 SOCKET hSocket
= accept(hListenSocket
.socket
, (struct sockaddr
*)&sockaddr
, &len
);
1030 int nMaxInbound
= nMaxConnections
- (nMaxOutbound
+ nMaxFeeler
);
1032 if (hSocket
!= INVALID_SOCKET
)
1033 if (!addr
.SetSockAddr((const struct sockaddr
*)&sockaddr
))
1034 LogPrintf("Warning: Unknown socket family\n");
1036 bool whitelisted
= hListenSocket
.whitelisted
|| IsWhitelistedRange(addr
);
1039 BOOST_FOREACH(CNode
* pnode
, vNodes
)
1040 if (pnode
->fInbound
)
1044 if (hSocket
== INVALID_SOCKET
)
1046 int nErr
= WSAGetLastError();
1047 if (nErr
!= WSAEWOULDBLOCK
)
1048 LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr
));
1052 if (!fNetworkActive
) {
1053 LogPrintf("connection from %s dropped: not accepting new connections\n", addr
.ToString());
1054 CloseSocket(hSocket
);
1058 if (!IsSelectableSocket(hSocket
))
1060 LogPrintf("connection from %s dropped: non-selectable socket\n", addr
.ToString());
1061 CloseSocket(hSocket
);
1065 // According to the internet TCP_NODELAY is not carried into accepted sockets
1066 // on all platforms. Set it again here just to be sure.
1069 setsockopt(hSocket
, IPPROTO_TCP
, TCP_NODELAY
, (const char*)&set
, sizeof(int));
1071 setsockopt(hSocket
, IPPROTO_TCP
, TCP_NODELAY
, (void*)&set
, sizeof(int));
1074 if (IsBanned(addr
) && !whitelisted
)
1076 LogPrintf("connection from %s dropped (banned)\n", addr
.ToString());
1077 CloseSocket(hSocket
);
1081 if (nInbound
>= nMaxInbound
)
1083 if (!AttemptToEvictConnection()) {
1084 // No connection to evict, disconnect the new connection
1085 LogPrint("net", "failed to find an eviction candidate - connection dropped (full)\n");
1086 CloseSocket(hSocket
);
1091 NodeId id
= GetNewNodeId();
1092 uint64_t nonce
= GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE
).Write(id
).Finalize();
1094 CNode
* pnode
= new CNode(id
, nLocalServices
, GetBestHeight(), hSocket
, addr
, CalculateKeyedNetGroup(addr
), nonce
, "", true);
1096 pnode
->fWhitelisted
= whitelisted
;
1097 GetNodeSignals().InitializeNode(pnode
, *this);
1099 LogPrint("net", "connection from %s accepted\n", addr
.ToString());
1103 vNodes
.push_back(pnode
);
1107 void CConnman::ThreadSocketHandler()
1109 unsigned int nPrevNodeCount
= 0;
1110 while (!interruptNet
)
1117 // Disconnect unused nodes
1118 std::vector
<CNode
*> vNodesCopy
= vNodes
;
1119 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1121 if (pnode
->fDisconnect
)
1123 // remove from vNodes
1124 vNodes
.erase(remove(vNodes
.begin(), vNodes
.end(), pnode
), vNodes
.end());
1126 // release outbound grant (if any)
1127 pnode
->grantOutbound
.Release();
1129 // close socket and cleanup
1130 pnode
->CloseSocketDisconnect();
1132 // hold in disconnected pool until all refs are released
1134 vNodesDisconnected
.push_back(pnode
);
1139 // Delete disconnected nodes
1140 std::list
<CNode
*> vNodesDisconnectedCopy
= vNodesDisconnected
;
1141 BOOST_FOREACH(CNode
* pnode
, vNodesDisconnectedCopy
)
1143 // wait until threads are done using it
1144 if (pnode
->GetRefCount() <= 0) {
1145 bool fDelete
= false;
1147 TRY_LOCK(pnode
->cs_inventory
, lockInv
);
1149 TRY_LOCK(pnode
->cs_vSend
, lockSend
);
1156 vNodesDisconnected
.remove(pnode
);
1165 vNodesSize
= vNodes
.size();
1167 if(vNodesSize
!= nPrevNodeCount
) {
1168 nPrevNodeCount
= vNodesSize
;
1170 clientInterface
->NotifyNumConnectionsChanged(nPrevNodeCount
);
1174 // Find which sockets have data to receive
1176 struct timeval timeout
;
1178 timeout
.tv_usec
= 50000; // frequency to poll pnode->vSend
1183 FD_ZERO(&fdsetRecv
);
1184 FD_ZERO(&fdsetSend
);
1185 FD_ZERO(&fdsetError
);
1186 SOCKET hSocketMax
= 0;
1187 bool have_fds
= false;
1189 BOOST_FOREACH(const ListenSocket
& hListenSocket
, vhListenSocket
) {
1190 FD_SET(hListenSocket
.socket
, &fdsetRecv
);
1191 hSocketMax
= std::max(hSocketMax
, hListenSocket
.socket
);
1197 BOOST_FOREACH(CNode
* pnode
, vNodes
)
1199 // Implement the following logic:
1200 // * If there is data to send, select() for sending data. As this only
1201 // happens when optimistic write failed, we choose to first drain the
1202 // write buffer in this case before receiving more. This avoids
1203 // needlessly queueing received data, if the remote peer is not themselves
1204 // receiving data. This means properly utilizing TCP flow control signalling.
1205 // * Otherwise, if there is space left in the receive buffer, select() for
1207 // * Hand off all complete messages to the processor, to be handled without
1210 bool select_recv
= !pnode
->fPauseRecv
;
1213 LOCK(pnode
->cs_vSend
);
1214 select_send
= !pnode
->vSendMsg
.empty();
1217 LOCK(pnode
->cs_hSocket
);
1218 if (pnode
->hSocket
== INVALID_SOCKET
)
1221 FD_SET(pnode
->hSocket
, &fdsetError
);
1222 hSocketMax
= std::max(hSocketMax
, pnode
->hSocket
);
1226 FD_SET(pnode
->hSocket
, &fdsetSend
);
1230 FD_SET(pnode
->hSocket
, &fdsetRecv
);
1235 int nSelect
= select(have_fds
? hSocketMax
+ 1 : 0,
1236 &fdsetRecv
, &fdsetSend
, &fdsetError
, &timeout
);
1240 if (nSelect
== SOCKET_ERROR
)
1244 int nErr
= WSAGetLastError();
1245 LogPrintf("socket select error %s\n", NetworkErrorString(nErr
));
1246 for (unsigned int i
= 0; i
<= hSocketMax
; i
++)
1247 FD_SET(i
, &fdsetRecv
);
1249 FD_ZERO(&fdsetSend
);
1250 FD_ZERO(&fdsetError
);
1251 if (!interruptNet
.sleep_for(std::chrono::milliseconds(timeout
.tv_usec
/1000)))
1256 // Accept new connections
1258 BOOST_FOREACH(const ListenSocket
& hListenSocket
, vhListenSocket
)
1260 if (hListenSocket
.socket
!= INVALID_SOCKET
&& FD_ISSET(hListenSocket
.socket
, &fdsetRecv
))
1262 AcceptConnection(hListenSocket
);
1267 // Service each socket
1269 std::vector
<CNode
*> vNodesCopy
;
1272 vNodesCopy
= vNodes
;
1273 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1276 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1284 bool recvSet
= false;
1285 bool sendSet
= false;
1286 bool errorSet
= false;
1288 LOCK(pnode
->cs_hSocket
);
1289 if (pnode
->hSocket
== INVALID_SOCKET
)
1291 recvSet
= FD_ISSET(pnode
->hSocket
, &fdsetRecv
);
1292 sendSet
= FD_ISSET(pnode
->hSocket
, &fdsetSend
);
1293 errorSet
= FD_ISSET(pnode
->hSocket
, &fdsetError
);
1295 if (recvSet
|| errorSet
)
1299 // typical socket buffer is 8K-64K
1300 char pchBuf
[0x10000];
1303 LOCK(pnode
->cs_hSocket
);
1304 if (pnode
->hSocket
== INVALID_SOCKET
)
1306 nBytes
= recv(pnode
->hSocket
, pchBuf
, sizeof(pchBuf
), MSG_DONTWAIT
);
1310 bool notify
= false;
1311 if (!pnode
->ReceiveMsgBytes(pchBuf
, nBytes
, notify
))
1312 pnode
->CloseSocketDisconnect();
1313 RecordBytesRecv(nBytes
);
1315 size_t nSizeAdded
= 0;
1316 auto it(pnode
->vRecvMsg
.begin());
1317 for (; it
!= pnode
->vRecvMsg
.end(); ++it
) {
1318 if (!it
->complete())
1320 nSizeAdded
+= it
->vRecv
.size() + CMessageHeader::HEADER_SIZE
;
1323 LOCK(pnode
->cs_vProcessMsg
);
1324 pnode
->vProcessMsg
.splice(pnode
->vProcessMsg
.end(), pnode
->vRecvMsg
, pnode
->vRecvMsg
.begin(), it
);
1325 pnode
->nProcessQueueSize
+= nSizeAdded
;
1326 pnode
->fPauseRecv
= pnode
->nProcessQueueSize
> nReceiveFloodSize
;
1328 WakeMessageHandler();
1331 else if (nBytes
== 0)
1333 // socket closed gracefully
1334 if (!pnode
->fDisconnect
)
1335 LogPrint("net", "socket closed\n");
1336 pnode
->CloseSocketDisconnect();
1338 else if (nBytes
< 0)
1341 int nErr
= WSAGetLastError();
1342 if (nErr
!= WSAEWOULDBLOCK
&& nErr
!= WSAEMSGSIZE
&& nErr
!= WSAEINTR
&& nErr
!= WSAEINPROGRESS
)
1344 if (!pnode
->fDisconnect
)
1345 LogPrintf("socket recv error %s\n", NetworkErrorString(nErr
));
1346 pnode
->CloseSocketDisconnect();
1358 LOCK(pnode
->cs_vSend
);
1359 size_t nBytes
= SocketSendData(pnode
);
1361 RecordBytesSent(nBytes
);
1366 // Inactivity checking
1368 int64_t nTime
= GetSystemTimeInSeconds();
1369 if (nTime
- pnode
->nTimeConnected
> 60)
1371 if (pnode
->nLastRecv
== 0 || pnode
->nLastSend
== 0)
1373 LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode
->nLastRecv
!= 0, pnode
->nLastSend
!= 0, pnode
->id
);
1374 pnode
->fDisconnect
= true;
1376 else if (nTime
- pnode
->nLastSend
> TIMEOUT_INTERVAL
)
1378 LogPrintf("socket sending timeout: %is\n", nTime
- pnode
->nLastSend
);
1379 pnode
->fDisconnect
= true;
1381 else if (nTime
- pnode
->nLastRecv
> (pnode
->nVersion
> BIP0031_VERSION
? TIMEOUT_INTERVAL
: 90*60))
1383 LogPrintf("socket receive timeout: %is\n", nTime
- pnode
->nLastRecv
);
1384 pnode
->fDisconnect
= true;
1386 else if (pnode
->nPingNonceSent
&& pnode
->nPingUsecStart
+ TIMEOUT_INTERVAL
* 1000000 < GetTimeMicros())
1388 LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode
->nPingUsecStart
));
1389 pnode
->fDisconnect
= true;
1391 else if (!pnode
->fSuccessfullyConnected
)
1393 LogPrintf("version handshake timeout from %d\n", pnode
->id
);
1394 pnode
->fDisconnect
= true;
1400 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1406 void CConnman::WakeMessageHandler()
1409 std::lock_guard
<std::mutex
> lock(mutexMsgProc
);
1410 fMsgProcWake
= true;
1412 condMsgProc
.notify_one();
1421 void ThreadMapPort()
1423 std::string port
= strprintf("%u", GetListenPort());
1424 const char * multicastif
= 0;
1425 const char * minissdpdpath
= 0;
1426 struct UPNPDev
* devlist
= 0;
1429 #ifndef UPNPDISCOVER_SUCCESS
1431 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0);
1432 #elif MINIUPNPC_API_VERSION < 14
1435 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0, 0, &error
);
1437 /* miniupnpc 1.9.20150730 */
1439 devlist
= upnpDiscover(2000, multicastif
, minissdpdpath
, 0, 0, 2, &error
);
1442 struct UPNPUrls urls
;
1443 struct IGDdatas data
;
1446 r
= UPNP_GetValidIGD(devlist
, &urls
, &data
, lanaddr
, sizeof(lanaddr
));
1450 char externalIPAddress
[40];
1451 r
= UPNP_GetExternalIPAddress(urls
.controlURL
, data
.first
.servicetype
, externalIPAddress
);
1452 if(r
!= UPNPCOMMAND_SUCCESS
)
1453 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r
);
1456 if(externalIPAddress
[0])
1459 if(LookupHost(externalIPAddress
, resolved
, false)) {
1460 LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved
.ToString().c_str());
1461 AddLocal(resolved
, LOCAL_UPNP
);
1465 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1469 std::string strDesc
= "Bitcoin " + FormatFullVersion();
1473 #ifndef UPNPDISCOVER_SUCCESS
1475 r
= UPNP_AddPortMapping(urls
.controlURL
, data
.first
.servicetype
,
1476 port
.c_str(), port
.c_str(), lanaddr
, strDesc
.c_str(), "TCP", 0);
1479 r
= UPNP_AddPortMapping(urls
.controlURL
, data
.first
.servicetype
,
1480 port
.c_str(), port
.c_str(), lanaddr
, strDesc
.c_str(), "TCP", 0, "0");
1483 if(r
!=UPNPCOMMAND_SUCCESS
)
1484 LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1485 port
, port
, lanaddr
, r
, strupnperror(r
));
1487 LogPrintf("UPnP Port Mapping successful.\n");
1489 MilliSleep(20*60*1000); // Refresh every 20 minutes
1492 catch (const boost::thread_interrupted
&)
1494 r
= UPNP_DeletePortMapping(urls
.controlURL
, data
.first
.servicetype
, port
.c_str(), "TCP", 0);
1495 LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r
);
1496 freeUPNPDevlist(devlist
); devlist
= 0;
1497 FreeUPNPUrls(&urls
);
1501 LogPrintf("No valid UPnP IGDs found\n");
1502 freeUPNPDevlist(devlist
); devlist
= 0;
1504 FreeUPNPUrls(&urls
);
1508 void MapPort(bool fUseUPnP
)
1510 static boost::thread
* upnp_thread
= NULL
;
1515 upnp_thread
->interrupt();
1516 upnp_thread
->join();
1519 upnp_thread
= new boost::thread(boost::bind(&TraceThread
<void (*)()>, "upnp", &ThreadMapPort
));
1521 else if (upnp_thread
) {
1522 upnp_thread
->interrupt();
1523 upnp_thread
->join();
1532 // Intentionally left blank.
1541 static std::string
GetDNSHost(const CDNSSeedData
& data
, ServiceFlags
* requiredServiceBits
)
1543 //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
1544 if (!data
.supportsServiceBitsFiltering
|| *requiredServiceBits
== NODE_NETWORK
) {
1545 *requiredServiceBits
= NODE_NETWORK
;
1549 // See chainparams.cpp, most dnsseeds only support one or two possible servicebits hostnames
1550 return strprintf("x%x.%s", *requiredServiceBits
, data
.host
);
1554 void CConnman::ThreadDNSAddressSeed()
1556 // goal: only query DNS seeds if address need is acute
1557 // Avoiding DNS seeds when we don't need them improves user privacy by
1558 // creating fewer identifying DNS requests, reduces trust by giving seeds
1559 // less influence on the network topology, and reduces traffic to the seeds.
1560 if ((addrman
.size() > 0) &&
1561 (!GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED
))) {
1562 if (!interruptNet
.sleep_for(std::chrono::seconds(11)))
1567 for (auto pnode
: vNodes
) {
1568 nRelevant
+= pnode
->fSuccessfullyConnected
&& ((pnode
->nServices
& nRelevantServices
) == nRelevantServices
);
1570 if (nRelevant
>= 2) {
1571 LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1576 const std::vector
<CDNSSeedData
> &vSeeds
= Params().DNSSeeds();
1579 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1581 BOOST_FOREACH(const CDNSSeedData
&seed
, vSeeds
) {
1582 if (HaveNameProxy()) {
1583 AddOneShot(seed
.host
);
1585 std::vector
<CNetAddr
> vIPs
;
1586 std::vector
<CAddress
> vAdd
;
1587 ServiceFlags requiredServiceBits
= nRelevantServices
;
1588 if (LookupHost(GetDNSHost(seed
, &requiredServiceBits
).c_str(), vIPs
, 0, true))
1590 BOOST_FOREACH(const CNetAddr
& ip
, vIPs
)
1592 int nOneDay
= 24*3600;
1593 CAddress addr
= CAddress(CService(ip
, Params().GetDefaultPort()), requiredServiceBits
);
1594 addr
.nTime
= GetTime() - 3*nOneDay
- GetRand(4*nOneDay
); // use a random age between 3 and 7 days old
1595 vAdd
.push_back(addr
);
1599 // TODO: The seed name resolve may fail, yielding an IP of [::], which results in
1600 // addrman assigning the same source to results from different seeds.
1601 // This should switch to a hard-coded stable dummy IP for each seed name, so that the
1602 // resolve is not required at all.
1603 if (!vIPs
.empty()) {
1604 CService seedSource
;
1605 Lookup(seed
.name
.c_str(), seedSource
, 0, true);
1606 addrman
.Add(vAdd
, seedSource
);
1611 LogPrintf("%d addresses found from DNS seeds\n", found
);
1625 void CConnman::DumpAddresses()
1627 int64_t nStart
= GetTimeMillis();
1632 LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
1633 addrman
.size(), GetTimeMillis() - nStart
);
1636 void CConnman::DumpData()
1642 void CConnman::ProcessOneShot()
1644 std::string strDest
;
1647 if (vOneShots
.empty())
1649 strDest
= vOneShots
.front();
1650 vOneShots
.pop_front();
1653 CSemaphoreGrant
grant(*semOutbound
, true);
1655 if (!OpenNetworkConnection(addr
, false, &grant
, strDest
.c_str(), true))
1656 AddOneShot(strDest
);
1660 void CConnman::ThreadOpenConnections()
1662 // Connect to specific addresses
1663 if (mapMultiArgs
.count("-connect") && mapMultiArgs
.at("-connect").size() > 0)
1665 for (int64_t nLoop
= 0;; nLoop
++)
1668 BOOST_FOREACH(const std::string
& strAddr
, mapMultiArgs
.at("-connect"))
1670 CAddress
addr(CService(), NODE_NONE
);
1671 OpenNetworkConnection(addr
, false, NULL
, strAddr
.c_str());
1672 for (int i
= 0; i
< 10 && i
< nLoop
; i
++)
1674 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1678 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1683 // Initiate network connections
1684 int64_t nStart
= GetTime();
1686 // Minimum time before next feeler connection (in microseconds).
1687 int64_t nNextFeeler
= PoissonNextSend(nStart
*1000*1000, FEELER_INTERVAL
);
1688 while (!interruptNet
)
1692 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1695 CSemaphoreGrant
grant(*semOutbound
);
1699 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1700 if (addrman
.size() == 0 && (GetTime() - nStart
> 60)) {
1701 static bool done
= false;
1703 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1705 LookupHost("127.0.0.1", local
, false);
1706 addrman
.Add(convertSeed6(Params().FixedSeeds()), local
);
1712 // Choose an address to connect to based on most recently seen
1714 CAddress addrConnect
;
1716 // Only connect out to one peer per network group (/16 for IPv4).
1717 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1719 std::set
<std::vector
<unsigned char> > setConnected
;
1722 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
1723 if (!pnode
->fInbound
&& !pnode
->fAddnode
) {
1724 // Netgroups for inbound and addnode peers are not excluded because our goal here
1725 // is to not use multiple of our limited outbound slots on a single netgroup
1726 // but inbound and addnode peers do not use our outbound slots. Inbound peers
1727 // also have the added issue that they're attacker controlled and could be used
1728 // to prevent us from connecting to particular hosts if we used them here.
1729 setConnected
.insert(pnode
->addr
.GetGroup());
1735 // Feeler Connections
1738 // * Increase the number of connectable addresses in the tried table.
1741 // * Choose a random address from new and attempt to connect to it if we can connect
1742 // successfully it is added to tried.
1743 // * Start attempting feeler connections only after node finishes making outbound
1745 // * Only make a feeler connection once every few minutes.
1747 bool fFeeler
= false;
1748 if (nOutbound
>= nMaxOutbound
) {
1749 int64_t nTime
= GetTimeMicros(); // The current time right now (in microseconds).
1750 if (nTime
> nNextFeeler
) {
1751 nNextFeeler
= PoissonNextSend(nTime
, FEELER_INTERVAL
);
1758 int64_t nANow
= GetAdjustedTime();
1760 while (!interruptNet
)
1762 CAddrInfo addr
= addrman
.Select(fFeeler
);
1764 // if we selected an invalid address, restart
1765 if (!addr
.IsValid() || setConnected
.count(addr
.GetGroup()) || IsLocal(addr
))
1768 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1769 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1770 // already-connected network ranges, ...) before trying new addrman addresses.
1775 if (IsLimited(addr
))
1778 // only connect to full nodes
1779 if ((addr
.nServices
& REQUIRED_SERVICES
) != REQUIRED_SERVICES
)
1782 // only consider very recently tried nodes after 30 failed attempts
1783 if (nANow
- addr
.nLastTry
< 600 && nTries
< 30)
1786 // only consider nodes missing relevant services after 40 failed attempts and only if less than half the outbound are up.
1787 if ((addr
.nServices
& nRelevantServices
) != nRelevantServices
&& (nTries
< 40 || nOutbound
>= (nMaxOutbound
>> 1)))
1790 // do not allow non-default ports, unless after 50 invalid addresses selected already
1791 if (addr
.GetPort() != Params().GetDefaultPort() && nTries
< 50)
1798 if (addrConnect
.IsValid()) {
1801 // Add small amount of random noise before connection to avoid synchronization.
1802 int randsleep
= GetRandInt(FEELER_SLEEP_WINDOW
* 1000);
1803 if (!interruptNet
.sleep_for(std::chrono::milliseconds(randsleep
)))
1805 LogPrint("net", "Making feeler connection to %s\n", addrConnect
.ToString());
1808 OpenNetworkConnection(addrConnect
, (int)setConnected
.size() >= std::min(nMaxConnections
- 1, 2), &grant
, NULL
, false, fFeeler
);
1813 std::vector
<AddedNodeInfo
> CConnman::GetAddedNodeInfo()
1815 std::vector
<AddedNodeInfo
> ret
;
1817 std::list
<std::string
> lAddresses(0);
1819 LOCK(cs_vAddedNodes
);
1820 ret
.reserve(vAddedNodes
.size());
1821 BOOST_FOREACH(const std::string
& strAddNode
, vAddedNodes
)
1822 lAddresses
.push_back(strAddNode
);
1826 // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
1827 std::map
<CService
, bool> mapConnected
;
1828 std::map
<std::string
, std::pair
<bool, CService
>> mapConnectedByName
;
1831 for (const CNode
* pnode
: vNodes
) {
1832 if (pnode
->addr
.IsValid()) {
1833 mapConnected
[pnode
->addr
] = pnode
->fInbound
;
1835 std::string addrName
= pnode
->GetAddrName();
1836 if (!addrName
.empty()) {
1837 mapConnectedByName
[std::move(addrName
)] = std::make_pair(pnode
->fInbound
, static_cast<const CService
&>(pnode
->addr
));
1842 BOOST_FOREACH(const std::string
& strAddNode
, lAddresses
) {
1843 CService
service(LookupNumeric(strAddNode
.c_str(), Params().GetDefaultPort()));
1844 if (service
.IsValid()) {
1845 // strAddNode is an IP:port
1846 auto it
= mapConnected
.find(service
);
1847 if (it
!= mapConnected
.end()) {
1848 ret
.push_back(AddedNodeInfo
{strAddNode
, service
, true, it
->second
});
1850 ret
.push_back(AddedNodeInfo
{strAddNode
, CService(), false, false});
1853 // strAddNode is a name
1854 auto it
= mapConnectedByName
.find(strAddNode
);
1855 if (it
!= mapConnectedByName
.end()) {
1856 ret
.push_back(AddedNodeInfo
{strAddNode
, it
->second
.second
, true, it
->second
.first
});
1858 ret
.push_back(AddedNodeInfo
{strAddNode
, CService(), false, false});
1866 void CConnman::ThreadOpenAddedConnections()
1869 LOCK(cs_vAddedNodes
);
1870 if (mapMultiArgs
.count("-addnode"))
1871 vAddedNodes
= mapMultiArgs
.at("-addnode");
1876 CSemaphoreGrant
grant(*semAddnode
);
1877 std::vector
<AddedNodeInfo
> vInfo
= GetAddedNodeInfo();
1879 for (const AddedNodeInfo
& info
: vInfo
) {
1880 if (!info
.fConnected
) {
1881 if (!grant
.TryAcquire()) {
1882 // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
1883 // the addednodeinfo state might change.
1886 // If strAddedNode is an IP/port, decode it immediately, so
1887 // OpenNetworkConnection can detect existing connections to that IP/port.
1889 CService
service(LookupNumeric(info
.strAddedNode
.c_str(), Params().GetDefaultPort()));
1890 OpenNetworkConnection(CAddress(service
, NODE_NONE
), false, &grant
, info
.strAddedNode
.c_str(), false, false, true);
1891 if (!interruptNet
.sleep_for(std::chrono::milliseconds(500)))
1895 // Retry every 60 seconds if a connection was attempted, otherwise two seconds
1896 if (!interruptNet
.sleep_for(std::chrono::seconds(tried
? 60 : 2)))
1901 // if successful, this moves the passed grant to the constructed node
1902 bool CConnman::OpenNetworkConnection(const CAddress
& addrConnect
, bool fCountFailure
, CSemaphoreGrant
*grantOutbound
, const char *pszDest
, bool fOneShot
, bool fFeeler
, bool fAddnode
)
1905 // Initiate outbound network connection
1910 if (!fNetworkActive
) {
1914 if (IsLocal(addrConnect
) ||
1915 FindNode((CNetAddr
)addrConnect
) || IsBanned(addrConnect
) ||
1916 FindNode(addrConnect
.ToStringIPPort()))
1918 } else if (FindNode(std::string(pszDest
)))
1921 CNode
* pnode
= ConnectNode(addrConnect
, pszDest
, fCountFailure
);
1926 grantOutbound
->MoveTo(pnode
->grantOutbound
);
1928 pnode
->fOneShot
= true;
1930 pnode
->fFeeler
= true;
1932 pnode
->fAddnode
= true;
1934 GetNodeSignals().InitializeNode(pnode
, *this);
1937 vNodes
.push_back(pnode
);
1943 void CConnman::ThreadMessageHandler()
1945 while (!flagInterruptMsgProc
)
1947 std::vector
<CNode
*> vNodesCopy
;
1950 vNodesCopy
= vNodes
;
1951 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
) {
1956 bool fMoreWork
= false;
1958 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1960 if (pnode
->fDisconnect
)
1964 bool fMoreNodeWork
= GetNodeSignals().ProcessMessages(pnode
, *this, flagInterruptMsgProc
);
1965 fMoreWork
|= (fMoreNodeWork
&& !pnode
->fPauseSend
);
1966 if (flagInterruptMsgProc
)
1971 LOCK(pnode
->cs_sendProcessing
);
1972 GetNodeSignals().SendMessages(pnode
, *this, flagInterruptMsgProc
);
1974 if (flagInterruptMsgProc
)
1980 BOOST_FOREACH(CNode
* pnode
, vNodesCopy
)
1984 std::unique_lock
<std::mutex
> lock(mutexMsgProc
);
1986 condMsgProc
.wait_until(lock
, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake
; });
1988 fMsgProcWake
= false;
1997 bool CConnman::BindListenPort(const CService
&addrBind
, std::string
& strError
, bool fWhitelisted
)
2002 // Create socket for listening for incoming connections
2003 struct sockaddr_storage sockaddr
;
2004 socklen_t len
= sizeof(sockaddr
);
2005 if (!addrBind
.GetSockAddr((struct sockaddr
*)&sockaddr
, &len
))
2007 strError
= strprintf("Error: Bind address family for %s not supported", addrBind
.ToString());
2008 LogPrintf("%s\n", strError
);
2012 SOCKET hListenSocket
= socket(((struct sockaddr
*)&sockaddr
)->sa_family
, SOCK_STREAM
, IPPROTO_TCP
);
2013 if (hListenSocket
== INVALID_SOCKET
)
2015 strError
= strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2016 LogPrintf("%s\n", strError
);
2019 if (!IsSelectableSocket(hListenSocket
))
2021 strError
= "Error: Couldn't create a listenable socket for incoming connections";
2022 LogPrintf("%s\n", strError
);
2029 // Different way of disabling SIGPIPE on BSD
2030 setsockopt(hListenSocket
, SOL_SOCKET
, SO_NOSIGPIPE
, (void*)&nOne
, sizeof(int));
2032 // Allow binding if the port is still in TIME_WAIT state after
2033 // the program was closed and restarted.
2034 setsockopt(hListenSocket
, SOL_SOCKET
, SO_REUSEADDR
, (void*)&nOne
, sizeof(int));
2035 // Disable Nagle's algorithm
2036 setsockopt(hListenSocket
, IPPROTO_TCP
, TCP_NODELAY
, (void*)&nOne
, sizeof(int));
2038 setsockopt(hListenSocket
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&nOne
, sizeof(int));
2039 setsockopt(hListenSocket
, IPPROTO_TCP
, TCP_NODELAY
, (const char*)&nOne
, sizeof(int));
2042 // Set to non-blocking, incoming connections will also inherit this
2043 if (!SetSocketNonBlocking(hListenSocket
, true)) {
2044 strError
= strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
2045 LogPrintf("%s\n", strError
);
2049 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2050 // and enable it by default or not. Try to enable it, if possible.
2051 if (addrBind
.IsIPv6()) {
2054 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_V6ONLY
, (const char*)&nOne
, sizeof(int));
2056 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_V6ONLY
, (void*)&nOne
, sizeof(int));
2060 int nProtLevel
= PROTECTION_LEVEL_UNRESTRICTED
;
2061 setsockopt(hListenSocket
, IPPROTO_IPV6
, IPV6_PROTECTION_LEVEL
, (const char*)&nProtLevel
, sizeof(int));
2065 if (::bind(hListenSocket
, (struct sockaddr
*)&sockaddr
, len
) == SOCKET_ERROR
)
2067 int nErr
= WSAGetLastError();
2068 if (nErr
== WSAEADDRINUSE
)
2069 strError
= strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind
.ToString(), _(PACKAGE_NAME
));
2071 strError
= strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind
.ToString(), NetworkErrorString(nErr
));
2072 LogPrintf("%s\n", strError
);
2073 CloseSocket(hListenSocket
);
2076 LogPrintf("Bound to %s\n", addrBind
.ToString());
2078 // Listen for incoming connections
2079 if (listen(hListenSocket
, SOMAXCONN
) == SOCKET_ERROR
)
2081 strError
= strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2082 LogPrintf("%s\n", strError
);
2083 CloseSocket(hListenSocket
);
2087 vhListenSocket
.push_back(ListenSocket(hListenSocket
, fWhitelisted
));
2089 if (addrBind
.IsRoutable() && fDiscover
&& !fWhitelisted
)
2090 AddLocal(addrBind
, LOCAL_BIND
);
2095 void Discover(boost::thread_group
& threadGroup
)
2101 // Get local host IP
2102 char pszHostName
[256] = "";
2103 if (gethostname(pszHostName
, sizeof(pszHostName
)) != SOCKET_ERROR
)
2105 std::vector
<CNetAddr
> vaddr
;
2106 if (LookupHost(pszHostName
, vaddr
, 0, true))
2108 BOOST_FOREACH (const CNetAddr
&addr
, vaddr
)
2110 if (AddLocal(addr
, LOCAL_IF
))
2111 LogPrintf("%s: %s - %s\n", __func__
, pszHostName
, addr
.ToString());
2116 // Get local host ip
2117 struct ifaddrs
* myaddrs
;
2118 if (getifaddrs(&myaddrs
) == 0)
2120 for (struct ifaddrs
* ifa
= myaddrs
; ifa
!= NULL
; ifa
= ifa
->ifa_next
)
2122 if (ifa
->ifa_addr
== NULL
) continue;
2123 if ((ifa
->ifa_flags
& IFF_UP
) == 0) continue;
2124 if (strcmp(ifa
->ifa_name
, "lo") == 0) continue;
2125 if (strcmp(ifa
->ifa_name
, "lo0") == 0) continue;
2126 if (ifa
->ifa_addr
->sa_family
== AF_INET
)
2128 struct sockaddr_in
* s4
= (struct sockaddr_in
*)(ifa
->ifa_addr
);
2129 CNetAddr
addr(s4
->sin_addr
);
2130 if (AddLocal(addr
, LOCAL_IF
))
2131 LogPrintf("%s: IPv4 %s: %s\n", __func__
, ifa
->ifa_name
, addr
.ToString());
2133 else if (ifa
->ifa_addr
->sa_family
== AF_INET6
)
2135 struct sockaddr_in6
* s6
= (struct sockaddr_in6
*)(ifa
->ifa_addr
);
2136 CNetAddr
addr(s6
->sin6_addr
);
2137 if (AddLocal(addr
, LOCAL_IF
))
2138 LogPrintf("%s: IPv6 %s: %s\n", __func__
, ifa
->ifa_name
, addr
.ToString());
2141 freeifaddrs(myaddrs
);
2146 void CConnman::SetNetworkActive(bool active
)
2149 LogPrint("net", "SetNetworkActive: %s\n", active
);
2153 fNetworkActive
= false;
2156 // Close sockets to all nodes
2157 BOOST_FOREACH(CNode
* pnode
, vNodes
) {
2158 pnode
->CloseSocketDisconnect();
2161 fNetworkActive
= true;
2164 uiInterface
.NotifyNetworkActiveChanged(fNetworkActive
);
2167 CConnman::CConnman(uint64_t nSeed0In
, uint64_t nSeed1In
) : nSeed0(nSeed0In
), nSeed1(nSeed1In
)
2169 fNetworkActive
= true;
2170 setBannedIsDirty
= false;
2171 fAddressesInitialized
= false;
2173 nSendBufferMaxSize
= 0;
2174 nReceiveFloodSize
= 0;
2177 nMaxConnections
= 0;
2181 clientInterface
= NULL
;
2182 flagInterruptMsgProc
= false;
2185 NodeId
CConnman::GetNewNodeId()
2187 return nLastNodeId
.fetch_add(1, std::memory_order_relaxed
);
2190 bool CConnman::Start(CScheduler
& scheduler
, std::string
& strNodeError
, Options connOptions
)
2192 nTotalBytesRecv
= 0;
2193 nTotalBytesSent
= 0;
2194 nMaxOutboundTotalBytesSentInCycle
= 0;
2195 nMaxOutboundCycleStartTime
= 0;
2197 nRelevantServices
= connOptions
.nRelevantServices
;
2198 nLocalServices
= connOptions
.nLocalServices
;
2199 nMaxConnections
= connOptions
.nMaxConnections
;
2200 nMaxOutbound
= std::min((connOptions
.nMaxOutbound
), nMaxConnections
);
2201 nMaxAddnode
= connOptions
.nMaxAddnode
;
2202 nMaxFeeler
= connOptions
.nMaxFeeler
;
2204 nSendBufferMaxSize
= connOptions
.nSendBufferMaxSize
;
2205 nReceiveFloodSize
= connOptions
.nReceiveFloodSize
;
2207 nMaxOutboundLimit
= connOptions
.nMaxOutboundLimit
;
2208 nMaxOutboundTimeframe
= connOptions
.nMaxOutboundTimeframe
;
2210 SetBestHeight(connOptions
.nBestHeight
);
2212 clientInterface
= connOptions
.uiInterface
;
2213 if (clientInterface
)
2214 clientInterface
->InitMessage(_("Loading addresses..."));
2215 // Load addresses from peers.dat
2216 int64_t nStart
= GetTimeMillis();
2219 if (adb
.Read(addrman
))
2220 LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman
.size(), GetTimeMillis() - nStart
);
2222 addrman
.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2223 LogPrintf("Invalid or missing peers.dat; recreating\n");
2227 if (clientInterface
)
2228 clientInterface
->InitMessage(_("Loading banlist..."));
2229 // Load addresses from banlist.dat
2230 nStart
= GetTimeMillis();
2233 if (bandb
.Read(banmap
)) {
2234 SetBanned(banmap
); // thread save setter
2235 SetBannedSetDirty(false); // no need to write down, just read data
2236 SweepBanned(); // sweep out unused entries
2238 LogPrint("net", "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
2239 banmap
.size(), GetTimeMillis() - nStart
);
2241 LogPrintf("Invalid or missing banlist.dat; recreating\n");
2242 SetBannedSetDirty(true); // force write
2246 uiInterface
.InitMessage(_("Starting network threads..."));
2248 fAddressesInitialized
= true;
2250 if (semOutbound
== NULL
) {
2251 // initialize semaphore
2252 semOutbound
= new CSemaphore(std::min((nMaxOutbound
+ nMaxFeeler
), nMaxConnections
));
2254 if (semAddnode
== NULL
) {
2255 // initialize semaphore
2256 semAddnode
= new CSemaphore(nMaxAddnode
);
2262 InterruptSocks5(false);
2263 interruptNet
.reset();
2264 flagInterruptMsgProc
= false;
2267 std::unique_lock
<std::mutex
> lock(mutexMsgProc
);
2268 fMsgProcWake
= false;
2271 // Send and receive from sockets, accept connections
2272 threadSocketHandler
= std::thread(&TraceThread
<std::function
<void()> >, "net", std::function
<void()>(std::bind(&CConnman::ThreadSocketHandler
, this)));
2274 if (!GetBoolArg("-dnsseed", true))
2275 LogPrintf("DNS seeding disabled\n");
2277 threadDNSAddressSeed
= std::thread(&TraceThread
<std::function
<void()> >, "dnsseed", std::function
<void()>(std::bind(&CConnman::ThreadDNSAddressSeed
, this)));
2279 // Initiate outbound connections from -addnode
2280 threadOpenAddedConnections
= std::thread(&TraceThread
<std::function
<void()> >, "addcon", std::function
<void()>(std::bind(&CConnman::ThreadOpenAddedConnections
, this)));
2282 // Initiate outbound connections unless connect=0
2283 if (!mapMultiArgs
.count("-connect") || mapMultiArgs
.at("-connect").size() != 1 || mapMultiArgs
.at("-connect")[0] != "0")
2284 threadOpenConnections
= std::thread(&TraceThread
<std::function
<void()> >, "opencon", std::function
<void()>(std::bind(&CConnman::ThreadOpenConnections
, this)));
2287 threadMessageHandler
= std::thread(&TraceThread
<std::function
<void()> >, "msghand", std::function
<void()>(std::bind(&CConnman::ThreadMessageHandler
, this)));
2289 // Dump network addresses
2290 scheduler
.scheduleEvery(boost::bind(&CConnman::DumpData
, this), DUMP_ADDRESSES_INTERVAL
);
2303 // Shutdown Windows Sockets
2308 instance_of_cnetcleanup
;
2310 void CConnman::Interrupt()
2313 std::lock_guard
<std::mutex
> lock(mutexMsgProc
);
2314 flagInterruptMsgProc
= true;
2316 condMsgProc
.notify_all();
2319 InterruptSocks5(true);
2322 for (int i
=0; i
<(nMaxOutbound
+ nMaxFeeler
); i
++)
2323 semOutbound
->post();
2326 void CConnman::Stop()
2328 if (threadMessageHandler
.joinable())
2329 threadMessageHandler
.join();
2330 if (threadOpenConnections
.joinable())
2331 threadOpenConnections
.join();
2332 if (threadOpenAddedConnections
.joinable())
2333 threadOpenAddedConnections
.join();
2334 if (threadDNSAddressSeed
.joinable())
2335 threadDNSAddressSeed
.join();
2336 if (threadSocketHandler
.joinable())
2337 threadSocketHandler
.join();
2340 for (int i
=0; i
<nMaxAddnode
; i
++)
2341 semOutbound
->post();
2343 if (fAddressesInitialized
)
2346 fAddressesInitialized
= false;
2350 BOOST_FOREACH(CNode
* pnode
, vNodes
)
2351 pnode
->CloseSocketDisconnect();
2352 BOOST_FOREACH(ListenSocket
& hListenSocket
, vhListenSocket
)
2353 if (hListenSocket
.socket
!= INVALID_SOCKET
)
2354 if (!CloseSocket(hListenSocket
.socket
))
2355 LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2357 // clean up some globals (to help leak detection)
2358 BOOST_FOREACH(CNode
*pnode
, vNodes
) {
2361 BOOST_FOREACH(CNode
*pnode
, vNodesDisconnected
) {
2365 vNodesDisconnected
.clear();
2366 vhListenSocket
.clear();
2373 void CConnman::DeleteNode(CNode
* pnode
)
2376 bool fUpdateConnectionTime
= false;
2377 GetNodeSignals().FinalizeNode(pnode
->GetId(), fUpdateConnectionTime
);
2378 if(fUpdateConnectionTime
)
2379 addrman
.Connected(pnode
->addr
);
2383 CConnman::~CConnman()
2389 size_t CConnman::GetAddressCount() const
2391 return addrman
.size();
2394 void CConnman::SetServices(const CService
&addr
, ServiceFlags nServices
)
2396 addrman
.SetServices(addr
, nServices
);
2399 void CConnman::MarkAddressGood(const CAddress
& addr
)
2404 void CConnman::AddNewAddress(const CAddress
& addr
, const CAddress
& addrFrom
, int64_t nTimePenalty
)
2406 addrman
.Add(addr
, addrFrom
, nTimePenalty
);
2409 void CConnman::AddNewAddresses(const std::vector
<CAddress
>& vAddr
, const CAddress
& addrFrom
, int64_t nTimePenalty
)
2411 addrman
.Add(vAddr
, addrFrom
, nTimePenalty
);
2414 std::vector
<CAddress
> CConnman::GetAddresses()
2416 return addrman
.GetAddr();
2419 bool CConnman::AddNode(const std::string
& strNode
)
2421 LOCK(cs_vAddedNodes
);
2422 for(std::vector
<std::string
>::const_iterator it
= vAddedNodes
.begin(); it
!= vAddedNodes
.end(); ++it
) {
2427 vAddedNodes
.push_back(strNode
);
2431 bool CConnman::RemoveAddedNode(const std::string
& strNode
)
2433 LOCK(cs_vAddedNodes
);
2434 for(std::vector
<std::string
>::iterator it
= vAddedNodes
.begin(); it
!= vAddedNodes
.end(); ++it
) {
2435 if (strNode
== *it
) {
2436 vAddedNodes
.erase(it
);
2443 size_t CConnman::GetNodeCount(NumConnections flags
)
2446 if (flags
== CConnman::CONNECTIONS_ALL
) // Shortcut if we want total
2447 return vNodes
.size();
2450 for(std::vector
<CNode
*>::const_iterator it
= vNodes
.begin(); it
!= vNodes
.end(); ++it
)
2451 if (flags
& ((*it
)->fInbound
? CONNECTIONS_IN
: CONNECTIONS_OUT
))
2457 void CConnman::GetNodeStats(std::vector
<CNodeStats
>& vstats
)
2461 vstats
.reserve(vNodes
.size());
2462 for(std::vector
<CNode
*>::iterator it
= vNodes
.begin(); it
!= vNodes
.end(); ++it
) {
2464 vstats
.emplace_back();
2465 pnode
->copyStats(vstats
.back());
2469 bool CConnman::DisconnectNode(const std::string
& strNode
)
2472 if (CNode
* pnode
= FindNode(strNode
)) {
2473 pnode
->fDisconnect
= true;
2478 bool CConnman::DisconnectNode(NodeId id
)
2481 for(CNode
* pnode
: vNodes
) {
2482 if (id
== pnode
->id
) {
2483 pnode
->fDisconnect
= true;
2490 void CConnman::RecordBytesRecv(uint64_t bytes
)
2492 LOCK(cs_totalBytesRecv
);
2493 nTotalBytesRecv
+= bytes
;
2496 void CConnman::RecordBytesSent(uint64_t bytes
)
2498 LOCK(cs_totalBytesSent
);
2499 nTotalBytesSent
+= bytes
;
2501 uint64_t now
= GetTime();
2502 if (nMaxOutboundCycleStartTime
+ nMaxOutboundTimeframe
< now
)
2504 // timeframe expired, reset cycle
2505 nMaxOutboundCycleStartTime
= now
;
2506 nMaxOutboundTotalBytesSentInCycle
= 0;
2509 // TODO, exclude whitebind peers
2510 nMaxOutboundTotalBytesSentInCycle
+= bytes
;
2513 void CConnman::SetMaxOutboundTarget(uint64_t limit
)
2515 LOCK(cs_totalBytesSent
);
2516 nMaxOutboundLimit
= limit
;
2519 uint64_t CConnman::GetMaxOutboundTarget()
2521 LOCK(cs_totalBytesSent
);
2522 return nMaxOutboundLimit
;
2525 uint64_t CConnman::GetMaxOutboundTimeframe()
2527 LOCK(cs_totalBytesSent
);
2528 return nMaxOutboundTimeframe
;
2531 uint64_t CConnman::GetMaxOutboundTimeLeftInCycle()
2533 LOCK(cs_totalBytesSent
);
2534 if (nMaxOutboundLimit
== 0)
2537 if (nMaxOutboundCycleStartTime
== 0)
2538 return nMaxOutboundTimeframe
;
2540 uint64_t cycleEndTime
= nMaxOutboundCycleStartTime
+ nMaxOutboundTimeframe
;
2541 uint64_t now
= GetTime();
2542 return (cycleEndTime
< now
) ? 0 : cycleEndTime
- GetTime();
2545 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe
)
2547 LOCK(cs_totalBytesSent
);
2548 if (nMaxOutboundTimeframe
!= timeframe
)
2550 // reset measure-cycle in case of changing
2552 nMaxOutboundCycleStartTime
= GetTime();
2554 nMaxOutboundTimeframe
= timeframe
;
2557 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit
)
2559 LOCK(cs_totalBytesSent
);
2560 if (nMaxOutboundLimit
== 0)
2563 if (historicalBlockServingLimit
)
2565 // keep a large enough buffer to at least relay each block once
2566 uint64_t timeLeftInCycle
= GetMaxOutboundTimeLeftInCycle();
2567 uint64_t buffer
= timeLeftInCycle
/ 600 * MAX_BLOCK_SERIALIZED_SIZE
;
2568 if (buffer
>= nMaxOutboundLimit
|| nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
- buffer
)
2571 else if (nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
)
2577 uint64_t CConnman::GetOutboundTargetBytesLeft()
2579 LOCK(cs_totalBytesSent
);
2580 if (nMaxOutboundLimit
== 0)
2583 return (nMaxOutboundTotalBytesSentInCycle
>= nMaxOutboundLimit
) ? 0 : nMaxOutboundLimit
- nMaxOutboundTotalBytesSentInCycle
;
2586 uint64_t CConnman::GetTotalBytesRecv()
2588 LOCK(cs_totalBytesRecv
);
2589 return nTotalBytesRecv
;
2592 uint64_t CConnman::GetTotalBytesSent()
2594 LOCK(cs_totalBytesSent
);
2595 return nTotalBytesSent
;
2598 ServiceFlags
CConnman::GetLocalServices() const
2600 return nLocalServices
;
2603 void CConnman::SetBestHeight(int height
)
2605 nBestHeight
.store(height
, std::memory_order_release
);
2608 int CConnman::GetBestHeight() const
2610 return nBestHeight
.load(std::memory_order_acquire
);
2613 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize
; }
2614 unsigned int CConnman::GetSendBufferSize() const{ return nSendBufferMaxSize
; }
2616 CNode::CNode(NodeId idIn
, ServiceFlags nLocalServicesIn
, int nMyStartingHeightIn
, SOCKET hSocketIn
, const CAddress
& addrIn
, uint64_t nKeyedNetGroupIn
, uint64_t nLocalHostNonceIn
, const std::string
& addrNameIn
, bool fInboundIn
) :
2617 nTimeConnected(GetSystemTimeInSeconds()),
2619 fInbound(fInboundIn
),
2621 nKeyedNetGroup(nKeyedNetGroupIn
),
2622 addrKnown(5000, 0.001),
2623 filterInventoryKnown(50000, 0.000001),
2624 nLocalHostNonce(nLocalHostNonceIn
),
2625 nLocalServices(nLocalServicesIn
),
2626 nMyStartingHeight(nMyStartingHeightIn
),
2629 nServices
= NODE_NONE
;
2630 nServicesExpected
= NODE_NONE
;
2631 hSocket
= hSocketIn
;
2632 nRecvVersion
= INIT_PROTO_VERSION
;
2638 addrName
= addrNameIn
== "" ? addr
.ToStringIPPort() : addrNameIn
;
2641 fWhitelisted
= false;
2644 fClient
= false; // set by version message
2646 fSuccessfullyConnected
= false;
2647 fDisconnect
= false;
2651 hashContinue
= uint256();
2652 nStartingHeight
= -1;
2653 filterInventoryKnown
.reset();
2654 fSendMempool
= false;
2656 nNextLocalAddrSend
= 0;
2661 pfilter
= new CBloomFilter();
2662 timeLastMempoolReq
= 0;
2668 fPingQueued
= false;
2669 nMinPingUsecTime
= std::numeric_limits
<int64_t>::max();
2671 lastSentFeeFilter
= 0;
2672 nextSendTimeFeeFilter
= 0;
2675 nProcessQueueSize
= 0;
2677 BOOST_FOREACH(const std::string
&msg
, getAllNetMessageTypes())
2678 mapRecvBytesPerMsgCmd
[msg
] = 0;
2679 mapRecvBytesPerMsgCmd
[NET_MESSAGE_COMMAND_OTHER
] = 0;
2682 LogPrint("net", "Added connection to %s peer=%d\n", addrName
, id
);
2684 LogPrint("net", "Added connection peer=%d\n", id
);
2689 CloseSocket(hSocket
);
2695 void CNode::AskFor(const CInv
& inv
)
2697 if (mapAskFor
.size() > MAPASKFOR_MAX_SZ
|| setAskFor
.size() > SETASKFOR_MAX_SZ
)
2699 // a peer may not have multiple non-responded queue positions for a single inv item
2700 if (!setAskFor
.insert(inv
.hash
).second
)
2703 // We're using mapAskFor as a priority queue,
2704 // the key is the earliest time the request can be sent
2705 int64_t nRequestTime
;
2706 limitedmap
<uint256
, int64_t>::const_iterator it
= mapAlreadyAskedFor
.find(inv
.hash
);
2707 if (it
!= mapAlreadyAskedFor
.end())
2708 nRequestTime
= it
->second
;
2711 LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv
.ToString(), nRequestTime
, DateTimeStrFormat("%H:%M:%S", nRequestTime
/1000000), id
);
2713 // Make sure not to reuse time indexes to keep things in the same order
2714 int64_t nNow
= GetTimeMicros() - 1000000;
2715 static int64_t nLastTime
;
2717 nNow
= std::max(nNow
, nLastTime
);
2720 // Each retry is 2 minutes after the last
2721 nRequestTime
= std::max(nRequestTime
+ 2 * 60 * 1000000, nNow
);
2722 if (it
!= mapAlreadyAskedFor
.end())
2723 mapAlreadyAskedFor
.update(it
, nRequestTime
);
2725 mapAlreadyAskedFor
.insert(std::make_pair(inv
.hash
, nRequestTime
));
2726 mapAskFor
.insert(std::make_pair(nRequestTime
, inv
));
2729 bool CConnman::NodeFullyConnected(const CNode
* pnode
)
2731 return pnode
&& pnode
->fSuccessfullyConnected
&& !pnode
->fDisconnect
;
2734 void CConnman::PushMessage(CNode
* pnode
, CSerializedNetMsg
&& msg
)
2736 size_t nMessageSize
= msg
.data
.size();
2737 size_t nTotalSize
= nMessageSize
+ CMessageHeader::HEADER_SIZE
;
2738 LogPrint("net", "sending %s (%d bytes) peer=%d\n", SanitizeString(msg
.command
.c_str()), nMessageSize
, pnode
->id
);
2740 std::vector
<unsigned char> serializedHeader
;
2741 serializedHeader
.reserve(CMessageHeader::HEADER_SIZE
);
2742 uint256 hash
= Hash(msg
.data
.data(), msg
.data
.data() + nMessageSize
);
2743 CMessageHeader
hdr(Params().MessageStart(), msg
.command
.c_str(), nMessageSize
);
2744 memcpy(hdr
.pchChecksum
, hash
.begin(), CMessageHeader::CHECKSUM_SIZE
);
2746 CVectorWriter
{SER_NETWORK
, INIT_PROTO_VERSION
, serializedHeader
, 0, hdr
};
2748 size_t nBytesSent
= 0;
2750 LOCK(pnode
->cs_vSend
);
2751 bool optimisticSend(pnode
->vSendMsg
.empty());
2753 //log total amount of bytes per command
2754 pnode
->mapSendBytesPerMsgCmd
[msg
.command
] += nTotalSize
;
2755 pnode
->nSendSize
+= nTotalSize
;
2757 if (pnode
->nSendSize
> nSendBufferMaxSize
)
2758 pnode
->fPauseSend
= true;
2759 pnode
->vSendMsg
.push_back(std::move(serializedHeader
));
2761 pnode
->vSendMsg
.push_back(std::move(msg
.data
));
2763 // If write queue empty, attempt "optimistic write"
2764 if (optimisticSend
== true)
2765 nBytesSent
= SocketSendData(pnode
);
2768 RecordBytesSent(nBytesSent
);
2771 bool CConnman::ForNode(NodeId id
, std::function
<bool(CNode
* pnode
)> func
)
2773 CNode
* found
= nullptr;
2775 for (auto&& pnode
: vNodes
) {
2776 if(pnode
->id
== id
) {
2781 return found
!= nullptr && NodeFullyConnected(found
) && func(found
);
2784 int64_t PoissonNextSend(int64_t nNow
, int average_interval_seconds
) {
2785 return nNow
+ (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds
* -1000000.0 + 0.5);
2788 CSipHasher
CConnman::GetDeterministicRandomizer(uint64_t id
) const
2790 return CSipHasher(nSeed0
, nSeed1
).Write(id
);
2793 uint64_t CConnman::CalculateKeyedNetGroup(const CAddress
& ad
) const
2795 std::vector
<unsigned char> vchNetGroup(ad
.GetGroup());
2797 return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP
).Write(&vchNetGroup
[0], vchNetGroup
.size()).Finalize();