Remove CValidationInterface::UpdatedTransaction
[bitcoinplatinum.git] / src / net.cpp
blobcf94faf8540fc26021e5464edda7e661a814a7ee
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2016 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
8 #endif
10 #include "net.h"
12 #include "addrman.h"
13 #include "chainparams.h"
14 #include "clientversion.h"
15 #include "consensus/consensus.h"
16 #include "crypto/common.h"
17 #include "crypto/sha256.h"
18 #include "hash.h"
19 #include "primitives/transaction.h"
20 #include "netbase.h"
21 #include "scheduler.h"
22 #include "ui_interface.h"
23 #include "utilstrencodings.h"
25 #ifdef WIN32
26 #include <string.h>
27 #else
28 #include <fcntl.h>
29 #endif
31 #ifdef USE_UPNP
32 #include <miniupnpc/miniupnpc.h>
33 #include <miniupnpc/miniwget.h>
34 #include <miniupnpc/upnpcommands.h>
35 #include <miniupnpc/upnperrors.h>
36 #endif
39 #include <math.h>
41 // Dump addresses to peers.dat and banlist.dat every 15 minutes (900s)
42 #define DUMP_ADDRESSES_INTERVAL 900
44 // We add a random period time (0 to 1 seconds) to feeler connections to prevent synchronization.
45 #define FEELER_SLEEP_WINDOW 1
47 #if !defined(HAVE_MSG_NOSIGNAL)
48 #define MSG_NOSIGNAL 0
49 #endif
51 // MSG_DONTWAIT is not available on some platforms, if it doesn't exist define it as 0
52 #if !defined(HAVE_MSG_DONTWAIT)
53 #define MSG_DONTWAIT 0
54 #endif
56 // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
57 // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
58 #ifdef WIN32
59 #ifndef PROTECTION_LEVEL_UNRESTRICTED
60 #define PROTECTION_LEVEL_UNRESTRICTED 10
61 #endif
62 #ifndef IPV6_PROTECTION_LEVEL
63 #define IPV6_PROTECTION_LEVEL 23
64 #endif
65 #endif
67 const static std::string NET_MESSAGE_COMMAND_OTHER = "*other*";
69 static const uint64_t RANDOMIZER_ID_NETGROUP = 0x6c0edd8036ef4036ULL; // SHA256("netgroup")[0:8]
70 static const uint64_t RANDOMIZER_ID_LOCALHOSTNONCE = 0xd93e69e2bbfa5735ULL; // SHA256("localhostnonce")[0:8]
72 // Global state variables
74 bool fDiscover = true;
75 bool fListen = true;
76 bool fRelayTxes = true;
77 CCriticalSection cs_mapLocalHost;
78 std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
79 static bool vfLimited[NET_MAX] = {};
80 std::string strSubVersion;
82 limitedmap<uint256, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
84 // Signals for message handling
85 static CNodeSignals g_signals;
86 CNodeSignals& GetNodeSignals() { return g_signals; }
88 void CConnman::AddOneShot(const std::string& strDest)
90 LOCK(cs_vOneShots);
91 vOneShots.push_back(strDest);
94 unsigned short GetListenPort()
96 return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
99 // find 'best' local address for a particular peer
100 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
102 if (!fListen)
103 return false;
105 int nBestScore = -1;
106 int nBestReachability = -1;
108 LOCK(cs_mapLocalHost);
109 for (std::map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
111 int nScore = (*it).second.nScore;
112 int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
113 if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
115 addr = CService((*it).first, (*it).second.nPort);
116 nBestReachability = nReachability;
117 nBestScore = nScore;
121 return nBestScore >= 0;
124 //! Convert the pnSeeds6 array into usable address objects.
125 static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn)
127 // It'll only connect to one or two seed nodes because once it connects,
128 // it'll get a pile of addresses with newer timestamps.
129 // Seed nodes are given a random 'last seen time' of between one and two
130 // weeks ago.
131 const int64_t nOneWeek = 7*24*60*60;
132 std::vector<CAddress> vSeedsOut;
133 vSeedsOut.reserve(vSeedsIn.size());
134 for (std::vector<SeedSpec6>::const_iterator i(vSeedsIn.begin()); i != vSeedsIn.end(); ++i)
136 struct in6_addr ip;
137 memcpy(&ip, i->addr, sizeof(ip));
138 CAddress addr(CService(ip, i->port), NODE_NETWORK);
139 addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
140 vSeedsOut.push_back(addr);
142 return vSeedsOut;
145 // get best local address for a particular peer as a CAddress
146 // Otherwise, return the unroutable 0.0.0.0 but filled in with
147 // the normal parameters, since the IP may be changed to a useful
148 // one by discovery.
149 CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
151 CAddress ret(CService(CNetAddr(),GetListenPort()), NODE_NONE);
152 CService addr;
153 if (GetLocal(addr, paddrPeer))
155 ret = CAddress(addr, nLocalServices);
157 ret.nTime = GetAdjustedTime();
158 return ret;
161 int GetnScore(const CService& addr)
163 LOCK(cs_mapLocalHost);
164 if (mapLocalHost.count(addr) == LOCAL_NONE)
165 return 0;
166 return mapLocalHost[addr].nScore;
169 // Is our peer's addrLocal potentially useful as an external IP source?
170 bool IsPeerAddrLocalGood(CNode *pnode)
172 CService addrLocal = pnode->GetAddrLocal();
173 return fDiscover && pnode->addr.IsRoutable() && addrLocal.IsRoutable() &&
174 !IsLimited(addrLocal.GetNetwork());
177 // pushes our own address to a peer
178 void AdvertiseLocal(CNode *pnode)
180 if (fListen && pnode->fSuccessfullyConnected)
182 CAddress addrLocal = GetLocalAddress(&pnode->addr, pnode->GetLocalServices());
183 // If discovery is enabled, sometimes give our peer the address it
184 // tells us that it sees us as in case it has a better idea of our
185 // address than we do.
186 if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
187 GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0))
189 addrLocal.SetIP(pnode->GetAddrLocal());
191 if (addrLocal.IsRoutable())
193 LogPrint(BCLog::NET, "AdvertiseLocal: advertising address %s\n", addrLocal.ToString());
194 FastRandomContext insecure_rand;
195 pnode->PushAddress(addrLocal, insecure_rand);
200 // learn a new local address
201 bool AddLocal(const CService& addr, int nScore)
203 if (!addr.IsRoutable())
204 return false;
206 if (!fDiscover && nScore < LOCAL_MANUAL)
207 return false;
209 if (IsLimited(addr))
210 return false;
212 LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
215 LOCK(cs_mapLocalHost);
216 bool fAlready = mapLocalHost.count(addr) > 0;
217 LocalServiceInfo &info = mapLocalHost[addr];
218 if (!fAlready || nScore >= info.nScore) {
219 info.nScore = nScore + (fAlready ? 1 : 0);
220 info.nPort = addr.GetPort();
224 return true;
227 bool AddLocal(const CNetAddr &addr, int nScore)
229 return AddLocal(CService(addr, GetListenPort()), nScore);
232 bool RemoveLocal(const CService& addr)
234 LOCK(cs_mapLocalHost);
235 LogPrintf("RemoveLocal(%s)\n", addr.ToString());
236 mapLocalHost.erase(addr);
237 return true;
240 /** Make a particular network entirely off-limits (no automatic connects to it) */
241 void SetLimited(enum Network net, bool fLimited)
243 if (net == NET_UNROUTABLE)
244 return;
245 LOCK(cs_mapLocalHost);
246 vfLimited[net] = fLimited;
249 bool IsLimited(enum Network net)
251 LOCK(cs_mapLocalHost);
252 return vfLimited[net];
255 bool IsLimited(const CNetAddr &addr)
257 return IsLimited(addr.GetNetwork());
260 /** vote for a local address */
261 bool SeenLocal(const CService& addr)
264 LOCK(cs_mapLocalHost);
265 if (mapLocalHost.count(addr) == 0)
266 return false;
267 mapLocalHost[addr].nScore++;
269 return true;
273 /** check whether a given address is potentially local */
274 bool IsLocal(const CService& addr)
276 LOCK(cs_mapLocalHost);
277 return mapLocalHost.count(addr) > 0;
280 /** check whether a given network is one we can probably connect to */
281 bool IsReachable(enum Network net)
283 LOCK(cs_mapLocalHost);
284 return !vfLimited[net];
287 /** check whether a given address is in a network we can probably connect to */
288 bool IsReachable(const CNetAddr& addr)
290 enum Network net = addr.GetNetwork();
291 return IsReachable(net);
295 CNode* CConnman::FindNode(const CNetAddr& ip)
297 LOCK(cs_vNodes);
298 BOOST_FOREACH(CNode* pnode, vNodes)
299 if ((CNetAddr)pnode->addr == ip)
300 return (pnode);
301 return NULL;
304 CNode* CConnman::FindNode(const CSubNet& subNet)
306 LOCK(cs_vNodes);
307 BOOST_FOREACH(CNode* pnode, vNodes)
308 if (subNet.Match((CNetAddr)pnode->addr))
309 return (pnode);
310 return NULL;
313 CNode* CConnman::FindNode(const std::string& addrName)
315 LOCK(cs_vNodes);
316 BOOST_FOREACH(CNode* pnode, vNodes) {
317 if (pnode->GetAddrName() == addrName) {
318 return (pnode);
321 return NULL;
324 CNode* CConnman::FindNode(const CService& addr)
326 LOCK(cs_vNodes);
327 BOOST_FOREACH(CNode* pnode, vNodes)
328 if ((CService)pnode->addr == addr)
329 return (pnode);
330 return NULL;
333 bool CConnman::CheckIncomingNonce(uint64_t nonce)
335 LOCK(cs_vNodes);
336 BOOST_FOREACH(CNode* pnode, vNodes) {
337 if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce)
338 return false;
340 return true;
343 CNode* CConnman::ConnectNode(CAddress addrConnect, const char *pszDest, bool fCountFailure)
345 if (pszDest == NULL) {
346 if (IsLocal(addrConnect))
347 return NULL;
349 // Look for an existing connection
350 CNode* pnode = FindNode((CService)addrConnect);
351 if (pnode)
353 LogPrintf("Failed to open new connection, already connected\n");
354 return NULL;
358 /// debug print
359 LogPrint(BCLog::NET, "trying connection %s lastseen=%.1fhrs\n",
360 pszDest ? pszDest : addrConnect.ToString(),
361 pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
363 // Connect
364 SOCKET hSocket;
365 bool proxyConnectionFailed = false;
366 if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
367 ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed))
369 if (!IsSelectableSocket(hSocket)) {
370 LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
371 CloseSocket(hSocket);
372 return NULL;
375 if (pszDest && addrConnect.IsValid()) {
376 // It is possible that we already have a connection to the IP/port pszDest resolved to.
377 // In that case, drop the connection that was just created, and return the existing CNode instead.
378 // Also store the name we used to connect in that CNode, so that future FindNode() calls to that
379 // name catch this early.
380 LOCK(cs_vNodes);
381 CNode* pnode = FindNode((CService)addrConnect);
382 if (pnode)
384 pnode->MaybeSetAddrName(std::string(pszDest));
385 CloseSocket(hSocket);
386 LogPrintf("Failed to open new connection, already connected\n");
387 return NULL;
391 addrman.Attempt(addrConnect, fCountFailure);
393 // Add node
394 NodeId id = GetNewNodeId();
395 uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
396 CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addrConnect, CalculateKeyedNetGroup(addrConnect), nonce, pszDest ? pszDest : "", false);
397 pnode->nServicesExpected = ServiceFlags(addrConnect.nServices & nRelevantServices);
398 pnode->AddRef();
400 return pnode;
401 } else if (!proxyConnectionFailed) {
402 // If connecting to the node failed, and failure is not caused by a problem connecting to
403 // the proxy, mark this as an attempt.
404 addrman.Attempt(addrConnect, fCountFailure);
407 return NULL;
410 void CConnman::DumpBanlist()
412 SweepBanned(); // clean unused entries (if bantime has expired)
414 if (!BannedSetIsDirty())
415 return;
417 int64_t nStart = GetTimeMillis();
419 CBanDB bandb;
420 banmap_t banmap;
421 SetBannedSetDirty(false);
422 GetBanned(banmap);
423 if (!bandb.Write(banmap))
424 SetBannedSetDirty(true);
426 LogPrint(BCLog::NET, "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
427 banmap.size(), GetTimeMillis() - nStart);
430 void CNode::CloseSocketDisconnect()
432 fDisconnect = true;
433 LOCK(cs_hSocket);
434 if (hSocket != INVALID_SOCKET)
436 LogPrint(BCLog::NET, "disconnecting peer=%d\n", id);
437 CloseSocket(hSocket);
441 void CConnman::ClearBanned()
444 LOCK(cs_setBanned);
445 setBanned.clear();
446 setBannedIsDirty = true;
448 DumpBanlist(); //store banlist to disk
449 if(clientInterface)
450 clientInterface->BannedListChanged();
453 bool CConnman::IsBanned(CNetAddr ip)
455 bool fResult = false;
457 LOCK(cs_setBanned);
458 for (banmap_t::iterator it = setBanned.begin(); it != setBanned.end(); it++)
460 CSubNet subNet = (*it).first;
461 CBanEntry banEntry = (*it).second;
463 if(subNet.Match(ip) && GetTime() < banEntry.nBanUntil)
464 fResult = true;
467 return fResult;
470 bool CConnman::IsBanned(CSubNet subnet)
472 bool fResult = false;
474 LOCK(cs_setBanned);
475 banmap_t::iterator i = setBanned.find(subnet);
476 if (i != setBanned.end())
478 CBanEntry banEntry = (*i).second;
479 if (GetTime() < banEntry.nBanUntil)
480 fResult = true;
483 return fResult;
486 void CConnman::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
487 CSubNet subNet(addr);
488 Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
491 void CConnman::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch) {
492 CBanEntry banEntry(GetTime());
493 banEntry.banReason = banReason;
494 if (bantimeoffset <= 0)
496 bantimeoffset = GetArg("-bantime", DEFAULT_MISBEHAVING_BANTIME);
497 sinceUnixEpoch = false;
499 banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
502 LOCK(cs_setBanned);
503 if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
504 setBanned[subNet] = banEntry;
505 setBannedIsDirty = true;
507 else
508 return;
510 if(clientInterface)
511 clientInterface->BannedListChanged();
513 LOCK(cs_vNodes);
514 BOOST_FOREACH(CNode* pnode, vNodes) {
515 if (subNet.Match((CNetAddr)pnode->addr))
516 pnode->fDisconnect = true;
519 if(banReason == BanReasonManuallyAdded)
520 DumpBanlist(); //store banlist to disk immediately if user requested ban
523 bool CConnman::Unban(const CNetAddr &addr) {
524 CSubNet subNet(addr);
525 return Unban(subNet);
528 bool CConnman::Unban(const CSubNet &subNet) {
530 LOCK(cs_setBanned);
531 if (!setBanned.erase(subNet))
532 return false;
533 setBannedIsDirty = true;
535 if(clientInterface)
536 clientInterface->BannedListChanged();
537 DumpBanlist(); //store banlist to disk immediately
538 return true;
541 void CConnman::GetBanned(banmap_t &banMap)
543 LOCK(cs_setBanned);
544 banMap = setBanned; //create a thread safe copy
547 void CConnman::SetBanned(const banmap_t &banMap)
549 LOCK(cs_setBanned);
550 setBanned = banMap;
551 setBannedIsDirty = true;
554 void CConnman::SweepBanned()
556 int64_t now = GetTime();
558 LOCK(cs_setBanned);
559 banmap_t::iterator it = setBanned.begin();
560 while(it != setBanned.end())
562 CSubNet subNet = (*it).first;
563 CBanEntry banEntry = (*it).second;
564 if(now > banEntry.nBanUntil)
566 setBanned.erase(it++);
567 setBannedIsDirty = true;
568 LogPrint(BCLog::NET, "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
570 else
571 ++it;
575 bool CConnman::BannedSetIsDirty()
577 LOCK(cs_setBanned);
578 return setBannedIsDirty;
581 void CConnman::SetBannedSetDirty(bool dirty)
583 LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
584 setBannedIsDirty = dirty;
588 bool CConnman::IsWhitelistedRange(const CNetAddr &addr) {
589 LOCK(cs_vWhitelistedRange);
590 BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) {
591 if (subnet.Match(addr))
592 return true;
594 return false;
597 void CConnman::AddWhitelistedRange(const CSubNet &subnet) {
598 LOCK(cs_vWhitelistedRange);
599 vWhitelistedRange.push_back(subnet);
603 std::string CNode::GetAddrName() const {
604 LOCK(cs_addrName);
605 return addrName;
608 void CNode::MaybeSetAddrName(const std::string& addrNameIn) {
609 LOCK(cs_addrName);
610 if (addrName.empty()) {
611 addrName = addrNameIn;
615 CService CNode::GetAddrLocal() const {
616 LOCK(cs_addrLocal);
617 return addrLocal;
620 void CNode::SetAddrLocal(const CService& addrLocalIn) {
621 LOCK(cs_addrLocal);
622 if (addrLocal.IsValid()) {
623 error("Addr local already set for node: %i. Refusing to change from %s to %s", id, addrLocal.ToString(), addrLocalIn.ToString());
624 } else {
625 addrLocal = addrLocalIn;
629 #undef X
630 #define X(name) stats.name = name
631 void CNode::copyStats(CNodeStats &stats)
633 stats.nodeid = this->GetId();
634 X(nServices);
635 X(addr);
637 LOCK(cs_filter);
638 X(fRelayTxes);
640 X(nLastSend);
641 X(nLastRecv);
642 X(nTimeConnected);
643 X(nTimeOffset);
644 stats.addrName = GetAddrName();
645 X(nVersion);
647 LOCK(cs_SubVer);
648 X(cleanSubVer);
650 X(fInbound);
651 X(fAddnode);
652 X(nStartingHeight);
654 LOCK(cs_vSend);
655 X(mapSendBytesPerMsgCmd);
656 X(nSendBytes);
659 LOCK(cs_vRecv);
660 X(mapRecvBytesPerMsgCmd);
661 X(nRecvBytes);
663 X(fWhitelisted);
665 // It is common for nodes with good ping times to suddenly become lagged,
666 // due to a new block arriving or other large transfer.
667 // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
668 // since pingtime does not update until the ping is complete, which might take a while.
669 // So, if a ping is taking an unusually long time in flight,
670 // the caller can immediately detect that this is happening.
671 int64_t nPingUsecWait = 0;
672 if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
673 nPingUsecWait = GetTimeMicros() - nPingUsecStart;
676 // 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 :)
677 stats.dPingTime = (((double)nPingUsecTime) / 1e6);
678 stats.dMinPing = (((double)nMinPingUsecTime) / 1e6);
679 stats.dPingWait = (((double)nPingUsecWait) / 1e6);
681 // Leave string empty if addrLocal invalid (not filled in yet)
682 CService addrLocalUnlocked = GetAddrLocal();
683 stats.addrLocal = addrLocalUnlocked.IsValid() ? addrLocalUnlocked.ToString() : "";
685 #undef X
687 bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes, bool& complete)
689 complete = false;
690 int64_t nTimeMicros = GetTimeMicros();
691 LOCK(cs_vRecv);
692 nLastRecv = nTimeMicros / 1000000;
693 nRecvBytes += nBytes;
694 while (nBytes > 0) {
696 // get current incomplete message, or create a new one
697 if (vRecvMsg.empty() ||
698 vRecvMsg.back().complete())
699 vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, INIT_PROTO_VERSION));
701 CNetMessage& msg = vRecvMsg.back();
703 // absorb network data
704 int handled;
705 if (!msg.in_data)
706 handled = msg.readHeader(pch, nBytes);
707 else
708 handled = msg.readData(pch, nBytes);
710 if (handled < 0)
711 return false;
713 if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
714 LogPrint(BCLog::NET, "Oversized message from peer=%i, disconnecting\n", GetId());
715 return false;
718 pch += handled;
719 nBytes -= handled;
721 if (msg.complete()) {
723 //store received bytes per message command
724 //to prevent a memory DOS, only allow valid commands
725 mapMsgCmdSize::iterator i = mapRecvBytesPerMsgCmd.find(msg.hdr.pchCommand);
726 if (i == mapRecvBytesPerMsgCmd.end())
727 i = mapRecvBytesPerMsgCmd.find(NET_MESSAGE_COMMAND_OTHER);
728 assert(i != mapRecvBytesPerMsgCmd.end());
729 i->second += msg.hdr.nMessageSize + CMessageHeader::HEADER_SIZE;
731 msg.nTime = nTimeMicros;
732 complete = true;
736 return true;
739 void CNode::SetSendVersion(int nVersionIn)
741 // Send version may only be changed in the version message, and
742 // only one version message is allowed per session. We can therefore
743 // treat this value as const and even atomic as long as it's only used
744 // once a version message has been successfully processed. Any attempt to
745 // set this twice is an error.
746 if (nSendVersion != 0) {
747 error("Send version already set for node: %i. Refusing to change from %i to %i", id, nSendVersion, nVersionIn);
748 } else {
749 nSendVersion = nVersionIn;
753 int CNode::GetSendVersion() const
755 // The send version should always be explicitly set to
756 // INIT_PROTO_VERSION rather than using this value until SetSendVersion
757 // has been called.
758 if (nSendVersion == 0) {
759 error("Requesting unset send version for node: %i. Using %i", id, INIT_PROTO_VERSION);
760 return INIT_PROTO_VERSION;
762 return nSendVersion;
766 int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
768 // copy data to temporary parsing buffer
769 unsigned int nRemaining = 24 - nHdrPos;
770 unsigned int nCopy = std::min(nRemaining, nBytes);
772 memcpy(&hdrbuf[nHdrPos], pch, nCopy);
773 nHdrPos += nCopy;
775 // if header incomplete, exit
776 if (nHdrPos < 24)
777 return nCopy;
779 // deserialize to CMessageHeader
780 try {
781 hdrbuf >> hdr;
783 catch (const std::exception&) {
784 return -1;
787 // reject messages larger than MAX_SIZE
788 if (hdr.nMessageSize > MAX_SIZE)
789 return -1;
791 // switch state to reading message data
792 in_data = true;
794 return nCopy;
797 int CNetMessage::readData(const char *pch, unsigned int nBytes)
799 unsigned int nRemaining = hdr.nMessageSize - nDataPos;
800 unsigned int nCopy = std::min(nRemaining, nBytes);
802 if (vRecv.size() < nDataPos + nCopy) {
803 // Allocate up to 256 KiB ahead, but never more than the total message size.
804 vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
807 hasher.Write((const unsigned char*)pch, nCopy);
808 memcpy(&vRecv[nDataPos], pch, nCopy);
809 nDataPos += nCopy;
811 return nCopy;
814 const uint256& CNetMessage::GetMessageHash() const
816 assert(complete());
817 if (data_hash.IsNull())
818 hasher.Finalize(data_hash.begin());
819 return data_hash;
830 // requires LOCK(cs_vSend)
831 size_t CConnman::SocketSendData(CNode *pnode) const
833 auto it = pnode->vSendMsg.begin();
834 size_t nSentSize = 0;
836 while (it != pnode->vSendMsg.end()) {
837 const auto &data = *it;
838 assert(data.size() > pnode->nSendOffset);
839 int nBytes = 0;
841 LOCK(pnode->cs_hSocket);
842 if (pnode->hSocket == INVALID_SOCKET)
843 break;
844 nBytes = send(pnode->hSocket, reinterpret_cast<const char*>(data.data()) + pnode->nSendOffset, data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
846 if (nBytes > 0) {
847 pnode->nLastSend = GetSystemTimeInSeconds();
848 pnode->nSendBytes += nBytes;
849 pnode->nSendOffset += nBytes;
850 nSentSize += nBytes;
851 if (pnode->nSendOffset == data.size()) {
852 pnode->nSendOffset = 0;
853 pnode->nSendSize -= data.size();
854 pnode->fPauseSend = pnode->nSendSize > nSendBufferMaxSize;
855 it++;
856 } else {
857 // could not send full message; stop sending more
858 break;
860 } else {
861 if (nBytes < 0) {
862 // error
863 int nErr = WSAGetLastError();
864 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
866 LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
867 pnode->CloseSocketDisconnect();
870 // couldn't send anything at all
871 break;
875 if (it == pnode->vSendMsg.end()) {
876 assert(pnode->nSendOffset == 0);
877 assert(pnode->nSendSize == 0);
879 pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
880 return nSentSize;
883 struct NodeEvictionCandidate
885 NodeId id;
886 int64_t nTimeConnected;
887 int64_t nMinPingUsecTime;
888 int64_t nLastBlockTime;
889 int64_t nLastTXTime;
890 bool fRelevantServices;
891 bool fRelayTxes;
892 bool fBloomFilter;
893 CAddress addr;
894 uint64_t nKeyedNetGroup;
897 static bool ReverseCompareNodeMinPingTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
899 return a.nMinPingUsecTime > b.nMinPingUsecTime;
902 static bool ReverseCompareNodeTimeConnected(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
904 return a.nTimeConnected > b.nTimeConnected;
907 static bool CompareNetGroupKeyed(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b) {
908 return a.nKeyedNetGroup < b.nKeyedNetGroup;
911 static bool CompareNodeBlockTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
913 // There is a fall-through here because it is common for a node to have many peers which have not yet relayed a block.
914 if (a.nLastBlockTime != b.nLastBlockTime) return a.nLastBlockTime < b.nLastBlockTime;
915 if (a.fRelevantServices != b.fRelevantServices) return b.fRelevantServices;
916 return a.nTimeConnected > b.nTimeConnected;
919 static bool CompareNodeTXTime(const NodeEvictionCandidate &a, const NodeEvictionCandidate &b)
921 // 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.
922 if (a.nLastTXTime != b.nLastTXTime) return a.nLastTXTime < b.nLastTXTime;
923 if (a.fRelayTxes != b.fRelayTxes) return b.fRelayTxes;
924 if (a.fBloomFilter != b.fBloomFilter) return a.fBloomFilter;
925 return a.nTimeConnected > b.nTimeConnected;
928 /** Try to find a connection to evict when the node is full.
929 * Extreme care must be taken to avoid opening the node to attacker
930 * triggered network partitioning.
931 * The strategy used here is to protect a small number of peers
932 * for each of several distinct characteristics which are difficult
933 * to forge. In order to partition a node the attacker must be
934 * simultaneously better at all of them than honest peers.
936 bool CConnman::AttemptToEvictConnection()
938 std::vector<NodeEvictionCandidate> vEvictionCandidates;
940 LOCK(cs_vNodes);
942 BOOST_FOREACH(CNode *node, vNodes) {
943 if (node->fWhitelisted)
944 continue;
945 if (!node->fInbound)
946 continue;
947 if (node->fDisconnect)
948 continue;
949 NodeEvictionCandidate candidate = {node->id, node->nTimeConnected, node->nMinPingUsecTime,
950 node->nLastBlockTime, node->nLastTXTime,
951 (node->nServices & nRelevantServices) == nRelevantServices,
952 node->fRelayTxes, node->pfilter != NULL, node->addr, node->nKeyedNetGroup};
953 vEvictionCandidates.push_back(candidate);
957 if (vEvictionCandidates.empty()) return false;
959 // Protect connections with certain characteristics
961 // Deterministically select 4 peers to protect by netgroup.
962 // An attacker cannot predict which netgroups will be protected
963 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNetGroupKeyed);
964 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
966 if (vEvictionCandidates.empty()) return false;
968 // Protect the 8 nodes with the lowest minimum ping time.
969 // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
970 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime);
971 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
973 if (vEvictionCandidates.empty()) return false;
975 // Protect 4 nodes that most recently sent us transactions.
976 // An attacker cannot manipulate this metric without performing useful work.
977 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeTXTime);
978 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
980 if (vEvictionCandidates.empty()) return false;
982 // Protect 4 nodes that most recently sent us blocks.
983 // An attacker cannot manipulate this metric without performing useful work.
984 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), CompareNodeBlockTime);
985 vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
987 if (vEvictionCandidates.empty()) return false;
989 // Protect the half of the remaining nodes which have been connected the longest.
990 // This replicates the non-eviction implicit behavior, and precludes attacks that start later.
991 std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected);
992 vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end());
994 if (vEvictionCandidates.empty()) return false;
996 // Identify the network group with the most connections and youngest member.
997 // (vEvictionCandidates is already sorted by reverse connect time)
998 uint64_t naMostConnections;
999 unsigned int nMostConnections = 0;
1000 int64_t nMostConnectionsTime = 0;
1001 std::map<uint64_t, std::vector<NodeEvictionCandidate> > mapNetGroupNodes;
1002 BOOST_FOREACH(const NodeEvictionCandidate &node, vEvictionCandidates) {
1003 mapNetGroupNodes[node.nKeyedNetGroup].push_back(node);
1004 int64_t grouptime = mapNetGroupNodes[node.nKeyedNetGroup][0].nTimeConnected;
1005 size_t groupsize = mapNetGroupNodes[node.nKeyedNetGroup].size();
1007 if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) {
1008 nMostConnections = groupsize;
1009 nMostConnectionsTime = grouptime;
1010 naMostConnections = node.nKeyedNetGroup;
1014 // Reduce to the network group with the most connections
1015 vEvictionCandidates = std::move(mapNetGroupNodes[naMostConnections]);
1017 // Disconnect from the network group with the most connections
1018 NodeId evicted = vEvictionCandidates.front().id;
1019 LOCK(cs_vNodes);
1020 for(std::vector<CNode*>::const_iterator it(vNodes.begin()); it != vNodes.end(); ++it) {
1021 if ((*it)->GetId() == evicted) {
1022 (*it)->fDisconnect = true;
1023 return true;
1026 return false;
1029 void CConnman::AcceptConnection(const ListenSocket& hListenSocket) {
1030 struct sockaddr_storage sockaddr;
1031 socklen_t len = sizeof(sockaddr);
1032 SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
1033 CAddress addr;
1034 int nInbound = 0;
1035 int nMaxInbound = nMaxConnections - (nMaxOutbound + nMaxFeeler);
1037 if (hSocket != INVALID_SOCKET)
1038 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
1039 LogPrintf("Warning: Unknown socket family\n");
1041 bool whitelisted = hListenSocket.whitelisted || IsWhitelistedRange(addr);
1043 LOCK(cs_vNodes);
1044 BOOST_FOREACH(CNode* pnode, vNodes)
1045 if (pnode->fInbound)
1046 nInbound++;
1049 if (hSocket == INVALID_SOCKET)
1051 int nErr = WSAGetLastError();
1052 if (nErr != WSAEWOULDBLOCK)
1053 LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
1054 return;
1057 if (!fNetworkActive) {
1058 LogPrintf("connection from %s dropped: not accepting new connections\n", addr.ToString());
1059 CloseSocket(hSocket);
1060 return;
1063 if (!IsSelectableSocket(hSocket))
1065 LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
1066 CloseSocket(hSocket);
1067 return;
1070 // According to the internet TCP_NODELAY is not carried into accepted sockets
1071 // on all platforms. Set it again here just to be sure.
1072 int set = 1;
1073 #ifdef WIN32
1074 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
1075 #else
1076 setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
1077 #endif
1079 if (IsBanned(addr) && !whitelisted)
1081 LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
1082 CloseSocket(hSocket);
1083 return;
1086 if (nInbound >= nMaxInbound)
1088 if (!AttemptToEvictConnection()) {
1089 // No connection to evict, disconnect the new connection
1090 LogPrint(BCLog::NET, "failed to find an eviction candidate - connection dropped (full)\n");
1091 CloseSocket(hSocket);
1092 return;
1096 NodeId id = GetNewNodeId();
1097 uint64_t nonce = GetDeterministicRandomizer(RANDOMIZER_ID_LOCALHOSTNONCE).Write(id).Finalize();
1099 CNode* pnode = new CNode(id, nLocalServices, GetBestHeight(), hSocket, addr, CalculateKeyedNetGroup(addr), nonce, "", true);
1100 pnode->AddRef();
1101 pnode->fWhitelisted = whitelisted;
1102 GetNodeSignals().InitializeNode(pnode, *this);
1104 LogPrint(BCLog::NET, "connection from %s accepted\n", addr.ToString());
1107 LOCK(cs_vNodes);
1108 vNodes.push_back(pnode);
1112 void CConnman::ThreadSocketHandler()
1114 unsigned int nPrevNodeCount = 0;
1115 while (!interruptNet)
1118 // Disconnect nodes
1121 LOCK(cs_vNodes);
1122 // Disconnect unused nodes
1123 std::vector<CNode*> vNodesCopy = vNodes;
1124 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1126 if (pnode->fDisconnect)
1128 // remove from vNodes
1129 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
1131 // release outbound grant (if any)
1132 pnode->grantOutbound.Release();
1134 // close socket and cleanup
1135 pnode->CloseSocketDisconnect();
1137 // hold in disconnected pool until all refs are released
1138 pnode->Release();
1139 vNodesDisconnected.push_back(pnode);
1144 // Delete disconnected nodes
1145 std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1146 BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
1148 // wait until threads are done using it
1149 if (pnode->GetRefCount() <= 0) {
1150 bool fDelete = false;
1152 TRY_LOCK(pnode->cs_inventory, lockInv);
1153 if (lockInv) {
1154 TRY_LOCK(pnode->cs_vSend, lockSend);
1155 if (lockSend) {
1156 fDelete = true;
1160 if (fDelete) {
1161 vNodesDisconnected.remove(pnode);
1162 DeleteNode(pnode);
1167 size_t vNodesSize;
1169 LOCK(cs_vNodes);
1170 vNodesSize = vNodes.size();
1172 if(vNodesSize != nPrevNodeCount) {
1173 nPrevNodeCount = vNodesSize;
1174 if(clientInterface)
1175 clientInterface->NotifyNumConnectionsChanged(nPrevNodeCount);
1179 // Find which sockets have data to receive
1181 struct timeval timeout;
1182 timeout.tv_sec = 0;
1183 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
1185 fd_set fdsetRecv;
1186 fd_set fdsetSend;
1187 fd_set fdsetError;
1188 FD_ZERO(&fdsetRecv);
1189 FD_ZERO(&fdsetSend);
1190 FD_ZERO(&fdsetError);
1191 SOCKET hSocketMax = 0;
1192 bool have_fds = false;
1194 BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) {
1195 FD_SET(hListenSocket.socket, &fdsetRecv);
1196 hSocketMax = std::max(hSocketMax, hListenSocket.socket);
1197 have_fds = true;
1201 LOCK(cs_vNodes);
1202 BOOST_FOREACH(CNode* pnode, vNodes)
1204 // Implement the following logic:
1205 // * If there is data to send, select() for sending data. As this only
1206 // happens when optimistic write failed, we choose to first drain the
1207 // write buffer in this case before receiving more. This avoids
1208 // needlessly queueing received data, if the remote peer is not themselves
1209 // receiving data. This means properly utilizing TCP flow control signalling.
1210 // * Otherwise, if there is space left in the receive buffer, select() for
1211 // receiving data.
1212 // * Hand off all complete messages to the processor, to be handled without
1213 // blocking here.
1215 bool select_recv = !pnode->fPauseRecv;
1216 bool select_send;
1218 LOCK(pnode->cs_vSend);
1219 select_send = !pnode->vSendMsg.empty();
1222 LOCK(pnode->cs_hSocket);
1223 if (pnode->hSocket == INVALID_SOCKET)
1224 continue;
1226 FD_SET(pnode->hSocket, &fdsetError);
1227 hSocketMax = std::max(hSocketMax, pnode->hSocket);
1228 have_fds = true;
1230 if (select_send) {
1231 FD_SET(pnode->hSocket, &fdsetSend);
1232 continue;
1234 if (select_recv) {
1235 FD_SET(pnode->hSocket, &fdsetRecv);
1240 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
1241 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1242 if (interruptNet)
1243 return;
1245 if (nSelect == SOCKET_ERROR)
1247 if (have_fds)
1249 int nErr = WSAGetLastError();
1250 LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1251 for (unsigned int i = 0; i <= hSocketMax; i++)
1252 FD_SET(i, &fdsetRecv);
1254 FD_ZERO(&fdsetSend);
1255 FD_ZERO(&fdsetError);
1256 if (!interruptNet.sleep_for(std::chrono::milliseconds(timeout.tv_usec/1000)))
1257 return;
1261 // Accept new connections
1263 BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket)
1265 if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
1267 AcceptConnection(hListenSocket);
1272 // Service each socket
1274 std::vector<CNode*> vNodesCopy;
1276 LOCK(cs_vNodes);
1277 vNodesCopy = vNodes;
1278 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1279 pnode->AddRef();
1281 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1283 if (interruptNet)
1284 return;
1287 // Receive
1289 bool recvSet = false;
1290 bool sendSet = false;
1291 bool errorSet = false;
1293 LOCK(pnode->cs_hSocket);
1294 if (pnode->hSocket == INVALID_SOCKET)
1295 continue;
1296 recvSet = FD_ISSET(pnode->hSocket, &fdsetRecv);
1297 sendSet = FD_ISSET(pnode->hSocket, &fdsetSend);
1298 errorSet = FD_ISSET(pnode->hSocket, &fdsetError);
1300 if (recvSet || errorSet)
1304 // typical socket buffer is 8K-64K
1305 char pchBuf[0x10000];
1306 int nBytes = 0;
1308 LOCK(pnode->cs_hSocket);
1309 if (pnode->hSocket == INVALID_SOCKET)
1310 continue;
1311 nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1313 if (nBytes > 0)
1315 bool notify = false;
1316 if (!pnode->ReceiveMsgBytes(pchBuf, nBytes, notify))
1317 pnode->CloseSocketDisconnect();
1318 RecordBytesRecv(nBytes);
1319 if (notify) {
1320 size_t nSizeAdded = 0;
1321 auto it(pnode->vRecvMsg.begin());
1322 for (; it != pnode->vRecvMsg.end(); ++it) {
1323 if (!it->complete())
1324 break;
1325 nSizeAdded += it->vRecv.size() + CMessageHeader::HEADER_SIZE;
1328 LOCK(pnode->cs_vProcessMsg);
1329 pnode->vProcessMsg.splice(pnode->vProcessMsg.end(), pnode->vRecvMsg, pnode->vRecvMsg.begin(), it);
1330 pnode->nProcessQueueSize += nSizeAdded;
1331 pnode->fPauseRecv = pnode->nProcessQueueSize > nReceiveFloodSize;
1333 WakeMessageHandler();
1336 else if (nBytes == 0)
1338 // socket closed gracefully
1339 if (!pnode->fDisconnect) {
1340 LogPrint(BCLog::NET, "socket closed\n");
1342 pnode->CloseSocketDisconnect();
1344 else if (nBytes < 0)
1346 // error
1347 int nErr = WSAGetLastError();
1348 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1350 if (!pnode->fDisconnect)
1351 LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
1352 pnode->CloseSocketDisconnect();
1360 // Send
1362 if (sendSet)
1364 LOCK(pnode->cs_vSend);
1365 size_t nBytes = SocketSendData(pnode);
1366 if (nBytes) {
1367 RecordBytesSent(nBytes);
1372 // Inactivity checking
1374 int64_t nTime = GetSystemTimeInSeconds();
1375 if (nTime - pnode->nTimeConnected > 60)
1377 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1379 LogPrint(BCLog::NET, "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
1380 pnode->fDisconnect = true;
1382 else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
1384 LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
1385 pnode->fDisconnect = true;
1387 else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
1389 LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
1390 pnode->fDisconnect = true;
1392 else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
1394 LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
1395 pnode->fDisconnect = true;
1397 else if (!pnode->fSuccessfullyConnected)
1399 LogPrintf("version handshake timeout from %d\n", pnode->id);
1400 pnode->fDisconnect = true;
1405 LOCK(cs_vNodes);
1406 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1407 pnode->Release();
1412 void CConnman::WakeMessageHandler()
1415 std::lock_guard<std::mutex> lock(mutexMsgProc);
1416 fMsgProcWake = true;
1418 condMsgProc.notify_one();
1426 #ifdef USE_UPNP
1427 void ThreadMapPort()
1429 std::string port = strprintf("%u", GetListenPort());
1430 const char * multicastif = 0;
1431 const char * minissdpdpath = 0;
1432 struct UPNPDev * devlist = 0;
1433 char lanaddr[64];
1435 #ifndef UPNPDISCOVER_SUCCESS
1436 /* miniupnpc 1.5 */
1437 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1438 #elif MINIUPNPC_API_VERSION < 14
1439 /* miniupnpc 1.6 */
1440 int error = 0;
1441 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1442 #else
1443 /* miniupnpc 1.9.20150730 */
1444 int error = 0;
1445 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
1446 #endif
1448 struct UPNPUrls urls;
1449 struct IGDdatas data;
1450 int r;
1452 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1453 if (r == 1)
1455 if (fDiscover) {
1456 char externalIPAddress[40];
1457 r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1458 if(r != UPNPCOMMAND_SUCCESS)
1459 LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
1460 else
1462 if(externalIPAddress[0])
1464 CNetAddr resolved;
1465 if(LookupHost(externalIPAddress, resolved, false)) {
1466 LogPrintf("UPnP: ExternalIPAddress = %s\n", resolved.ToString().c_str());
1467 AddLocal(resolved, LOCAL_UPNP);
1470 else
1471 LogPrintf("UPnP: GetExternalIPAddress failed.\n");
1475 std::string strDesc = "Bitcoin " + FormatFullVersion();
1477 try {
1478 while (true) {
1479 #ifndef UPNPDISCOVER_SUCCESS
1480 /* miniupnpc 1.5 */
1481 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1482 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1483 #else
1484 /* miniupnpc 1.6 */
1485 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1486 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1487 #endif
1489 if(r!=UPNPCOMMAND_SUCCESS)
1490 LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1491 port, port, lanaddr, r, strupnperror(r));
1492 else
1493 LogPrintf("UPnP Port Mapping successful.\n");
1495 MilliSleep(20*60*1000); // Refresh every 20 minutes
1498 catch (const boost::thread_interrupted&)
1500 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1501 LogPrintf("UPNP_DeletePortMapping() returned: %d\n", r);
1502 freeUPNPDevlist(devlist); devlist = 0;
1503 FreeUPNPUrls(&urls);
1504 throw;
1506 } else {
1507 LogPrintf("No valid UPnP IGDs found\n");
1508 freeUPNPDevlist(devlist); devlist = 0;
1509 if (r != 0)
1510 FreeUPNPUrls(&urls);
1514 void MapPort(bool fUseUPnP)
1516 static boost::thread* upnp_thread = NULL;
1518 if (fUseUPnP)
1520 if (upnp_thread) {
1521 upnp_thread->interrupt();
1522 upnp_thread->join();
1523 delete upnp_thread;
1525 upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
1527 else if (upnp_thread) {
1528 upnp_thread->interrupt();
1529 upnp_thread->join();
1530 delete upnp_thread;
1531 upnp_thread = NULL;
1535 #else
1536 void MapPort(bool)
1538 // Intentionally left blank.
1540 #endif
1547 static std::string GetDNSHost(const CDNSSeedData& data, ServiceFlags* requiredServiceBits)
1549 //use default host for non-filter-capable seeds or if we use the default service bits (NODE_NETWORK)
1550 if (!data.supportsServiceBitsFiltering || *requiredServiceBits == NODE_NETWORK) {
1551 *requiredServiceBits = NODE_NETWORK;
1552 return data.host;
1555 // See chainparams.cpp, most dnsseeds only support one or two possible servicebits hostnames
1556 return strprintf("x%x.%s", *requiredServiceBits, data.host);
1560 void CConnman::ThreadDNSAddressSeed()
1562 // goal: only query DNS seeds if address need is acute
1563 // Avoiding DNS seeds when we don't need them improves user privacy by
1564 // creating fewer identifying DNS requests, reduces trust by giving seeds
1565 // less influence on the network topology, and reduces traffic to the seeds.
1566 if ((addrman.size() > 0) &&
1567 (!GetBoolArg("-forcednsseed", DEFAULT_FORCEDNSSEED))) {
1568 if (!interruptNet.sleep_for(std::chrono::seconds(11)))
1569 return;
1571 LOCK(cs_vNodes);
1572 int nRelevant = 0;
1573 for (auto pnode : vNodes) {
1574 nRelevant += pnode->fSuccessfullyConnected && ((pnode->nServices & nRelevantServices) == nRelevantServices);
1576 if (nRelevant >= 2) {
1577 LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1578 return;
1582 const std::vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
1583 int found = 0;
1585 LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1587 BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
1588 if (HaveNameProxy()) {
1589 AddOneShot(seed.host);
1590 } else {
1591 std::vector<CNetAddr> vIPs;
1592 std::vector<CAddress> vAdd;
1593 ServiceFlags requiredServiceBits = nRelevantServices;
1594 if (LookupHost(GetDNSHost(seed, &requiredServiceBits).c_str(), vIPs, 0, true))
1596 BOOST_FOREACH(const CNetAddr& ip, vIPs)
1598 int nOneDay = 24*3600;
1599 CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()), requiredServiceBits);
1600 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1601 vAdd.push_back(addr);
1602 found++;
1605 // TODO: The seed name resolve may fail, yielding an IP of [::], which results in
1606 // addrman assigning the same source to results from different seeds.
1607 // This should switch to a hard-coded stable dummy IP for each seed name, so that the
1608 // resolve is not required at all.
1609 if (!vIPs.empty()) {
1610 CService seedSource;
1611 Lookup(seed.name.c_str(), seedSource, 0, true);
1612 addrman.Add(vAdd, seedSource);
1617 LogPrintf("%d addresses found from DNS seeds\n", found);
1631 void CConnman::DumpAddresses()
1633 int64_t nStart = GetTimeMillis();
1635 CAddrDB adb;
1636 adb.Write(addrman);
1638 LogPrint(BCLog::NET, "Flushed %d addresses to peers.dat %dms\n",
1639 addrman.size(), GetTimeMillis() - nStart);
1642 void CConnman::DumpData()
1644 DumpAddresses();
1645 DumpBanlist();
1648 void CConnman::ProcessOneShot()
1650 std::string strDest;
1652 LOCK(cs_vOneShots);
1653 if (vOneShots.empty())
1654 return;
1655 strDest = vOneShots.front();
1656 vOneShots.pop_front();
1658 CAddress addr;
1659 CSemaphoreGrant grant(*semOutbound, true);
1660 if (grant) {
1661 if (!OpenNetworkConnection(addr, false, &grant, strDest.c_str(), true))
1662 AddOneShot(strDest);
1666 void CConnman::ThreadOpenConnections()
1668 // Connect to specific addresses
1669 if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0)
1671 for (int64_t nLoop = 0;; nLoop++)
1673 ProcessOneShot();
1674 BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-connect"))
1676 CAddress addr(CService(), NODE_NONE);
1677 OpenNetworkConnection(addr, false, NULL, strAddr.c_str());
1678 for (int i = 0; i < 10 && i < nLoop; i++)
1680 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1681 return;
1684 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1685 return;
1689 // Initiate network connections
1690 int64_t nStart = GetTime();
1692 // Minimum time before next feeler connection (in microseconds).
1693 int64_t nNextFeeler = PoissonNextSend(nStart*1000*1000, FEELER_INTERVAL);
1694 while (!interruptNet)
1696 ProcessOneShot();
1698 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1699 return;
1701 CSemaphoreGrant grant(*semOutbound);
1702 if (interruptNet)
1703 return;
1705 // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1706 if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1707 static bool done = false;
1708 if (!done) {
1709 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1710 CNetAddr local;
1711 LookupHost("127.0.0.1", local, false);
1712 addrman.Add(convertSeed6(Params().FixedSeeds()), local);
1713 done = true;
1718 // Choose an address to connect to based on most recently seen
1720 CAddress addrConnect;
1722 // Only connect out to one peer per network group (/16 for IPv4).
1723 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1724 int nOutbound = 0;
1725 std::set<std::vector<unsigned char> > setConnected;
1727 LOCK(cs_vNodes);
1728 BOOST_FOREACH(CNode* pnode, vNodes) {
1729 if (!pnode->fInbound && !pnode->fAddnode) {
1730 // Netgroups for inbound and addnode peers are not excluded because our goal here
1731 // is to not use multiple of our limited outbound slots on a single netgroup
1732 // but inbound and addnode peers do not use our outbound slots. Inbound peers
1733 // also have the added issue that they're attacker controlled and could be used
1734 // to prevent us from connecting to particular hosts if we used them here.
1735 setConnected.insert(pnode->addr.GetGroup());
1736 nOutbound++;
1741 // Feeler Connections
1743 // Design goals:
1744 // * Increase the number of connectable addresses in the tried table.
1746 // Method:
1747 // * Choose a random address from new and attempt to connect to it if we can connect
1748 // successfully it is added to tried.
1749 // * Start attempting feeler connections only after node finishes making outbound
1750 // connections.
1751 // * Only make a feeler connection once every few minutes.
1753 bool fFeeler = false;
1754 if (nOutbound >= nMaxOutbound) {
1755 int64_t nTime = GetTimeMicros(); // The current time right now (in microseconds).
1756 if (nTime > nNextFeeler) {
1757 nNextFeeler = PoissonNextSend(nTime, FEELER_INTERVAL);
1758 fFeeler = true;
1759 } else {
1760 continue;
1764 int64_t nANow = GetAdjustedTime();
1765 int nTries = 0;
1766 while (!interruptNet)
1768 CAddrInfo addr = addrman.Select(fFeeler);
1770 // if we selected an invalid address, restart
1771 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1772 break;
1774 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1775 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1776 // already-connected network ranges, ...) before trying new addrman addresses.
1777 nTries++;
1778 if (nTries > 100)
1779 break;
1781 if (IsLimited(addr))
1782 continue;
1784 // only connect to full nodes
1785 if ((addr.nServices & REQUIRED_SERVICES) != REQUIRED_SERVICES)
1786 continue;
1788 // only consider very recently tried nodes after 30 failed attempts
1789 if (nANow - addr.nLastTry < 600 && nTries < 30)
1790 continue;
1792 // only consider nodes missing relevant services after 40 failed attempts and only if less than half the outbound are up.
1793 if ((addr.nServices & nRelevantServices) != nRelevantServices && (nTries < 40 || nOutbound >= (nMaxOutbound >> 1)))
1794 continue;
1796 // do not allow non-default ports, unless after 50 invalid addresses selected already
1797 if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1798 continue;
1800 addrConnect = addr;
1801 break;
1804 if (addrConnect.IsValid()) {
1806 if (fFeeler) {
1807 // Add small amount of random noise before connection to avoid synchronization.
1808 int randsleep = GetRandInt(FEELER_SLEEP_WINDOW * 1000);
1809 if (!interruptNet.sleep_for(std::chrono::milliseconds(randsleep)))
1810 return;
1811 LogPrint(BCLog::NET, "Making feeler connection to %s\n", addrConnect.ToString());
1814 OpenNetworkConnection(addrConnect, (int)setConnected.size() >= std::min(nMaxConnections - 1, 2), &grant, NULL, false, fFeeler);
1819 std::vector<AddedNodeInfo> CConnman::GetAddedNodeInfo()
1821 std::vector<AddedNodeInfo> ret;
1823 std::list<std::string> lAddresses(0);
1825 LOCK(cs_vAddedNodes);
1826 ret.reserve(vAddedNodes.size());
1827 BOOST_FOREACH(const std::string& strAddNode, vAddedNodes)
1828 lAddresses.push_back(strAddNode);
1832 // Build a map of all already connected addresses (by IP:port and by name) to inbound/outbound and resolved CService
1833 std::map<CService, bool> mapConnected;
1834 std::map<std::string, std::pair<bool, CService>> mapConnectedByName;
1836 LOCK(cs_vNodes);
1837 for (const CNode* pnode : vNodes) {
1838 if (pnode->addr.IsValid()) {
1839 mapConnected[pnode->addr] = pnode->fInbound;
1841 std::string addrName = pnode->GetAddrName();
1842 if (!addrName.empty()) {
1843 mapConnectedByName[std::move(addrName)] = std::make_pair(pnode->fInbound, static_cast<const CService&>(pnode->addr));
1848 BOOST_FOREACH(const std::string& strAddNode, lAddresses) {
1849 CService service(LookupNumeric(strAddNode.c_str(), Params().GetDefaultPort()));
1850 if (service.IsValid()) {
1851 // strAddNode is an IP:port
1852 auto it = mapConnected.find(service);
1853 if (it != mapConnected.end()) {
1854 ret.push_back(AddedNodeInfo{strAddNode, service, true, it->second});
1855 } else {
1856 ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
1858 } else {
1859 // strAddNode is a name
1860 auto it = mapConnectedByName.find(strAddNode);
1861 if (it != mapConnectedByName.end()) {
1862 ret.push_back(AddedNodeInfo{strAddNode, it->second.second, true, it->second.first});
1863 } else {
1864 ret.push_back(AddedNodeInfo{strAddNode, CService(), false, false});
1869 return ret;
1872 void CConnman::ThreadOpenAddedConnections()
1875 LOCK(cs_vAddedNodes);
1876 if (mapMultiArgs.count("-addnode"))
1877 vAddedNodes = mapMultiArgs.at("-addnode");
1880 while (true)
1882 CSemaphoreGrant grant(*semAddnode);
1883 std::vector<AddedNodeInfo> vInfo = GetAddedNodeInfo();
1884 bool tried = false;
1885 for (const AddedNodeInfo& info : vInfo) {
1886 if (!info.fConnected) {
1887 if (!grant.TryAcquire()) {
1888 // If we've used up our semaphore and need a new one, lets not wait here since while we are waiting
1889 // the addednodeinfo state might change.
1890 break;
1892 // If strAddedNode is an IP/port, decode it immediately, so
1893 // OpenNetworkConnection can detect existing connections to that IP/port.
1894 tried = true;
1895 CService service(LookupNumeric(info.strAddedNode.c_str(), Params().GetDefaultPort()));
1896 OpenNetworkConnection(CAddress(service, NODE_NONE), false, &grant, info.strAddedNode.c_str(), false, false, true);
1897 if (!interruptNet.sleep_for(std::chrono::milliseconds(500)))
1898 return;
1901 // Retry every 60 seconds if a connection was attempted, otherwise two seconds
1902 if (!interruptNet.sleep_for(std::chrono::seconds(tried ? 60 : 2)))
1903 return;
1907 // if successful, this moves the passed grant to the constructed node
1908 bool CConnman::OpenNetworkConnection(const CAddress& addrConnect, bool fCountFailure, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot, bool fFeeler, bool fAddnode)
1911 // Initiate outbound network connection
1913 if (interruptNet) {
1914 return false;
1916 if (!fNetworkActive) {
1917 return false;
1919 if (!pszDest) {
1920 if (IsLocal(addrConnect) ||
1921 FindNode((CNetAddr)addrConnect) || IsBanned(addrConnect) ||
1922 FindNode(addrConnect.ToStringIPPort()))
1923 return false;
1924 } else if (FindNode(std::string(pszDest)))
1925 return false;
1927 CNode* pnode = ConnectNode(addrConnect, pszDest, fCountFailure);
1929 if (!pnode)
1930 return false;
1931 if (grantOutbound)
1932 grantOutbound->MoveTo(pnode->grantOutbound);
1933 if (fOneShot)
1934 pnode->fOneShot = true;
1935 if (fFeeler)
1936 pnode->fFeeler = true;
1937 if (fAddnode)
1938 pnode->fAddnode = true;
1940 GetNodeSignals().InitializeNode(pnode, *this);
1942 LOCK(cs_vNodes);
1943 vNodes.push_back(pnode);
1946 return true;
1949 void CConnman::ThreadMessageHandler()
1951 while (!flagInterruptMsgProc)
1953 std::vector<CNode*> vNodesCopy;
1955 LOCK(cs_vNodes);
1956 vNodesCopy = vNodes;
1957 BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1958 pnode->AddRef();
1962 bool fMoreWork = false;
1964 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1966 if (pnode->fDisconnect)
1967 continue;
1969 // Receive messages
1970 bool fMoreNodeWork = GetNodeSignals().ProcessMessages(pnode, *this, flagInterruptMsgProc);
1971 fMoreWork |= (fMoreNodeWork && !pnode->fPauseSend);
1972 if (flagInterruptMsgProc)
1973 return;
1975 // Send messages
1977 LOCK(pnode->cs_sendProcessing);
1978 GetNodeSignals().SendMessages(pnode, *this, flagInterruptMsgProc);
1980 if (flagInterruptMsgProc)
1981 return;
1985 LOCK(cs_vNodes);
1986 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1987 pnode->Release();
1990 std::unique_lock<std::mutex> lock(mutexMsgProc);
1991 if (!fMoreWork) {
1992 condMsgProc.wait_until(lock, std::chrono::steady_clock::now() + std::chrono::milliseconds(100), [this] { return fMsgProcWake; });
1994 fMsgProcWake = false;
2003 bool CConnman::BindListenPort(const CService &addrBind, std::string& strError, bool fWhitelisted)
2005 strError = "";
2006 int nOne = 1;
2008 // Create socket for listening for incoming connections
2009 struct sockaddr_storage sockaddr;
2010 socklen_t len = sizeof(sockaddr);
2011 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
2013 strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
2014 LogPrintf("%s\n", strError);
2015 return false;
2018 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
2019 if (hListenSocket == INVALID_SOCKET)
2021 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
2022 LogPrintf("%s\n", strError);
2023 return false;
2025 if (!IsSelectableSocket(hListenSocket))
2027 strError = "Error: Couldn't create a listenable socket for incoming connections";
2028 LogPrintf("%s\n", strError);
2029 return false;
2033 #ifndef WIN32
2034 #ifdef SO_NOSIGPIPE
2035 // Different way of disabling SIGPIPE on BSD
2036 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
2037 #endif
2038 // Allow binding if the port is still in TIME_WAIT state after
2039 // the program was closed and restarted.
2040 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
2041 // Disable Nagle's algorithm
2042 setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int));
2043 #else
2044 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int));
2045 setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int));
2046 #endif
2048 // Set to non-blocking, incoming connections will also inherit this
2049 if (!SetSocketNonBlocking(hListenSocket, true)) {
2050 strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
2051 LogPrintf("%s\n", strError);
2052 return false;
2055 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
2056 // and enable it by default or not. Try to enable it, if possible.
2057 if (addrBind.IsIPv6()) {
2058 #ifdef IPV6_V6ONLY
2059 #ifdef WIN32
2060 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
2061 #else
2062 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
2063 #endif
2064 #endif
2065 #ifdef WIN32
2066 int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
2067 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
2068 #endif
2071 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
2073 int nErr = WSAGetLastError();
2074 if (nErr == WSAEADDRINUSE)
2075 strError = strprintf(_("Unable to bind to %s on this computer. %s is probably already running."), addrBind.ToString(), _(PACKAGE_NAME));
2076 else
2077 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
2078 LogPrintf("%s\n", strError);
2079 CloseSocket(hListenSocket);
2080 return false;
2082 LogPrintf("Bound to %s\n", addrBind.ToString());
2084 // Listen for incoming connections
2085 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
2087 strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
2088 LogPrintf("%s\n", strError);
2089 CloseSocket(hListenSocket);
2090 return false;
2093 vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
2095 if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
2096 AddLocal(addrBind, LOCAL_BIND);
2098 return true;
2101 void Discover(boost::thread_group& threadGroup)
2103 if (!fDiscover)
2104 return;
2106 #ifdef WIN32
2107 // Get local host IP
2108 char pszHostName[256] = "";
2109 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
2111 std::vector<CNetAddr> vaddr;
2112 if (LookupHost(pszHostName, vaddr, 0, true))
2114 BOOST_FOREACH (const CNetAddr &addr, vaddr)
2116 if (AddLocal(addr, LOCAL_IF))
2117 LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
2121 #else
2122 // Get local host ip
2123 struct ifaddrs* myaddrs;
2124 if (getifaddrs(&myaddrs) == 0)
2126 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
2128 if (ifa->ifa_addr == NULL) continue;
2129 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
2130 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
2131 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
2132 if (ifa->ifa_addr->sa_family == AF_INET)
2134 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
2135 CNetAddr addr(s4->sin_addr);
2136 if (AddLocal(addr, LOCAL_IF))
2137 LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2139 else if (ifa->ifa_addr->sa_family == AF_INET6)
2141 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
2142 CNetAddr addr(s6->sin6_addr);
2143 if (AddLocal(addr, LOCAL_IF))
2144 LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
2147 freeifaddrs(myaddrs);
2149 #endif
2152 void CConnman::SetNetworkActive(bool active)
2154 LogPrint(BCLog::NET, "SetNetworkActive: %s\n", active);
2156 if (!active) {
2157 fNetworkActive = false;
2159 LOCK(cs_vNodes);
2160 // Close sockets to all nodes
2161 BOOST_FOREACH(CNode* pnode, vNodes) {
2162 pnode->CloseSocketDisconnect();
2164 } else {
2165 fNetworkActive = true;
2168 uiInterface.NotifyNetworkActiveChanged(fNetworkActive);
2171 CConnman::CConnman(uint64_t nSeed0In, uint64_t nSeed1In) : nSeed0(nSeed0In), nSeed1(nSeed1In)
2173 fNetworkActive = true;
2174 setBannedIsDirty = false;
2175 fAddressesInitialized = false;
2176 nLastNodeId = 0;
2177 nSendBufferMaxSize = 0;
2178 nReceiveFloodSize = 0;
2179 semOutbound = NULL;
2180 semAddnode = NULL;
2181 nMaxConnections = 0;
2182 nMaxOutbound = 0;
2183 nMaxAddnode = 0;
2184 nBestHeight = 0;
2185 clientInterface = NULL;
2186 flagInterruptMsgProc = false;
2189 NodeId CConnman::GetNewNodeId()
2191 return nLastNodeId.fetch_add(1, std::memory_order_relaxed);
2194 bool CConnman::Start(CScheduler& scheduler, std::string& strNodeError, Options connOptions)
2196 nTotalBytesRecv = 0;
2197 nTotalBytesSent = 0;
2198 nMaxOutboundTotalBytesSentInCycle = 0;
2199 nMaxOutboundCycleStartTime = 0;
2201 nRelevantServices = connOptions.nRelevantServices;
2202 nLocalServices = connOptions.nLocalServices;
2203 nMaxConnections = connOptions.nMaxConnections;
2204 nMaxOutbound = std::min((connOptions.nMaxOutbound), nMaxConnections);
2205 nMaxAddnode = connOptions.nMaxAddnode;
2206 nMaxFeeler = connOptions.nMaxFeeler;
2208 nSendBufferMaxSize = connOptions.nSendBufferMaxSize;
2209 nReceiveFloodSize = connOptions.nReceiveFloodSize;
2211 nMaxOutboundLimit = connOptions.nMaxOutboundLimit;
2212 nMaxOutboundTimeframe = connOptions.nMaxOutboundTimeframe;
2214 SetBestHeight(connOptions.nBestHeight);
2216 clientInterface = connOptions.uiInterface;
2217 if (clientInterface) {
2218 clientInterface->InitMessage(_("Loading P2P addresses..."));
2220 // Load addresses from peers.dat
2221 int64_t nStart = GetTimeMillis();
2223 CAddrDB adb;
2224 if (adb.Read(addrman))
2225 LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart);
2226 else {
2227 addrman.Clear(); // Addrman can be in an inconsistent state after failure, reset it
2228 LogPrintf("Invalid or missing peers.dat; recreating\n");
2229 DumpAddresses();
2232 if (clientInterface)
2233 clientInterface->InitMessage(_("Loading banlist..."));
2234 // Load addresses from banlist.dat
2235 nStart = GetTimeMillis();
2236 CBanDB bandb;
2237 banmap_t banmap;
2238 if (bandb.Read(banmap)) {
2239 SetBanned(banmap); // thread save setter
2240 SetBannedSetDirty(false); // no need to write down, just read data
2241 SweepBanned(); // sweep out unused entries
2243 LogPrint(BCLog::NET, "Loaded %d banned node ips/subnets from banlist.dat %dms\n",
2244 banmap.size(), GetTimeMillis() - nStart);
2245 } else {
2246 LogPrintf("Invalid or missing banlist.dat; recreating\n");
2247 SetBannedSetDirty(true); // force write
2248 DumpBanlist();
2251 uiInterface.InitMessage(_("Starting network threads..."));
2253 fAddressesInitialized = true;
2255 if (semOutbound == NULL) {
2256 // initialize semaphore
2257 semOutbound = new CSemaphore(std::min((nMaxOutbound + nMaxFeeler), nMaxConnections));
2259 if (semAddnode == NULL) {
2260 // initialize semaphore
2261 semAddnode = new CSemaphore(nMaxAddnode);
2265 // Start threads
2267 InterruptSocks5(false);
2268 interruptNet.reset();
2269 flagInterruptMsgProc = false;
2272 std::unique_lock<std::mutex> lock(mutexMsgProc);
2273 fMsgProcWake = false;
2276 // Send and receive from sockets, accept connections
2277 threadSocketHandler = std::thread(&TraceThread<std::function<void()> >, "net", std::function<void()>(std::bind(&CConnman::ThreadSocketHandler, this)));
2279 if (!GetBoolArg("-dnsseed", true))
2280 LogPrintf("DNS seeding disabled\n");
2281 else
2282 threadDNSAddressSeed = std::thread(&TraceThread<std::function<void()> >, "dnsseed", std::function<void()>(std::bind(&CConnman::ThreadDNSAddressSeed, this)));
2284 // Initiate outbound connections from -addnode
2285 threadOpenAddedConnections = std::thread(&TraceThread<std::function<void()> >, "addcon", std::function<void()>(std::bind(&CConnman::ThreadOpenAddedConnections, this)));
2287 // Initiate outbound connections unless connect=0
2288 if (!mapMultiArgs.count("-connect") || mapMultiArgs.at("-connect").size() != 1 || mapMultiArgs.at("-connect")[0] != "0")
2289 threadOpenConnections = std::thread(&TraceThread<std::function<void()> >, "opencon", std::function<void()>(std::bind(&CConnman::ThreadOpenConnections, this)));
2291 // Process messages
2292 threadMessageHandler = std::thread(&TraceThread<std::function<void()> >, "msghand", std::function<void()>(std::bind(&CConnman::ThreadMessageHandler, this)));
2294 // Dump network addresses
2295 scheduler.scheduleEvery(std::bind(&CConnman::DumpData, this), DUMP_ADDRESSES_INTERVAL * 1000);
2297 return true;
2300 class CNetCleanup
2302 public:
2303 CNetCleanup() {}
2305 ~CNetCleanup()
2307 #ifdef WIN32
2308 // Shutdown Windows Sockets
2309 WSACleanup();
2310 #endif
2313 instance_of_cnetcleanup;
2315 void CConnman::Interrupt()
2318 std::lock_guard<std::mutex> lock(mutexMsgProc);
2319 flagInterruptMsgProc = true;
2321 condMsgProc.notify_all();
2323 interruptNet();
2324 InterruptSocks5(true);
2326 if (semOutbound) {
2327 for (int i=0; i<(nMaxOutbound + nMaxFeeler); i++) {
2328 semOutbound->post();
2332 if (semAddnode) {
2333 for (int i=0; i<nMaxAddnode; i++) {
2334 semAddnode->post();
2339 void CConnman::Stop()
2341 if (threadMessageHandler.joinable())
2342 threadMessageHandler.join();
2343 if (threadOpenConnections.joinable())
2344 threadOpenConnections.join();
2345 if (threadOpenAddedConnections.joinable())
2346 threadOpenAddedConnections.join();
2347 if (threadDNSAddressSeed.joinable())
2348 threadDNSAddressSeed.join();
2349 if (threadSocketHandler.joinable())
2350 threadSocketHandler.join();
2352 if (fAddressesInitialized)
2354 DumpData();
2355 fAddressesInitialized = false;
2358 // Close sockets
2359 BOOST_FOREACH(CNode* pnode, vNodes)
2360 pnode->CloseSocketDisconnect();
2361 BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket)
2362 if (hListenSocket.socket != INVALID_SOCKET)
2363 if (!CloseSocket(hListenSocket.socket))
2364 LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
2366 // clean up some globals (to help leak detection)
2367 BOOST_FOREACH(CNode *pnode, vNodes) {
2368 DeleteNode(pnode);
2370 BOOST_FOREACH(CNode *pnode, vNodesDisconnected) {
2371 DeleteNode(pnode);
2373 vNodes.clear();
2374 vNodesDisconnected.clear();
2375 vhListenSocket.clear();
2376 delete semOutbound;
2377 semOutbound = NULL;
2378 delete semAddnode;
2379 semAddnode = NULL;
2382 void CConnman::DeleteNode(CNode* pnode)
2384 assert(pnode);
2385 bool fUpdateConnectionTime = false;
2386 GetNodeSignals().FinalizeNode(pnode->GetId(), fUpdateConnectionTime);
2387 if(fUpdateConnectionTime)
2388 addrman.Connected(pnode->addr);
2389 delete pnode;
2392 CConnman::~CConnman()
2394 Interrupt();
2395 Stop();
2398 size_t CConnman::GetAddressCount() const
2400 return addrman.size();
2403 void CConnman::SetServices(const CService &addr, ServiceFlags nServices)
2405 addrman.SetServices(addr, nServices);
2408 void CConnman::MarkAddressGood(const CAddress& addr)
2410 addrman.Good(addr);
2413 void CConnman::AddNewAddresses(const std::vector<CAddress>& vAddr, const CAddress& addrFrom, int64_t nTimePenalty)
2415 addrman.Add(vAddr, addrFrom, nTimePenalty);
2418 std::vector<CAddress> CConnman::GetAddresses()
2420 return addrman.GetAddr();
2423 bool CConnman::AddNode(const std::string& strNode)
2425 LOCK(cs_vAddedNodes);
2426 for(std::vector<std::string>::const_iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
2427 if (strNode == *it)
2428 return false;
2431 vAddedNodes.push_back(strNode);
2432 return true;
2435 bool CConnman::RemoveAddedNode(const std::string& strNode)
2437 LOCK(cs_vAddedNodes);
2438 for(std::vector<std::string>::iterator it = vAddedNodes.begin(); it != vAddedNodes.end(); ++it) {
2439 if (strNode == *it) {
2440 vAddedNodes.erase(it);
2441 return true;
2444 return false;
2447 size_t CConnman::GetNodeCount(NumConnections flags)
2449 LOCK(cs_vNodes);
2450 if (flags == CConnman::CONNECTIONS_ALL) // Shortcut if we want total
2451 return vNodes.size();
2453 int nNum = 0;
2454 for(std::vector<CNode*>::const_iterator it = vNodes.begin(); it != vNodes.end(); ++it)
2455 if (flags & ((*it)->fInbound ? CONNECTIONS_IN : CONNECTIONS_OUT))
2456 nNum++;
2458 return nNum;
2461 void CConnman::GetNodeStats(std::vector<CNodeStats>& vstats)
2463 vstats.clear();
2464 LOCK(cs_vNodes);
2465 vstats.reserve(vNodes.size());
2466 for(std::vector<CNode*>::iterator it = vNodes.begin(); it != vNodes.end(); ++it) {
2467 CNode* pnode = *it;
2468 vstats.emplace_back();
2469 pnode->copyStats(vstats.back());
2473 bool CConnman::DisconnectNode(const std::string& strNode)
2475 LOCK(cs_vNodes);
2476 if (CNode* pnode = FindNode(strNode)) {
2477 pnode->fDisconnect = true;
2478 return true;
2480 return false;
2482 bool CConnman::DisconnectNode(NodeId id)
2484 LOCK(cs_vNodes);
2485 for(CNode* pnode : vNodes) {
2486 if (id == pnode->id) {
2487 pnode->fDisconnect = true;
2488 return true;
2491 return false;
2494 void CConnman::RecordBytesRecv(uint64_t bytes)
2496 LOCK(cs_totalBytesRecv);
2497 nTotalBytesRecv += bytes;
2500 void CConnman::RecordBytesSent(uint64_t bytes)
2502 LOCK(cs_totalBytesSent);
2503 nTotalBytesSent += bytes;
2505 uint64_t now = GetTime();
2506 if (nMaxOutboundCycleStartTime + nMaxOutboundTimeframe < now)
2508 // timeframe expired, reset cycle
2509 nMaxOutboundCycleStartTime = now;
2510 nMaxOutboundTotalBytesSentInCycle = 0;
2513 // TODO, exclude whitebind peers
2514 nMaxOutboundTotalBytesSentInCycle += bytes;
2517 void CConnman::SetMaxOutboundTarget(uint64_t limit)
2519 LOCK(cs_totalBytesSent);
2520 nMaxOutboundLimit = limit;
2523 uint64_t CConnman::GetMaxOutboundTarget()
2525 LOCK(cs_totalBytesSent);
2526 return nMaxOutboundLimit;
2529 uint64_t CConnman::GetMaxOutboundTimeframe()
2531 LOCK(cs_totalBytesSent);
2532 return nMaxOutboundTimeframe;
2535 uint64_t CConnman::GetMaxOutboundTimeLeftInCycle()
2537 LOCK(cs_totalBytesSent);
2538 if (nMaxOutboundLimit == 0)
2539 return 0;
2541 if (nMaxOutboundCycleStartTime == 0)
2542 return nMaxOutboundTimeframe;
2544 uint64_t cycleEndTime = nMaxOutboundCycleStartTime + nMaxOutboundTimeframe;
2545 uint64_t now = GetTime();
2546 return (cycleEndTime < now) ? 0 : cycleEndTime - GetTime();
2549 void CConnman::SetMaxOutboundTimeframe(uint64_t timeframe)
2551 LOCK(cs_totalBytesSent);
2552 if (nMaxOutboundTimeframe != timeframe)
2554 // reset measure-cycle in case of changing
2555 // the timeframe
2556 nMaxOutboundCycleStartTime = GetTime();
2558 nMaxOutboundTimeframe = timeframe;
2561 bool CConnman::OutboundTargetReached(bool historicalBlockServingLimit)
2563 LOCK(cs_totalBytesSent);
2564 if (nMaxOutboundLimit == 0)
2565 return false;
2567 if (historicalBlockServingLimit)
2569 // keep a large enough buffer to at least relay each block once
2570 uint64_t timeLeftInCycle = GetMaxOutboundTimeLeftInCycle();
2571 uint64_t buffer = timeLeftInCycle / 600 * MAX_BLOCK_SERIALIZED_SIZE;
2572 if (buffer >= nMaxOutboundLimit || nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit - buffer)
2573 return true;
2575 else if (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit)
2576 return true;
2578 return false;
2581 uint64_t CConnman::GetOutboundTargetBytesLeft()
2583 LOCK(cs_totalBytesSent);
2584 if (nMaxOutboundLimit == 0)
2585 return 0;
2587 return (nMaxOutboundTotalBytesSentInCycle >= nMaxOutboundLimit) ? 0 : nMaxOutboundLimit - nMaxOutboundTotalBytesSentInCycle;
2590 uint64_t CConnman::GetTotalBytesRecv()
2592 LOCK(cs_totalBytesRecv);
2593 return nTotalBytesRecv;
2596 uint64_t CConnman::GetTotalBytesSent()
2598 LOCK(cs_totalBytesSent);
2599 return nTotalBytesSent;
2602 ServiceFlags CConnman::GetLocalServices() const
2604 return nLocalServices;
2607 void CConnman::SetBestHeight(int height)
2609 nBestHeight.store(height, std::memory_order_release);
2612 int CConnman::GetBestHeight() const
2614 return nBestHeight.load(std::memory_order_acquire);
2617 unsigned int CConnman::GetReceiveFloodSize() const { return nReceiveFloodSize; }
2618 unsigned int CConnman::GetSendBufferSize() const{ return nSendBufferMaxSize; }
2620 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) :
2621 nTimeConnected(GetSystemTimeInSeconds()),
2622 addr(addrIn),
2623 fInbound(fInboundIn),
2624 id(idIn),
2625 nKeyedNetGroup(nKeyedNetGroupIn),
2626 addrKnown(5000, 0.001),
2627 filterInventoryKnown(50000, 0.000001),
2628 nLocalHostNonce(nLocalHostNonceIn),
2629 nLocalServices(nLocalServicesIn),
2630 nMyStartingHeight(nMyStartingHeightIn),
2631 nSendVersion(0)
2633 nServices = NODE_NONE;
2634 nServicesExpected = NODE_NONE;
2635 hSocket = hSocketIn;
2636 nRecvVersion = INIT_PROTO_VERSION;
2637 nLastSend = 0;
2638 nLastRecv = 0;
2639 nSendBytes = 0;
2640 nRecvBytes = 0;
2641 nTimeOffset = 0;
2642 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
2643 nVersion = 0;
2644 strSubVer = "";
2645 fWhitelisted = false;
2646 fOneShot = false;
2647 fAddnode = false;
2648 fClient = false; // set by version message
2649 fFeeler = false;
2650 fSuccessfullyConnected = false;
2651 fDisconnect = false;
2652 nRefCount = 0;
2653 nSendSize = 0;
2654 nSendOffset = 0;
2655 hashContinue = uint256();
2656 nStartingHeight = -1;
2657 filterInventoryKnown.reset();
2658 fSendMempool = false;
2659 fGetAddr = false;
2660 nNextLocalAddrSend = 0;
2661 nNextAddrSend = 0;
2662 nNextInvSend = 0;
2663 fRelayTxes = false;
2664 fSentAddr = false;
2665 pfilter = new CBloomFilter();
2666 timeLastMempoolReq = 0;
2667 nLastBlockTime = 0;
2668 nLastTXTime = 0;
2669 nPingNonceSent = 0;
2670 nPingUsecStart = 0;
2671 nPingUsecTime = 0;
2672 fPingQueued = false;
2673 nMinPingUsecTime = std::numeric_limits<int64_t>::max();
2674 minFeeFilter = 0;
2675 lastSentFeeFilter = 0;
2676 nextSendTimeFeeFilter = 0;
2677 fPauseRecv = false;
2678 fPauseSend = false;
2679 nProcessQueueSize = 0;
2681 BOOST_FOREACH(const std::string &msg, getAllNetMessageTypes())
2682 mapRecvBytesPerMsgCmd[msg] = 0;
2683 mapRecvBytesPerMsgCmd[NET_MESSAGE_COMMAND_OTHER] = 0;
2685 if (fLogIPs) {
2686 LogPrint(BCLog::NET, "Added connection to %s peer=%d\n", addrName, id);
2687 } else {
2688 LogPrint(BCLog::NET, "Added connection peer=%d\n", id);
2692 CNode::~CNode()
2694 CloseSocket(hSocket);
2696 if (pfilter)
2697 delete pfilter;
2700 void CNode::AskFor(const CInv& inv)
2702 if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ)
2703 return;
2704 // a peer may not have multiple non-responded queue positions for a single inv item
2705 if (!setAskFor.insert(inv.hash).second)
2706 return;
2708 // We're using mapAskFor as a priority queue,
2709 // the key is the earliest time the request can be sent
2710 int64_t nRequestTime;
2711 limitedmap<uint256, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv.hash);
2712 if (it != mapAlreadyAskedFor.end())
2713 nRequestTime = it->second;
2714 else
2715 nRequestTime = 0;
2716 LogPrint(BCLog::NET, "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
2718 // Make sure not to reuse time indexes to keep things in the same order
2719 int64_t nNow = GetTimeMicros() - 1000000;
2720 static int64_t nLastTime;
2721 ++nLastTime;
2722 nNow = std::max(nNow, nLastTime);
2723 nLastTime = nNow;
2725 // Each retry is 2 minutes after the last
2726 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
2727 if (it != mapAlreadyAskedFor.end())
2728 mapAlreadyAskedFor.update(it, nRequestTime);
2729 else
2730 mapAlreadyAskedFor.insert(std::make_pair(inv.hash, nRequestTime));
2731 mapAskFor.insert(std::make_pair(nRequestTime, inv));
2734 bool CConnman::NodeFullyConnected(const CNode* pnode)
2736 return pnode && pnode->fSuccessfullyConnected && !pnode->fDisconnect;
2739 void CConnman::PushMessage(CNode* pnode, CSerializedNetMsg&& msg)
2741 size_t nMessageSize = msg.data.size();
2742 size_t nTotalSize = nMessageSize + CMessageHeader::HEADER_SIZE;
2743 LogPrint(BCLog::NET, "sending %s (%d bytes) peer=%d\n", SanitizeString(msg.command.c_str()), nMessageSize, pnode->id);
2745 std::vector<unsigned char> serializedHeader;
2746 serializedHeader.reserve(CMessageHeader::HEADER_SIZE);
2747 uint256 hash = Hash(msg.data.data(), msg.data.data() + nMessageSize);
2748 CMessageHeader hdr(Params().MessageStart(), msg.command.c_str(), nMessageSize);
2749 memcpy(hdr.pchChecksum, hash.begin(), CMessageHeader::CHECKSUM_SIZE);
2751 CVectorWriter{SER_NETWORK, INIT_PROTO_VERSION, serializedHeader, 0, hdr};
2753 size_t nBytesSent = 0;
2755 LOCK(pnode->cs_vSend);
2756 bool optimisticSend(pnode->vSendMsg.empty());
2758 //log total amount of bytes per command
2759 pnode->mapSendBytesPerMsgCmd[msg.command] += nTotalSize;
2760 pnode->nSendSize += nTotalSize;
2762 if (pnode->nSendSize > nSendBufferMaxSize)
2763 pnode->fPauseSend = true;
2764 pnode->vSendMsg.push_back(std::move(serializedHeader));
2765 if (nMessageSize)
2766 pnode->vSendMsg.push_back(std::move(msg.data));
2768 // If write queue empty, attempt "optimistic write"
2769 if (optimisticSend == true)
2770 nBytesSent = SocketSendData(pnode);
2772 if (nBytesSent)
2773 RecordBytesSent(nBytesSent);
2776 bool CConnman::ForNode(NodeId id, std::function<bool(CNode* pnode)> func)
2778 CNode* found = nullptr;
2779 LOCK(cs_vNodes);
2780 for (auto&& pnode : vNodes) {
2781 if(pnode->id == id) {
2782 found = pnode;
2783 break;
2786 return found != nullptr && NodeFullyConnected(found) && func(found);
2789 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds) {
2790 return nNow + (int64_t)(log1p(GetRand(1ULL << 48) * -0.0000000000000035527136788 /* -1/2^48 */) * average_interval_seconds * -1000000.0 + 0.5);
2793 CSipHasher CConnman::GetDeterministicRandomizer(uint64_t id) const
2795 return CSipHasher(nSeed0, nSeed1).Write(id);
2798 uint64_t CConnman::CalculateKeyedNetGroup(const CAddress& ad) const
2800 std::vector<unsigned char> vchNetGroup(ad.GetGroup());
2802 return GetDeterministicRandomizer(RANDOMIZER_ID_NETGROUP).Write(&vchNetGroup[0], vchNetGroup.size()).Finalize();