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