1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 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"
14 #include "chainparams.h"
15 #include "clientversion.h"
16 #include "primitives/transaction.h"
17 #include "scheduler.h"
18 #include "ui_interface.h"
19 #include "crypto/common.h"
27 #include <boost/filesystem.hpp>
28 #include <boost/thread.hpp>
30 // Dump addresses to peers.dat every 15 minutes (900s)
31 #define DUMP_ADDRESSES_INTERVAL 900
33 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
34 #define MSG_NOSIGNAL 0
37 // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
38 // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
40 #ifndef PROTECTION_LEVEL_UNRESTRICTED
41 #define PROTECTION_LEVEL_UNRESTRICTED 10
43 #ifndef IPV6_PROTECTION_LEVEL
44 #define IPV6_PROTECTION_LEVEL 23
51 const int MAX_OUTBOUND_CONNECTIONS = 8;
57 ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
62 // Global state variables
64 bool fDiscover = true;
66 uint64_t nLocalServices = NODE_NETWORK;
67 CCriticalSection cs_mapLocalHost;
68 map<CNetAddr, LocalServiceInfo> mapLocalHost;
69 static bool vfLimited[NET_MAX] = {};
70 static CNode* pnodeLocalHost = NULL;
71 uint64_t nLocalHostNonce = 0;
72 static std::vector<ListenSocket> vhListenSocket;
74 int nMaxConnections = DEFAULT_MAX_PEER_CONNECTIONS;
75 bool fAddressesInitialized = false;
76 std::string strSubVersion;
78 vector<CNode*> vNodes;
79 CCriticalSection cs_vNodes;
80 map<CInv, CDataStream> mapRelay;
81 deque<pair<int64_t, CInv> > vRelayExpiration;
82 CCriticalSection cs_mapRelay;
83 limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
85 static deque<string> vOneShots;
86 static CCriticalSection cs_vOneShots;
88 static set<CNetAddr> setservAddNodeAddresses;
89 static CCriticalSection cs_setservAddNodeAddresses;
91 vector<std::string> vAddedNodes;
92 CCriticalSection cs_vAddedNodes;
94 NodeId nLastNodeId = 0;
95 CCriticalSection cs_nLastNodeId;
97 static CSemaphore *semOutbound = NULL;
98 static boost::condition_variable messageHandlerCondition;
100 // Signals for message handling
101 static CNodeSignals g_signals;
102 CNodeSignals& GetNodeSignals() { return g_signals; }
104 void AddOneShot(const std::string& strDest)
107 vOneShots.push_back(strDest);
110 unsigned short GetListenPort()
112 return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
115 // find 'best' local address for a particular peer
116 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
122 int nBestReachability = -1;
124 LOCK(cs_mapLocalHost);
125 for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
127 int nScore = (*it).second.nScore;
128 int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
129 if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
131 addr = CService((*it).first, (*it).second.nPort);
132 nBestReachability = nReachability;
137 return nBestScore >= 0;
140 //! Convert the pnSeeds6 array into usable address objects.
141 static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn)
143 // It'll only connect to one or two seed nodes because once it connects,
144 // it'll get a pile of addresses with newer timestamps.
145 // Seed nodes are given a random 'last seen time' of between one and two
147 const int64_t nOneWeek = 7*24*60*60;
148 std::vector<CAddress> vSeedsOut;
149 vSeedsOut.reserve(vSeedsIn.size());
150 for (std::vector<SeedSpec6>::const_iterator i(vSeedsIn.begin()); i != vSeedsIn.end(); ++i)
153 memcpy(&ip, i->addr, sizeof(ip));
154 CAddress addr(CService(ip, i->port));
155 addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
156 vSeedsOut.push_back(addr);
161 // get best local address for a particular peer as a CAddress
162 // Otherwise, return the unroutable 0.0.0.0 but filled in with
163 // the normal parameters, since the IP may be changed to a useful
165 CAddress GetLocalAddress(const CNetAddr *paddrPeer)
167 CAddress ret(CService("0.0.0.0",GetListenPort()),0);
169 if (GetLocal(addr, paddrPeer))
171 ret = CAddress(addr);
173 ret.nServices = nLocalServices;
174 ret.nTime = GetAdjustedTime();
178 int GetnScore(const CService& addr)
180 LOCK(cs_mapLocalHost);
181 if (mapLocalHost.count(addr) == LOCAL_NONE)
183 return mapLocalHost[addr].nScore;
186 // Is our peer's addrLocal potentially useful as an external IP source?
187 bool IsPeerAddrLocalGood(CNode *pnode)
189 return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() &&
190 !IsLimited(pnode->addrLocal.GetNetwork());
193 // pushes our own address to a peer
194 void AdvertizeLocal(CNode *pnode)
196 if (fListen && pnode->fSuccessfullyConnected)
198 CAddress addrLocal = GetLocalAddress(&pnode->addr);
199 // If discovery is enabled, sometimes give our peer the address it
200 // tells us that it sees us as in case it has a better idea of our
201 // address than we do.
202 if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
203 GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0))
205 addrLocal.SetIP(pnode->addrLocal);
207 if (addrLocal.IsRoutable())
209 LogPrintf("AdvertizeLocal: advertizing address %s\n", addrLocal.ToString());
210 pnode->PushAddress(addrLocal);
215 // learn a new local address
216 bool AddLocal(const CService& addr, int nScore)
218 if (!addr.IsRoutable())
221 if (!fDiscover && nScore < LOCAL_MANUAL)
227 LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
230 LOCK(cs_mapLocalHost);
231 bool fAlready = mapLocalHost.count(addr) > 0;
232 LocalServiceInfo &info = mapLocalHost[addr];
233 if (!fAlready || nScore >= info.nScore) {
234 info.nScore = nScore + (fAlready ? 1 : 0);
235 info.nPort = addr.GetPort();
242 bool AddLocal(const CNetAddr &addr, int nScore)
244 return AddLocal(CService(addr, GetListenPort()), nScore);
247 bool RemoveLocal(const CService& addr)
249 LOCK(cs_mapLocalHost);
250 LogPrintf("RemoveLocal(%s)\n", addr.ToString());
251 mapLocalHost.erase(addr);
255 /** Make a particular network entirely off-limits (no automatic connects to it) */
256 void SetLimited(enum Network net, bool fLimited)
258 if (net == NET_UNROUTABLE)
260 LOCK(cs_mapLocalHost);
261 vfLimited[net] = fLimited;
264 bool IsLimited(enum Network net)
266 LOCK(cs_mapLocalHost);
267 return vfLimited[net];
270 bool IsLimited(const CNetAddr &addr)
272 return IsLimited(addr.GetNetwork());
275 /** vote for a local address */
276 bool SeenLocal(const CService& addr)
279 LOCK(cs_mapLocalHost);
280 if (mapLocalHost.count(addr) == 0)
282 mapLocalHost[addr].nScore++;
288 /** check whether a given address is potentially local */
289 bool IsLocal(const CService& addr)
291 LOCK(cs_mapLocalHost);
292 return mapLocalHost.count(addr) > 0;
295 /** check whether a given network is one we can probably connect to */
296 bool IsReachable(enum Network net)
298 LOCK(cs_mapLocalHost);
299 return !vfLimited[net];
302 /** check whether a given address is in a network we can probably connect to */
303 bool IsReachable(const CNetAddr& addr)
305 enum Network net = addr.GetNetwork();
306 return IsReachable(net);
309 void AddressCurrentlyConnected(const CService& addr)
311 addrman.Connected(addr);
315 uint64_t CNode::nTotalBytesRecv = 0;
316 uint64_t CNode::nTotalBytesSent = 0;
317 CCriticalSection CNode::cs_totalBytesRecv;
318 CCriticalSection CNode::cs_totalBytesSent;
320 CNode* FindNode(const CNetAddr& ip)
323 BOOST_FOREACH(CNode* pnode, vNodes)
324 if ((CNetAddr)pnode->addr == ip)
329 CNode* FindNode(const CSubNet& subNet)
332 BOOST_FOREACH(CNode* pnode, vNodes)
333 if (subNet.Match((CNetAddr)pnode->addr))
338 CNode* FindNode(const std::string& addrName)
341 BOOST_FOREACH(CNode* pnode, vNodes)
342 if (pnode->addrName == addrName)
347 CNode* FindNode(const CService& addr)
350 BOOST_FOREACH(CNode* pnode, vNodes)
351 if ((CService)pnode->addr == addr)
356 CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
358 if (pszDest == NULL) {
359 if (IsLocal(addrConnect))
362 // Look for an existing connection
363 CNode* pnode = FindNode((CService)addrConnect);
372 LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
373 pszDest ? pszDest : addrConnect.ToString(),
374 pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
378 bool proxyConnectionFailed = false;
379 if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
380 ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed))
382 if (!IsSelectableSocket(hSocket)) {
383 LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
384 CloseSocket(hSocket);
388 addrman.Attempt(addrConnect);
391 CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
396 vNodes.push_back(pnode);
399 pnode->nTimeConnected = GetTime();
402 } else if (!proxyConnectionFailed) {
403 // If connecting to the node failed, and failure is not caused by a problem connecting to
404 // the proxy, mark this as an attempt.
405 addrman.Attempt(addrConnect);
411 void CNode::CloseSocketDisconnect()
414 if (hSocket != INVALID_SOCKET)
416 LogPrint("net", "disconnecting peer=%d\n", id);
417 CloseSocket(hSocket);
420 // in case this fails, we'll empty the recv buffer when the CNode is deleted
421 TRY_LOCK(cs_vRecvMsg, lockRecv);
426 void CNode::PushVersion()
428 int nBestHeight = g_signals.GetHeight().get_value_or(0);
430 int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
431 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
432 CAddress addrMe = GetLocalAddress(&addr);
433 GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
435 LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
437 LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
438 PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
439 nLocalHostNonce, strSubVersion, nBestHeight, true);
446 std::map<CSubNet, int64_t> CNode::setBanned;
447 CCriticalSection CNode::cs_setBanned;
449 void CNode::ClearBanned()
455 bool CNode::IsBanned(CNetAddr ip)
457 bool fResult = false;
460 for (std::map<CSubNet, int64_t>::iterator it = setBanned.begin(); it != setBanned.end(); it++)
462 CSubNet subNet = (*it).first;
463 int64_t t = (*it).second;
465 if(subNet.Match(ip) && GetTime() < t)
472 bool CNode::IsBanned(CSubNet subnet)
474 bool fResult = false;
477 std::map<CSubNet, int64_t>::iterator i = setBanned.find(subnet);
478 if (i != setBanned.end())
480 int64_t t = (*i).second;
488 void CNode::Ban(const CNetAddr& addr, int64_t bantimeoffset, bool sinceUnixEpoch) {
489 CSubNet subNet(addr.ToString()+(addr.IsIPv4() ? "/32" : "/128"));
490 Ban(subNet, bantimeoffset, sinceUnixEpoch);
493 void CNode::Ban(const CSubNet& subNet, int64_t bantimeoffset, bool sinceUnixEpoch) {
494 int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
495 if (bantimeoffset > 0)
496 banTime = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
499 if (setBanned[subNet] < banTime)
500 setBanned[subNet] = banTime;
503 bool CNode::Unban(const CNetAddr &addr) {
504 CSubNet subNet(addr.ToString()+(addr.IsIPv4() ? "/32" : "/128"));
505 return Unban(subNet);
508 bool CNode::Unban(const CSubNet &subNet) {
510 if (setBanned.erase(subNet))
515 void CNode::GetBanned(std::map<CSubNet, int64_t> &banMap)
518 banMap = setBanned; //create a thread safe copy
522 std::vector<CSubNet> CNode::vWhitelistedRange;
523 CCriticalSection CNode::cs_vWhitelistedRange;
525 bool CNode::IsWhitelistedRange(const CNetAddr &addr) {
526 LOCK(cs_vWhitelistedRange);
527 BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) {
528 if (subnet.Match(addr))
534 void CNode::AddWhitelistedRange(const CSubNet &subnet) {
535 LOCK(cs_vWhitelistedRange);
536 vWhitelistedRange.push_back(subnet);
539 void CNode::copyStats(CNodeStats &stats)
541 stats.nodeid = this->GetId();
542 stats.nServices = nServices;
543 stats.nLastSend = nLastSend;
544 stats.nLastRecv = nLastRecv;
545 stats.nTimeConnected = nTimeConnected;
546 stats.nTimeOffset = nTimeOffset;
547 stats.addrName = addrName;
548 stats.nVersion = nVersion;
549 stats.cleanSubVer = cleanSubVer;
550 stats.fInbound = fInbound;
551 stats.nStartingHeight = nStartingHeight;
552 stats.nSendBytes = nSendBytes;
553 stats.nRecvBytes = nRecvBytes;
554 stats.fWhitelisted = fWhitelisted;
556 // It is common for nodes with good ping times to suddenly become lagged,
557 // due to a new block arriving or other large transfer.
558 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
559 // since pingtime does not update until the ping is complete, which might take a while.
560 // So, if a ping is taking an unusually long time in flight,
561 // the caller can immediately detect that this is happening.
562 int64_t nPingUsecWait = 0;
563 if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
564 nPingUsecWait = GetTimeMicros() - nPingUsecStart;
567 // 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 :)
568 stats.dPingTime = (((double)nPingUsecTime) / 1e6);
569 stats.dPingWait = (((double)nPingUsecWait) / 1e6);
571 // Leave string empty if addrLocal invalid (not filled in yet)
572 stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
575 // requires LOCK(cs_vRecvMsg)
576 bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
580 // get current incomplete message, or create a new one
581 if (vRecvMsg.empty() ||
582 vRecvMsg.back().complete())
583 vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, nRecvVersion));
585 CNetMessage& msg = vRecvMsg.back();
587 // absorb network data
590 handled = msg.readHeader(pch, nBytes);
592 handled = msg.readData(pch, nBytes);
597 if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
598 LogPrint("net", "Oversized message from peer=%i, disconnecting\n", GetId());
605 if (msg.complete()) {
606 msg.nTime = GetTimeMicros();
607 messageHandlerCondition.notify_one();
614 int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
616 // copy data to temporary parsing buffer
617 unsigned int nRemaining = 24 - nHdrPos;
618 unsigned int nCopy = std::min(nRemaining, nBytes);
620 memcpy(&hdrbuf[nHdrPos], pch, nCopy);
623 // if header incomplete, exit
627 // deserialize to CMessageHeader
631 catch (const std::exception&) {
635 // reject messages larger than MAX_SIZE
636 if (hdr.nMessageSize > MAX_SIZE)
639 // switch state to reading message data
645 int CNetMessage::readData(const char *pch, unsigned int nBytes)
647 unsigned int nRemaining = hdr.nMessageSize - nDataPos;
648 unsigned int nCopy = std::min(nRemaining, nBytes);
650 if (vRecv.size() < nDataPos + nCopy) {
651 // Allocate up to 256 KiB ahead, but never more than the total message size.
652 vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
655 memcpy(&vRecv[nDataPos], pch, nCopy);
669 // requires LOCK(cs_vSend)
670 void SocketSendData(CNode *pnode)
672 std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
674 while (it != pnode->vSendMsg.end()) {
675 const CSerializeData &data = *it;
676 assert(data.size() > pnode->nSendOffset);
677 int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
679 pnode->nLastSend = GetTime();
680 pnode->nSendBytes += nBytes;
681 pnode->nSendOffset += nBytes;
682 pnode->RecordBytesSent(nBytes);
683 if (pnode->nSendOffset == data.size()) {
684 pnode->nSendOffset = 0;
685 pnode->nSendSize -= data.size();
688 // could not send full message; stop sending more
694 int nErr = WSAGetLastError();
695 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
697 LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
698 pnode->CloseSocketDisconnect();
701 // couldn't send anything at all
706 if (it == pnode->vSendMsg.end()) {
707 assert(pnode->nSendOffset == 0);
708 assert(pnode->nSendSize == 0);
710 pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
713 static list<CNode*> vNodesDisconnected;
717 CNodeRef(CNode *pnode) : _pnode(pnode) {
727 CNode& operator *() const {return *_pnode;};
728 CNode* operator ->() const {return _pnode;};
730 CNodeRef& operator =(const CNodeRef& other)
732 if (this != &other) {
736 _pnode = other._pnode;
742 CNodeRef(const CNodeRef& other):
752 static bool ReverseCompareNodeMinPingTime(const CNodeRef &a, const CNodeRef &b)
754 return a->nMinPingUsecTime > b->nMinPingUsecTime;
757 static bool ReverseCompareNodeTimeConnected(const CNodeRef &a, const CNodeRef &b)
759 return a->nTimeConnected > b->nTimeConnected;
762 class CompareNetGroupKeyed
764 std::vector<unsigned char> vchSecretKey;
766 CompareNetGroupKeyed()
768 vchSecretKey.resize(32, 0);
769 GetRandBytes(vchSecretKey.data(), vchSecretKey.size());
772 bool operator()(const CNodeRef &a, const CNodeRef &b)
774 std::vector<unsigned char> vchGroupA, vchGroupB;
775 CSHA256 hashA, hashB;
776 std::vector<unsigned char> vchA(32), vchB(32);
778 vchGroupA = a->addr.GetGroup();
779 vchGroupB = b->addr.GetGroup();
781 hashA.Write(begin_ptr(vchGroupA), vchGroupA.size());
782 hashB.Write(begin_ptr(vchGroupB), vchGroupB.size());
784 hashA.Write(begin_ptr(vchSecretKey), vchSecretKey.size());
785 hashB.Write(begin_ptr(vchSecretKey), vchSecretKey.size());
787 hashA.Finalize(begin_ptr(vchA));
788 hashB.Finalize(begin_ptr(vchB));
794 static bool AttemptToEvictConnection(bool fPreferNewConnection) {
795 std::vector<CNodeRef> vEvictionCandidates;
799 BOOST_FOREACH(CNode *node, vNodes) {
800 if (node->fWhitelisted)
804 if (node->fDisconnect)
806 vEvictionCandidates.push_back(CNodeRef(node));
810 if (vEvictionCandidates.empty()) return false;
812 // Protect connections with certain characteristics
814 // Check version of eviction candidates and prioritize nodes which do not support network upgrade.
815 std::vector<CNodeRef> vTmpEvictionCandidates;
819 height = chainActive.Height();
822 const Consensus::Params& params = Params().GetConsensus();
823 auto nextEpoch = NextEpoch(height, params);
825 auto idx = nextEpoch.get();
826 int nActivationHeight = params.vUpgrades[idx].nActivationHeight;
828 if (nActivationHeight > 0 &&
829 height < nActivationHeight &&
830 height >= nActivationHeight - NETWORK_UPGRADE_PEER_PREFERENCE_BLOCK_PERIOD)
832 // Find any nodes which don't support the protocol version for the next upgrade
833 for (const CNodeRef &node : vEvictionCandidates) {
834 if (node->nVersion < params.vUpgrades[idx].nProtocolVersion) {
835 vTmpEvictionCandidates.push_back(node);
839 // Prioritize these nodes by replacing eviction set with them
840 if (vTmpEvictionCandidates.size() > 0) {
841 vEvictionCandidates = vTmpEvictionCandidates;
846 // Deterministically select 4 peers to protect by netgroup.
847 // An attacker cannot predict which netgroups will be protected.
848 static CompareNetGroupKeyed comparerNetGroupKeyed;
849 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), comparerNetGroupKeyed);
850 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
852 if (vEvictionCandidates.empty()) return false;
854 // Protect the 8 nodes with the best ping times.
855 // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
856 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime);
857 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
859 if (vEvictionCandidates.empty()) return false;
861 // Protect the half of the remaining nodes which have been connected the longest.
862 // This replicates the existing implicit behavior.
863 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected);
864 vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end());
866 if (vEvictionCandidates.empty()) return false;
868 // Identify the network group with the most connections and youngest member.
869 // (vEvictionCandidates is already sorted by reverse connect time)
870 std::vector<unsigned char> naMostConnections;
871 unsigned int nMostConnections = 0;
872 int64_t nMostConnectionsTime = 0;
873 std::map<std::vector<unsigned char>, std::vector<CNodeRef> > mapAddrCounts;
874 BOOST_FOREACH(const CNodeRef &node, vEvictionCandidates) {
875 mapAddrCounts[node->addr.GetGroup()].push_back(node);
876 int64_t grouptime = mapAddrCounts[node->addr.GetGroup()][0]->nTimeConnected;
877 size_t groupsize = mapAddrCounts[node->addr.GetGroup()].size();
879 if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) {
880 nMostConnections = groupsize;
881 nMostConnectionsTime = grouptime;
882 naMostConnections = node->addr.GetGroup();
886 // Reduce to the network group with the most connections
887 vEvictionCandidates = mapAddrCounts[naMostConnections];
889 // Do not disconnect peers if there is only one unprotected connection from their network group.
890 if (vEvictionCandidates.size() <= 1)
891 // unless we prefer the new connection (for whitelisted peers)
892 if (!fPreferNewConnection)
895 // Disconnect from the network group with the most connections
896 vEvictionCandidates[0]->fDisconnect = true;
901 static void AcceptConnection(const ListenSocket& hListenSocket) {
902 struct sockaddr_storage sockaddr;
903 socklen_t len = sizeof(sockaddr);
904 SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
907 int nMaxInbound = nMaxConnections - MAX_OUTBOUND_CONNECTIONS;
909 if (hSocket != INVALID_SOCKET)
910 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
911 LogPrintf("Warning: Unknown socket family\n");
913 bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
916 BOOST_FOREACH(CNode* pnode, vNodes)
921 if (hSocket == INVALID_SOCKET)
923 int nErr = WSAGetLastError();
924 if (nErr != WSAEWOULDBLOCK)
925 LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
929 if (!IsSelectableSocket(hSocket))
931 LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
932 CloseSocket(hSocket);
936 if (CNode::IsBanned(addr) && !whitelisted)
938 LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
939 CloseSocket(hSocket);
943 if (nInbound >= nMaxInbound)
945 if (!AttemptToEvictConnection(whitelisted)) {
946 // No connection to evict, disconnect the new connection
947 LogPrint("net", "failed to find an eviction candidate - connection dropped (full)\n");
948 CloseSocket(hSocket);
953 // According to the internet TCP_NODELAY is not carried into accepted sockets
954 // on all platforms. Set it again here just to be sure.
957 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
959 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
962 CNode* pnode = new CNode(hSocket, addr, "", true);
964 pnode->fWhitelisted = whitelisted;
966 LogPrint("net", "connection from %s accepted\n", addr.ToString());
970 vNodes.push_back(pnode);
974 void ThreadSocketHandler()
976 unsigned int nPrevNodeCount = 0;
984 // Disconnect unused nodes
985 vector<CNode*> vNodesCopy = vNodes;
986 BOOST_FOREACH(CNode* pnode, vNodesCopy)
988 if (pnode->fDisconnect ||
989 (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
991 // remove from vNodes
992 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
994 // release outbound grant (if any)
995 pnode->grantOutbound.Release();
997 // close socket and cleanup
998 pnode->CloseSocketDisconnect();
1000 // hold in disconnected pool until all refs are released
1001 if (pnode->fNetworkNode || pnode->fInbound)
1003 vNodesDisconnected.push_back(pnode);
1008 // Delete disconnected nodes
1009 list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1010 BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
1012 // wait until threads are done using it
1013 if (pnode->GetRefCount() <= 0)
1015 bool fDelete = false;
1017 TRY_LOCK(pnode->cs_vSend, lockSend);
1020 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1023 TRY_LOCK(pnode->cs_inventory, lockInv);
1031 vNodesDisconnected.remove(pnode);
1037 if(vNodes.size() != nPrevNodeCount) {
1038 nPrevNodeCount = vNodes.size();
1039 uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
1043 // Find which sockets have data to receive
1045 struct timeval timeout;
1047 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
1052 FD_ZERO(&fdsetRecv);
1053 FD_ZERO(&fdsetSend);
1054 FD_ZERO(&fdsetError);
1055 SOCKET hSocketMax = 0;
1056 bool have_fds = false;
1058 BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) {
1059 FD_SET(hListenSocket.socket, &fdsetRecv);
1060 hSocketMax = max(hSocketMax, hListenSocket.socket);
1066 BOOST_FOREACH(CNode* pnode, vNodes)
1068 if (pnode->hSocket == INVALID_SOCKET)
1070 FD_SET(pnode->hSocket, &fdsetError);
1071 hSocketMax = max(hSocketMax, pnode->hSocket);
1074 // Implement the following logic:
1075 // * If there is data to send, select() for sending data. As this only
1076 // happens when optimistic write failed, we choose to first drain the
1077 // write buffer in this case before receiving more. This avoids
1078 // needlessly queueing received data, if the remote peer is not themselves
1079 // receiving data. This means properly utilizing TCP flow control signaling.
1080 // * Otherwise, if there is no (complete) message in the receive buffer,
1081 // or there is space left in the buffer, select() for receiving data.
1082 // * (if neither of the above applies, there is certainly one message
1083 // in the receiver buffer ready to be processed).
1084 // Together, that means that at least one of the following is always possible,
1085 // so we don't deadlock:
1086 // * We send some data.
1087 // * We wait for data to be received (and disconnect after timeout).
1088 // * We process a message in the buffer (message handler thread).
1090 TRY_LOCK(pnode->cs_vSend, lockSend);
1091 if (lockSend && !pnode->vSendMsg.empty()) {
1092 FD_SET(pnode->hSocket, &fdsetSend);
1097 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1099 pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
1100 pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
1101 FD_SET(pnode->hSocket, &fdsetRecv);
1106 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
1107 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1108 boost::this_thread::interruption_point();
1110 if (nSelect == SOCKET_ERROR)
1114 int nErr = WSAGetLastError();
1115 LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1116 for (unsigned int i = 0; i <= hSocketMax; i++)
1117 FD_SET(i, &fdsetRecv);
1119 FD_ZERO(&fdsetSend);
1120 FD_ZERO(&fdsetError);
1121 MilliSleep(timeout.tv_usec/1000);
1125 // Accept new connections
1127 BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket)
1129 if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
1131 AcceptConnection(hListenSocket);
1136 // Service each socket
1138 vector<CNode*> vNodesCopy;
1141 vNodesCopy = vNodes;
1142 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1145 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1147 boost::this_thread::interruption_point();
1152 if (pnode->hSocket == INVALID_SOCKET)
1154 if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
1156 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1160 // typical socket buffer is 8K-64K
1161 char pchBuf[0x10000];
1162 int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1165 if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
1166 pnode->CloseSocketDisconnect();
1167 pnode->nLastRecv = GetTime();
1168 pnode->nRecvBytes += nBytes;
1169 pnode->RecordBytesRecv(nBytes);
1171 else if (nBytes == 0)
1173 // socket closed gracefully
1174 if (!pnode->fDisconnect)
1175 LogPrint("net", "socket closed\n");
1176 pnode->CloseSocketDisconnect();
1178 else if (nBytes < 0)
1181 int nErr = WSAGetLastError();
1182 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1184 if (!pnode->fDisconnect)
1185 LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
1186 pnode->CloseSocketDisconnect();
1196 if (pnode->hSocket == INVALID_SOCKET)
1198 if (FD_ISSET(pnode->hSocket, &fdsetSend))
1200 TRY_LOCK(pnode->cs_vSend, lockSend);
1202 SocketSendData(pnode);
1206 // Inactivity checking
1208 int64_t nTime = GetTime();
1209 if (nTime - pnode->nTimeConnected > 60)
1211 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1213 LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
1214 pnode->fDisconnect = true;
1216 else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
1218 LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
1219 pnode->fDisconnect = true;
1221 else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
1223 LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
1224 pnode->fDisconnect = true;
1226 else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
1228 LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
1229 pnode->fDisconnect = true;
1235 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1242 void ThreadDNSAddressSeed()
1244 // goal: only query DNS seeds if address need is acute
1245 if ((addrman.size() > 0) &&
1246 (!GetBoolArg("-forcednsseed", false))) {
1247 MilliSleep(11 * 1000);
1250 if (vNodes.size() >= 2) {
1251 LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1256 const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
1259 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1261 BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
1262 if (HaveNameProxy()) {
1263 AddOneShot(seed.host);
1265 vector<CNetAddr> vIPs;
1266 vector<CAddress> vAdd;
1267 if (LookupHost(seed.host.c_str(), vIPs))
1269 BOOST_FOREACH(const CNetAddr& ip, vIPs)
1271 int nOneDay = 24*3600;
1272 CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
1273 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1274 vAdd.push_back(addr);
1278 addrman.Add(vAdd, CNetAddr(seed.name, true));
1282 LogPrintf("%d addresses found from DNS seeds\n", found);
1296 void DumpAddresses()
1298 int64_t nStart = GetTimeMillis();
1303 LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
1304 addrman.size(), GetTimeMillis() - nStart);
1307 void static ProcessOneShot()
1312 if (vOneShots.empty())
1314 strDest = vOneShots.front();
1315 vOneShots.pop_front();
1318 CSemaphoreGrant grant(*semOutbound, true);
1320 if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1321 AddOneShot(strDest);
1325 void ThreadOpenConnections()
1327 // Connect to specific addresses
1328 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1330 for (int64_t nLoop = 0;; nLoop++)
1333 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-connect"])
1336 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1337 for (int i = 0; i < 10 && i < nLoop; i++)
1346 // Initiate network connections
1347 int64_t nStart = GetTime();
1354 CSemaphoreGrant grant(*semOutbound);
1355 boost::this_thread::interruption_point();
1357 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1358 if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1359 static bool done = false;
1361 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1362 addrman.Add(convertSeed6(Params().FixedSeeds()), CNetAddr("127.0.0.1"));
1368 // Choose an address to connect to based on most recently seen
1370 CAddress addrConnect;
1372 // Only connect out to one peer per network group (/16 for IPv4).
1373 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1375 set<vector<unsigned char> > setConnected;
1378 BOOST_FOREACH(CNode* pnode, vNodes) {
1379 if (!pnode->fInbound) {
1380 setConnected.insert(pnode->addr.GetGroup());
1386 int64_t nANow = GetAdjustedTime();
1391 CAddrInfo addr = addrman.Select();
1393 // if we selected an invalid address, restart
1394 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1397 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1398 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1399 // already-connected network ranges, ...) before trying new addrman addresses.
1404 if (IsLimited(addr))
1407 // only consider very recently tried nodes after 30 failed attempts
1408 if (nANow - addr.nLastTry < 600 && nTries < 30)
1411 // do not allow non-default ports, unless after 50 invalid addresses selected already
1412 if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1419 if (addrConnect.IsValid())
1420 OpenNetworkConnection(addrConnect, &grant);
1424 void ThreadOpenAddedConnections()
1427 LOCK(cs_vAddedNodes);
1428 vAddedNodes = mapMultiArgs["-addnode"];
1431 if (HaveNameProxy()) {
1433 list<string> lAddresses(0);
1435 LOCK(cs_vAddedNodes);
1436 BOOST_FOREACH(const std::string& strAddNode, vAddedNodes)
1437 lAddresses.push_back(strAddNode);
1439 BOOST_FOREACH(const std::string& strAddNode, lAddresses) {
1441 CSemaphoreGrant grant(*semOutbound);
1442 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1445 MilliSleep(120000); // Retry every 2 minutes
1449 for (unsigned int i = 0; true; i++)
1451 list<string> lAddresses(0);
1453 LOCK(cs_vAddedNodes);
1454 BOOST_FOREACH(const std::string& strAddNode, vAddedNodes)
1455 lAddresses.push_back(strAddNode);
1458 list<vector<CService> > lservAddressesToAdd(0);
1459 BOOST_FOREACH(const std::string& strAddNode, lAddresses) {
1460 vector<CService> vservNode(0);
1461 if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
1463 lservAddressesToAdd.push_back(vservNode);
1465 LOCK(cs_setservAddNodeAddresses);
1466 BOOST_FOREACH(const CService& serv, vservNode)
1467 setservAddNodeAddresses.insert(serv);
1471 // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1472 // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1475 BOOST_FOREACH(CNode* pnode, vNodes)
1476 for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
1477 BOOST_FOREACH(const CService& addrNode, *(it))
1478 if (pnode->addr == addrNode)
1480 it = lservAddressesToAdd.erase(it);
1485 BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
1487 CSemaphoreGrant grant(*semOutbound);
1488 OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
1491 MilliSleep(120000); // Retry every 2 minutes
1495 // if successful, this moves the passed grant to the constructed node
1496 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot)
1499 // Initiate outbound network connection
1501 boost::this_thread::interruption_point();
1503 if (IsLocal(addrConnect) ||
1504 FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1505 FindNode(addrConnect.ToStringIPPort()))
1507 } else if (FindNode(std::string(pszDest)))
1510 CNode* pnode = ConnectNode(addrConnect, pszDest);
1511 boost::this_thread::interruption_point();
1516 grantOutbound->MoveTo(pnode->grantOutbound);
1517 pnode->fNetworkNode = true;
1519 pnode->fOneShot = true;
1525 void ThreadMessageHandler()
1527 boost::mutex condition_mutex;
1528 boost::unique_lock<boost::mutex> lock(condition_mutex);
1530 SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1533 vector<CNode*> vNodesCopy;
1536 vNodesCopy = vNodes;
1537 BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1542 // Poll the connected nodes for messages
1543 CNode* pnodeTrickle = NULL;
1544 if (!vNodesCopy.empty())
1545 pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1549 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1551 if (pnode->fDisconnect)
1556 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1559 if (!g_signals.ProcessMessages(pnode))
1560 pnode->CloseSocketDisconnect();
1562 if (pnode->nSendSize < SendBufferSize())
1564 if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete()))
1571 boost::this_thread::interruption_point();
1575 TRY_LOCK(pnode->cs_vSend, lockSend);
1577 g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted);
1579 boost::this_thread::interruption_point();
1584 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1589 messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100));
1598 bool BindListenPort(const CService &addrBind, string& strError, bool fWhitelisted)
1603 // Create socket for listening for incoming connections
1604 struct sockaddr_storage sockaddr;
1605 socklen_t len = sizeof(sockaddr);
1606 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1608 strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
1609 LogPrintf("%s\n", strError);
1613 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1614 if (hListenSocket == INVALID_SOCKET)
1616 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
1617 LogPrintf("%s\n", strError);
1620 if (!IsSelectableSocket(hListenSocket))
1622 strError = "Error: Couldn't create a listenable socket for incoming connections";
1623 LogPrintf("%s\n", strError);
1630 // Different way of disabling SIGPIPE on BSD
1631 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1633 // Allow binding if the port is still in TIME_WAIT state after
1634 // the program was closed and restarted.
1635 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1636 // Disable Nagle's algorithm
1637 setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int));
1639 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int));
1640 setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int));
1643 // Set to non-blocking, incoming connections will also inherit this
1644 if (!SetSocketNonBlocking(hListenSocket, true)) {
1645 strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
1646 LogPrintf("%s\n", strError);
1650 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1651 // and enable it by default or not. Try to enable it, if possible.
1652 if (addrBind.IsIPv6()) {
1655 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1657 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1661 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
1662 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
1666 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1668 int nErr = WSAGetLastError();
1669 if (nErr == WSAEADDRINUSE)
1670 strError = strprintf(_("Unable to bind to %s on this computer. Zcash is probably already running."), addrBind.ToString());
1672 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
1673 LogPrintf("%s\n", strError);
1674 CloseSocket(hListenSocket);
1677 LogPrintf("Bound to %s\n", addrBind.ToString());
1679 // Listen for incoming connections
1680 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1682 strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
1683 LogPrintf("%s\n", strError);
1684 CloseSocket(hListenSocket);
1688 vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
1690 if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
1691 AddLocal(addrBind, LOCAL_BIND);
1696 void static Discover(boost::thread_group& threadGroup)
1702 // Get local host IP
1703 char pszHostName[256] = "";
1704 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1706 vector<CNetAddr> vaddr;
1707 if (LookupHost(pszHostName, vaddr))
1709 BOOST_FOREACH (const CNetAddr &addr, vaddr)
1711 if (AddLocal(addr, LOCAL_IF))
1712 LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
1717 // Get local host ip
1718 struct ifaddrs* myaddrs;
1719 if (getifaddrs(&myaddrs) == 0)
1721 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1723 if (ifa->ifa_addr == NULL) continue;
1724 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1725 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1726 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1727 if (ifa->ifa_addr->sa_family == AF_INET)
1729 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1730 CNetAddr addr(s4->sin_addr);
1731 if (AddLocal(addr, LOCAL_IF))
1732 LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
1734 else if (ifa->ifa_addr->sa_family == AF_INET6)
1736 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1737 CNetAddr addr(s6->sin6_addr);
1738 if (AddLocal(addr, LOCAL_IF))
1739 LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
1742 freeifaddrs(myaddrs);
1747 void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler)
1749 uiInterface.InitMessage(_("Loading addresses..."));
1750 // Load addresses for peers.dat
1751 int64_t nStart = GetTimeMillis();
1754 if (!adb.Read(addrman))
1755 LogPrintf("Invalid or missing peers.dat; recreating\n");
1757 LogPrintf("Loaded %i addresses from peers.dat %dms\n",
1758 addrman.size(), GetTimeMillis() - nStart);
1759 fAddressesInitialized = true;
1761 if (semOutbound == NULL) {
1762 // initialize semaphore
1763 int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
1764 semOutbound = new CSemaphore(nMaxOutbound);
1767 if (pnodeLocalHost == NULL)
1768 pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1770 Discover(threadGroup);
1776 if (!GetBoolArg("-dnsseed", true))
1777 LogPrintf("DNS seeding disabled\n");
1779 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
1781 // Send and receive from sockets, accept connections
1782 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
1784 // Initiate outbound connections from -addnode
1785 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
1787 // Initiate outbound connections
1788 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
1791 threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
1793 // Dump network addresses
1794 scheduler.scheduleEvery(&DumpAddresses, DUMP_ADDRESSES_INTERVAL);
1799 LogPrintf("StopNode()\n");
1801 for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1802 semOutbound->post();
1804 if (fAddressesInitialized)
1807 fAddressesInitialized = false;
1813 static class CNetCleanup
1821 BOOST_FOREACH(CNode* pnode, vNodes)
1822 if (pnode->hSocket != INVALID_SOCKET)
1823 CloseSocket(pnode->hSocket);
1824 BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket)
1825 if (hListenSocket.socket != INVALID_SOCKET)
1826 if (!CloseSocket(hListenSocket.socket))
1827 LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
1829 // clean up some globals (to help leak detection)
1830 BOOST_FOREACH(CNode *pnode, vNodes)
1832 BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
1835 vNodesDisconnected.clear();
1836 vhListenSocket.clear();
1839 delete pnodeLocalHost;
1840 pnodeLocalHost = NULL;
1843 // Shutdown Windows Sockets
1848 instance_of_cnetcleanup;
1856 void RelayTransaction(const CTransaction& tx)
1858 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1861 RelayTransaction(tx, ss);
1864 void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
1866 CInv inv(MSG_TX, tx.GetHash());
1869 // Expire old relay messages
1870 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
1872 mapRelay.erase(vRelayExpiration.front().second);
1873 vRelayExpiration.pop_front();
1876 // Save original serialized message so newer versions are preserved
1877 mapRelay.insert(std::make_pair(inv, ss));
1878 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1881 BOOST_FOREACH(CNode* pnode, vNodes)
1883 if(!pnode->fRelayTxes)
1885 LOCK(pnode->cs_filter);
1888 if (pnode->pfilter->IsRelevantAndUpdate(tx))
1889 pnode->PushInventory(inv);
1891 pnode->PushInventory(inv);
1895 void CNode::RecordBytesRecv(uint64_t bytes)
1897 LOCK(cs_totalBytesRecv);
1898 nTotalBytesRecv += bytes;
1901 void CNode::RecordBytesSent(uint64_t bytes)
1903 LOCK(cs_totalBytesSent);
1904 nTotalBytesSent += bytes;
1907 uint64_t CNode::GetTotalBytesRecv()
1909 LOCK(cs_totalBytesRecv);
1910 return nTotalBytesRecv;
1913 uint64_t CNode::GetTotalBytesSent()
1915 LOCK(cs_totalBytesSent);
1916 return nTotalBytesSent;
1919 void CNode::Fuzz(int nChance)
1921 if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
1922 if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
1927 // xor a random byte with a random value:
1928 if (!ssSend.empty()) {
1929 CDataStream::size_type pos = GetRand(ssSend.size());
1930 ssSend[pos] ^= (unsigned char)(GetRand(256));
1934 // delete a random byte:
1935 if (!ssSend.empty()) {
1936 CDataStream::size_type pos = GetRand(ssSend.size());
1937 ssSend.erase(ssSend.begin()+pos);
1941 // insert a random byte at a random position
1943 CDataStream::size_type pos = GetRand(ssSend.size());
1944 char ch = (char)GetRand(256);
1945 ssSend.insert(ssSend.begin()+pos, ch);
1949 // Chance of more than one change half the time:
1950 // (more changes exponentially less likely):
1960 pathAddr = GetDataDir() / "peers.dat";
1963 bool CAddrDB::Write(const CAddrMan& addr)
1965 // Generate random temporary filename
1966 unsigned short randv = 0;
1967 GetRandBytes((unsigned char*)&randv, sizeof(randv));
1968 std::string tmpfn = strprintf("peers.dat.%04x", randv);
1970 // serialize addresses, checksum data up to that point, then append csum
1971 CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
1972 ssPeers << FLATDATA(Params().MessageStart());
1974 uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
1977 // open temp output file, and associate with CAutoFile
1978 boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
1979 FILE *file = fopen(pathTmp.string().c_str(), "wb");
1980 CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
1981 if (fileout.IsNull())
1982 return error("%s: Failed to open file %s", __func__, pathTmp.string());
1984 // Write and commit header, data
1988 catch (const std::exception& e) {
1989 return error("%s: Serialize or I/O error - %s", __func__, e.what());
1991 FileCommit(fileout.Get());
1994 // replace existing peers.dat, if any, with new peers.dat.XXXX
1995 if (!RenameOver(pathTmp, pathAddr))
1996 return error("%s: Rename-into-place failed", __func__);
2001 bool CAddrDB::Read(CAddrMan& addr)
2003 // open input file, and associate with CAutoFile
2004 FILE *file = fopen(pathAddr.string().c_str(), "rb");
2005 CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
2006 if (filein.IsNull())
2007 return error("%s: Failed to open file %s", __func__, pathAddr.string());
2009 // use file size to size memory buffer
2010 int fileSize = boost::filesystem::file_size(pathAddr);
2011 int dataSize = fileSize - sizeof(uint256);
2012 // Don't try to resize to a negative number if file is small
2015 vector<unsigned char> vchData;
2016 vchData.resize(dataSize);
2019 // read data and checksum from file
2021 filein.read((char *)&vchData[0], dataSize);
2024 catch (const std::exception& e) {
2025 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2029 CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
2031 // verify stored checksum matches input data
2032 uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
2033 if (hashIn != hashTmp)
2034 return error("%s: Checksum mismatch, data corrupted", __func__);
2036 unsigned char pchMsgTmp[4];
2038 // de-serialize file header (network specific magic number) and ..
2039 ssPeers >> FLATDATA(pchMsgTmp);
2041 // ... verify the network matches ours
2042 if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
2043 return error("%s: Invalid network magic number", __func__);
2045 // de-serialize address data into one CAddrMan object
2048 catch (const std::exception& e) {
2049 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2055 unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
2056 unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
2058 CNode::CNode(SOCKET hSocketIn, const CAddress& addrIn, const std::string& addrNameIn, bool fInboundIn) :
2059 ssSend(SER_NETWORK, INIT_PROTO_VERSION),
2060 addrKnown(5000, 0.001),
2061 setInventoryKnown(SendBufferSize() / 1000)
2064 hSocket = hSocketIn;
2065 nRecvVersion = INIT_PROTO_VERSION;
2070 nTimeConnected = GetTime();
2073 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
2076 fWhitelisted = false;
2078 fClient = false; // set by version message
2079 fInbound = fInboundIn;
2080 fNetworkNode = false;
2081 fSuccessfullyConnected = false;
2082 fDisconnect = false;
2086 hashContinue = uint256();
2087 nStartingHeight = -1;
2091 pfilter = new CBloomFilter();
2095 fPingQueued = false;
2096 nMinPingUsecTime = std::numeric_limits<int64_t>::max();
2099 LOCK(cs_nLastNodeId);
2104 LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
2106 LogPrint("net", "Added connection peer=%d\n", id);
2108 // Be shy and don't send version until we hear
2109 if (hSocket != INVALID_SOCKET && !fInbound)
2112 GetNodeSignals().InitializeNode(GetId(), this);
2117 CloseSocket(hSocket);
2122 GetNodeSignals().FinalizeNode(GetId());
2125 void CNode::AskFor(const CInv& inv)
2127 if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ)
2129 // a peer may not have multiple non-responded queue positions for a single inv item
2130 if (!setAskFor.insert(inv.hash).second)
2133 // We're using mapAskFor as a priority queue,
2134 // the key is the earliest time the request can be sent
2135 int64_t nRequestTime;
2136 limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
2137 if (it != mapAlreadyAskedFor.end())
2138 nRequestTime = it->second;
2141 LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
2143 // Make sure not to reuse time indexes to keep things in the same order
2144 int64_t nNow = GetTimeMicros() - 1000000;
2145 static int64_t nLastTime;
2147 nNow = std::max(nNow, nLastTime);
2150 // Each retry is 2 minutes after the last
2151 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
2152 if (it != mapAlreadyAskedFor.end())
2153 mapAlreadyAskedFor.update(it, nRequestTime);
2155 mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
2156 mapAskFor.insert(std::make_pair(nRequestTime, inv));
2159 void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
2161 ENTER_CRITICAL_SECTION(cs_vSend);
2162 assert(ssSend.size() == 0);
2163 ssSend << CMessageHeader(Params().MessageStart(), pszCommand, 0);
2164 LogPrint("net", "sending: %s ", SanitizeString(pszCommand));
2167 void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
2171 LEAVE_CRITICAL_SECTION(cs_vSend);
2173 LogPrint("net", "(aborted)\n");
2176 void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
2178 // The -*messagestest options are intentionally not documented in the help message,
2179 // since they are only used during development to debug the networking code and are
2180 // not intended for end-users.
2181 if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0)
2183 LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
2187 if (mapArgs.count("-fuzzmessagestest"))
2188 Fuzz(GetArg("-fuzzmessagestest", 10));
2190 if (ssSend.size() == 0)
2192 LEAVE_CRITICAL_SECTION(cs_vSend);
2196 unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
2197 WriteLE32((uint8_t*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], nSize);
2200 uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
2201 unsigned int nChecksum = 0;
2202 memcpy(&nChecksum, &hash, sizeof(nChecksum));
2203 assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
2204 memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
2206 LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
2208 std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
2209 ssSend.GetAndClear(*it);
2210 nSendSize += (*it).size();
2212 // If write queue empty, attempt "optimistic write"
2213 if (it == vSendMsg.begin())
2214 SocketSendData(this);
2216 LEAVE_CRITICAL_SECTION(cs_vSend);