]> Git Repo - VerusCoin.git/blob - src/net.cpp
Auto merge of #3521 - bitcartel:sapling_json_data, r=str4d
[VerusCoin.git] / src / net.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #if defined(HAVE_CONFIG_H)
7 #include "config/bitcoin-config.h"
8 #endif
9
10 #include "main.h"
11 #include "net.h"
12
13 #include "addrman.h"
14 #include "chainparams.h"
15 #include "clientversion.h"
16 #include "primitives/transaction.h"
17 #include "scheduler.h"
18 #include "ui_interface.h"
19 #include "crypto/common.h"
20
21 #ifdef WIN32
22 #include <string.h>
23 #else
24 #include <fcntl.h>
25 #endif
26
27 #include <boost/filesystem.hpp>
28 #include <boost/thread.hpp>
29
30 // Dump addresses to peers.dat every 15 minutes (900s)
31 #define DUMP_ADDRESSES_INTERVAL 900
32
33 #if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
34 #define MSG_NOSIGNAL 0
35 #endif
36
37 // Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
38 // Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
39 #ifdef WIN32
40 #ifndef PROTECTION_LEVEL_UNRESTRICTED
41 #define PROTECTION_LEVEL_UNRESTRICTED 10
42 #endif
43 #ifndef IPV6_PROTECTION_LEVEL
44 #define IPV6_PROTECTION_LEVEL 23
45 #endif
46 #endif
47
48 using namespace std;
49
50 namespace {
51     const int MAX_OUTBOUND_CONNECTIONS = 8;
52
53     struct ListenSocket {
54         SOCKET socket;
55         bool whitelisted;
56
57         ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
58     };
59 }
60
61 //
62 // Global state variables
63 //
64 bool fDiscover = true;
65 bool fListen = true;
66 uint64_t nLocalServices = NODE_NETWORK;
67 CCriticalSection cs_mapLocalHost;
68 map<CNetAddr, LocalServiceInfo> mapLocalHost;
69 static bool vfLimited[NET_MAX] = {};
70 static CNode* pnodeLocalHost = NULL;
71 uint64_t nLocalHostNonce = 0;
72 static std::vector<ListenSocket> vhListenSocket;
73 CAddrMan addrman;
74 int nMaxConnections = DEFAULT_MAX_PEER_CONNECTIONS;
75 bool fAddressesInitialized = false;
76 std::string strSubVersion;
77
78 vector<CNode*> vNodes;
79 CCriticalSection cs_vNodes;
80 map<CInv, CDataStream> mapRelay;
81 deque<pair<int64_t, CInv> > vRelayExpiration;
82 CCriticalSection cs_mapRelay;
83 limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
84
85 static deque<string> vOneShots;
86 static CCriticalSection cs_vOneShots;
87
88 static set<CNetAddr> setservAddNodeAddresses;
89 static CCriticalSection cs_setservAddNodeAddresses;
90
91 vector<std::string> vAddedNodes;
92 CCriticalSection cs_vAddedNodes;
93
94 NodeId nLastNodeId = 0;
95 CCriticalSection cs_nLastNodeId;
96
97 static CSemaphore *semOutbound = NULL;
98 static boost::condition_variable messageHandlerCondition;
99
100 // Signals for message handling
101 static CNodeSignals g_signals;
102 CNodeSignals& GetNodeSignals() { return g_signals; }
103
104 void AddOneShot(const std::string& strDest)
105 {
106     LOCK(cs_vOneShots);
107     vOneShots.push_back(strDest);
108 }
109
110 unsigned short GetListenPort()
111 {
112     return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
113 }
114
115 // find 'best' local address for a particular peer
116 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
117 {
118     if (!fListen)
119         return false;
120
121     int nBestScore = -1;
122     int nBestReachability = -1;
123     {
124         LOCK(cs_mapLocalHost);
125         for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
126         {
127             int nScore = (*it).second.nScore;
128             int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
129             if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
130             {
131                 addr = CService((*it).first, (*it).second.nPort);
132                 nBestReachability = nReachability;
133                 nBestScore = nScore;
134             }
135         }
136     }
137     return nBestScore >= 0;
138 }
139
140 //! Convert the pnSeeds6 array into usable address objects.
141 static std::vector<CAddress> convertSeed6(const std::vector<SeedSpec6> &vSeedsIn)
142 {
143     // It'll only connect to one or two seed nodes because once it connects,
144     // it'll get a pile of addresses with newer timestamps.
145     // Seed nodes are given a random 'last seen time' of between one and two
146     // weeks ago.
147     const int64_t nOneWeek = 7*24*60*60;
148     std::vector<CAddress> vSeedsOut;
149     vSeedsOut.reserve(vSeedsIn.size());
150     for (std::vector<SeedSpec6>::const_iterator i(vSeedsIn.begin()); i != vSeedsIn.end(); ++i)
151     {
152         struct in6_addr ip;
153         memcpy(&ip, i->addr, sizeof(ip));
154         CAddress addr(CService(ip, i->port));
155         addr.nTime = GetTime() - GetRand(nOneWeek) - nOneWeek;
156         vSeedsOut.push_back(addr);
157     }
158     return vSeedsOut;
159 }
160
161 // get best local address for a particular peer as a CAddress
162 // Otherwise, return the unroutable 0.0.0.0 but filled in with
163 // the normal parameters, since the IP may be changed to a useful
164 // one by discovery.
165 CAddress GetLocalAddress(const CNetAddr *paddrPeer)
166 {
167     CAddress ret(CService("0.0.0.0",GetListenPort()),0);
168     CService addr;
169     if (GetLocal(addr, paddrPeer))
170     {
171         ret = CAddress(addr);
172     }
173     ret.nServices = nLocalServices;
174     ret.nTime = GetAdjustedTime();
175     return ret;
176 }
177
178 int GetnScore(const CService& addr)
179 {
180     LOCK(cs_mapLocalHost);
181     if (mapLocalHost.count(addr) == LOCAL_NONE)
182         return 0;
183     return mapLocalHost[addr].nScore;
184 }
185
186 // Is our peer's addrLocal potentially useful as an external IP source?
187 bool IsPeerAddrLocalGood(CNode *pnode)
188 {
189     return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() &&
190            !IsLimited(pnode->addrLocal.GetNetwork());
191 }
192
193 // pushes our own address to a peer
194 void AdvertizeLocal(CNode *pnode)
195 {
196     if (fListen && pnode->fSuccessfullyConnected)
197     {
198         CAddress addrLocal = GetLocalAddress(&pnode->addr);
199         // If discovery is enabled, sometimes give our peer the address it
200         // tells us that it sees us as in case it has a better idea of our
201         // address than we do.
202         if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
203              GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0))
204         {
205             addrLocal.SetIP(pnode->addrLocal);
206         }
207         if (addrLocal.IsRoutable())
208         {
209             LogPrintf("AdvertizeLocal: advertizing address %s\n", addrLocal.ToString());
210             pnode->PushAddress(addrLocal);
211         }
212     }
213 }
214
215 // learn a new local address
216 bool AddLocal(const CService& addr, int nScore)
217 {
218     if (!addr.IsRoutable())
219         return false;
220
221     if (!fDiscover && nScore < LOCAL_MANUAL)
222         return false;
223
224     if (IsLimited(addr))
225         return false;
226
227     LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
228
229     {
230         LOCK(cs_mapLocalHost);
231         bool fAlready = mapLocalHost.count(addr) > 0;
232         LocalServiceInfo &info = mapLocalHost[addr];
233         if (!fAlready || nScore >= info.nScore) {
234             info.nScore = nScore + (fAlready ? 1 : 0);
235             info.nPort = addr.GetPort();
236         }
237     }
238
239     return true;
240 }
241
242 bool AddLocal(const CNetAddr &addr, int nScore)
243 {
244     return AddLocal(CService(addr, GetListenPort()), nScore);
245 }
246
247 bool RemoveLocal(const CService& addr)
248 {
249     LOCK(cs_mapLocalHost);
250     LogPrintf("RemoveLocal(%s)\n", addr.ToString());
251     mapLocalHost.erase(addr);
252     return true;
253 }
254
255 /** Make a particular network entirely off-limits (no automatic connects to it) */
256 void SetLimited(enum Network net, bool fLimited)
257 {
258     if (net == NET_UNROUTABLE)
259         return;
260     LOCK(cs_mapLocalHost);
261     vfLimited[net] = fLimited;
262 }
263
264 bool IsLimited(enum Network net)
265 {
266     LOCK(cs_mapLocalHost);
267     return vfLimited[net];
268 }
269
270 bool IsLimited(const CNetAddr &addr)
271 {
272     return IsLimited(addr.GetNetwork());
273 }
274
275 /** vote for a local address */
276 bool SeenLocal(const CService& addr)
277 {
278     {
279         LOCK(cs_mapLocalHost);
280         if (mapLocalHost.count(addr) == 0)
281             return false;
282         mapLocalHost[addr].nScore++;
283     }
284     return true;
285 }
286
287
288 /** check whether a given address is potentially local */
289 bool IsLocal(const CService& addr)
290 {
291     LOCK(cs_mapLocalHost);
292     return mapLocalHost.count(addr) > 0;
293 }
294
295 /** check whether a given network is one we can probably connect to */
296 bool IsReachable(enum Network net)
297 {
298     LOCK(cs_mapLocalHost);
299     return !vfLimited[net];
300 }
301
302 /** check whether a given address is in a network we can probably connect to */
303 bool IsReachable(const CNetAddr& addr)
304 {
305     enum Network net = addr.GetNetwork();
306     return IsReachable(net);
307 }
308
309 void AddressCurrentlyConnected(const CService& addr)
310 {
311     addrman.Connected(addr);
312 }
313
314
315 uint64_t CNode::nTotalBytesRecv = 0;
316 uint64_t CNode::nTotalBytesSent = 0;
317 CCriticalSection CNode::cs_totalBytesRecv;
318 CCriticalSection CNode::cs_totalBytesSent;
319
320 CNode* FindNode(const CNetAddr& ip)
321 {
322     LOCK(cs_vNodes);
323     BOOST_FOREACH(CNode* pnode, vNodes)
324         if ((CNetAddr)pnode->addr == ip)
325             return (pnode);
326     return NULL;
327 }
328
329 CNode* FindNode(const CSubNet& subNet)
330 {
331     LOCK(cs_vNodes);
332     BOOST_FOREACH(CNode* pnode, vNodes)
333     if (subNet.Match((CNetAddr)pnode->addr))
334         return (pnode);
335     return NULL;
336 }
337
338 CNode* FindNode(const std::string& addrName)
339 {
340     LOCK(cs_vNodes);
341     BOOST_FOREACH(CNode* pnode, vNodes)
342         if (pnode->addrName == addrName)
343             return (pnode);
344     return NULL;
345 }
346
347 CNode* FindNode(const CService& addr)
348 {
349     LOCK(cs_vNodes);
350     BOOST_FOREACH(CNode* pnode, vNodes)
351         if ((CService)pnode->addr == addr)
352             return (pnode);
353     return NULL;
354 }
355
356 CNode* ConnectNode(CAddress addrConnect, const char *pszDest)
357 {
358     if (pszDest == NULL) {
359         if (IsLocal(addrConnect))
360             return NULL;
361
362         // Look for an existing connection
363         CNode* pnode = FindNode((CService)addrConnect);
364         if (pnode)
365         {
366             pnode->AddRef();
367             return pnode;
368         }
369     }
370
371     /// debug print
372     LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
373         pszDest ? pszDest : addrConnect.ToString(),
374         pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
375
376     // Connect
377     SOCKET hSocket;
378     bool proxyConnectionFailed = false;
379     if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
380                   ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed))
381     {
382         if (!IsSelectableSocket(hSocket)) {
383             LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
384             CloseSocket(hSocket);
385             return NULL;
386         }
387
388         addrman.Attempt(addrConnect);
389
390         // Add node
391         CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
392         pnode->AddRef();
393
394         {
395             LOCK(cs_vNodes);
396             vNodes.push_back(pnode);
397         }
398
399         pnode->nTimeConnected = GetTime();
400
401         return pnode;
402     } else if (!proxyConnectionFailed) {
403         // If connecting to the node failed, and failure is not caused by a problem connecting to
404         // the proxy, mark this as an attempt.
405         addrman.Attempt(addrConnect);
406     }
407
408     return NULL;
409 }
410
411 void CNode::CloseSocketDisconnect()
412 {
413     fDisconnect = true;
414     if (hSocket != INVALID_SOCKET)
415     {
416         LogPrint("net", "disconnecting peer=%d\n", id);
417         CloseSocket(hSocket);
418     }
419
420     // in case this fails, we'll empty the recv buffer when the CNode is deleted
421     TRY_LOCK(cs_vRecvMsg, lockRecv);
422     if (lockRecv)
423         vRecvMsg.clear();
424 }
425
426 void CNode::PushVersion()
427 {
428     int nBestHeight = g_signals.GetHeight().get_value_or(0);
429
430     int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
431     CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
432     CAddress addrMe = GetLocalAddress(&addr);
433     GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
434     if (fLogIPs)
435         LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
436     else
437         LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
438     PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
439                 nLocalHostNonce, strSubVersion, nBestHeight, true);
440 }
441
442
443
444
445
446 std::map<CSubNet, int64_t> CNode::setBanned;
447 CCriticalSection CNode::cs_setBanned;
448
449 void CNode::ClearBanned()
450 {
451     LOCK(cs_setBanned);
452     setBanned.clear();
453 }
454
455 bool CNode::IsBanned(CNetAddr ip)
456 {
457     bool fResult = false;
458     {
459         LOCK(cs_setBanned);
460         for (std::map<CSubNet, int64_t>::iterator it = setBanned.begin(); it != setBanned.end(); it++)
461         {
462             CSubNet subNet = (*it).first;
463             int64_t t = (*it).second;
464
465             if(subNet.Match(ip) && GetTime() < t)
466                 fResult = true;
467         }
468     }
469     return fResult;
470 }
471
472 bool CNode::IsBanned(CSubNet subnet)
473 {
474     bool fResult = false;
475     {
476         LOCK(cs_setBanned);
477         std::map<CSubNet, int64_t>::iterator i = setBanned.find(subnet);
478         if (i != setBanned.end())
479         {
480             int64_t t = (*i).second;
481             if (GetTime() < t)
482                 fResult = true;
483         }
484     }
485     return fResult;
486 }
487
488 void CNode::Ban(const CNetAddr& addr, int64_t bantimeoffset, bool sinceUnixEpoch) {
489     CSubNet subNet(addr.ToString()+(addr.IsIPv4() ? "/32" : "/128"));
490     Ban(subNet, bantimeoffset, sinceUnixEpoch);
491 }
492
493 void CNode::Ban(const CSubNet& subNet, int64_t bantimeoffset, bool sinceUnixEpoch) {
494     int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24);  // Default 24-hour ban
495     if (bantimeoffset > 0)
496         banTime = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
497
498     LOCK(cs_setBanned);
499     if (setBanned[subNet] < banTime)
500         setBanned[subNet] = banTime;
501 }
502
503 bool CNode::Unban(const CNetAddr &addr) {
504     CSubNet subNet(addr.ToString()+(addr.IsIPv4() ? "/32" : "/128"));
505     return Unban(subNet);
506 }
507
508 bool CNode::Unban(const CSubNet &subNet) {
509     LOCK(cs_setBanned);
510     if (setBanned.erase(subNet))
511         return true;
512     return false;
513 }
514
515 void CNode::GetBanned(std::map<CSubNet, int64_t> &banMap)
516 {
517     LOCK(cs_setBanned);
518     banMap = setBanned; //create a thread safe copy
519 }
520
521
522 std::vector<CSubNet> CNode::vWhitelistedRange;
523 CCriticalSection CNode::cs_vWhitelistedRange;
524
525 bool CNode::IsWhitelistedRange(const CNetAddr &addr) {
526     LOCK(cs_vWhitelistedRange);
527     BOOST_FOREACH(const CSubNet& subnet, vWhitelistedRange) {
528         if (subnet.Match(addr))
529             return true;
530     }
531     return false;
532 }
533
534 void CNode::AddWhitelistedRange(const CSubNet &subnet) {
535     LOCK(cs_vWhitelistedRange);
536     vWhitelistedRange.push_back(subnet);
537 }
538
539 void CNode::copyStats(CNodeStats &stats)
540 {
541     stats.nodeid = this->GetId();
542     stats.nServices = nServices;
543     stats.nLastSend = nLastSend;
544     stats.nLastRecv = nLastRecv;
545     stats.nTimeConnected = nTimeConnected;
546     stats.nTimeOffset = nTimeOffset;
547     stats.addrName = addrName;
548     stats.nVersion = nVersion;
549     stats.cleanSubVer = cleanSubVer;
550     stats.fInbound = fInbound;
551     stats.nStartingHeight = nStartingHeight;
552     stats.nSendBytes = nSendBytes;
553     stats.nRecvBytes = nRecvBytes;
554     stats.fWhitelisted = fWhitelisted;
555
556     // It is common for nodes with good ping times to suddenly become lagged,
557     // due to a new block arriving or other large transfer.
558     // Merely reporting pingtime might fool the caller into thinking the node was still responsive,
559     // since pingtime does not update until the ping is complete, which might take a while.
560     // So, if a ping is taking an unusually long time in flight,
561     // the caller can immediately detect that this is happening.
562     int64_t nPingUsecWait = 0;
563     if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
564         nPingUsecWait = GetTimeMicros() - nPingUsecStart;
565     }
566
567     // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :)
568     stats.dPingTime = (((double)nPingUsecTime) / 1e6);
569     stats.dPingWait = (((double)nPingUsecWait) / 1e6);
570
571     // Leave string empty if addrLocal invalid (not filled in yet)
572     stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
573 }
574
575 // requires LOCK(cs_vRecvMsg)
576 bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes)
577 {
578     while (nBytes > 0) {
579
580         // get current incomplete message, or create a new one
581         if (vRecvMsg.empty() ||
582             vRecvMsg.back().complete())
583             vRecvMsg.push_back(CNetMessage(Params().MessageStart(), SER_NETWORK, nRecvVersion));
584
585         CNetMessage& msg = vRecvMsg.back();
586
587         // absorb network data
588         int handled;
589         if (!msg.in_data)
590             handled = msg.readHeader(pch, nBytes);
591         else
592             handled = msg.readData(pch, nBytes);
593
594         if (handled < 0)
595                 return false;
596
597         if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
598             LogPrint("net", "Oversized message from peer=%i, disconnecting\n", GetId());
599             return false;
600         }
601
602         pch += handled;
603         nBytes -= handled;
604
605         if (msg.complete()) {
606             msg.nTime = GetTimeMicros();
607             messageHandlerCondition.notify_one();
608         }
609     }
610
611     return true;
612 }
613
614 int CNetMessage::readHeader(const char *pch, unsigned int nBytes)
615 {
616     // copy data to temporary parsing buffer
617     unsigned int nRemaining = 24 - nHdrPos;
618     unsigned int nCopy = std::min(nRemaining, nBytes);
619
620     memcpy(&hdrbuf[nHdrPos], pch, nCopy);
621     nHdrPos += nCopy;
622
623     // if header incomplete, exit
624     if (nHdrPos < 24)
625         return nCopy;
626
627     // deserialize to CMessageHeader
628     try {
629         hdrbuf >> hdr;
630     }
631     catch (const std::exception&) {
632         return -1;
633     }
634
635     // reject messages larger than MAX_SIZE
636     if (hdr.nMessageSize > MAX_SIZE)
637             return -1;
638
639     // switch state to reading message data
640     in_data = true;
641
642     return nCopy;
643 }
644
645 int CNetMessage::readData(const char *pch, unsigned int nBytes)
646 {
647     unsigned int nRemaining = hdr.nMessageSize - nDataPos;
648     unsigned int nCopy = std::min(nRemaining, nBytes);
649
650     if (vRecv.size() < nDataPos + nCopy) {
651         // Allocate up to 256 KiB ahead, but never more than the total message size.
652         vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
653     }
654
655     memcpy(&vRecv[nDataPos], pch, nCopy);
656     nDataPos += nCopy;
657
658     return nCopy;
659 }
660
661
662
663
664
665
666
667
668
669 // requires LOCK(cs_vSend)
670 void SocketSendData(CNode *pnode)
671 {
672     std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
673
674     while (it != pnode->vSendMsg.end()) {
675         const CSerializeData &data = *it;
676         assert(data.size() > pnode->nSendOffset);
677         int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
678         if (nBytes > 0) {
679             pnode->nLastSend = GetTime();
680             pnode->nSendBytes += nBytes;
681             pnode->nSendOffset += nBytes;
682             pnode->RecordBytesSent(nBytes);
683             if (pnode->nSendOffset == data.size()) {
684                 pnode->nSendOffset = 0;
685                 pnode->nSendSize -= data.size();
686                 it++;
687             } else {
688                 // could not send full message; stop sending more
689                 break;
690             }
691         } else {
692             if (nBytes < 0) {
693                 // error
694                 int nErr = WSAGetLastError();
695                 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
696                 {
697                     LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
698                     pnode->CloseSocketDisconnect();
699                 }
700             }
701             // couldn't send anything at all
702             break;
703         }
704     }
705
706     if (it == pnode->vSendMsg.end()) {
707         assert(pnode->nSendOffset == 0);
708         assert(pnode->nSendSize == 0);
709     }
710     pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
711 }
712
713 static list<CNode*> vNodesDisconnected;
714
715 class CNodeRef {
716 public:
717     CNodeRef(CNode *pnode) : _pnode(pnode) {
718         LOCK(cs_vNodes);
719         _pnode->AddRef();
720     }
721
722     ~CNodeRef() {
723         LOCK(cs_vNodes);
724         _pnode->Release();
725     }
726
727     CNode& operator *() const {return *_pnode;};
728     CNode* operator ->() const {return _pnode;};
729
730     CNodeRef& operator =(const CNodeRef& other)
731     {
732         if (this != &other) {
733             LOCK(cs_vNodes);
734
735             _pnode->Release();
736             _pnode = other._pnode;
737             _pnode->AddRef();
738         }
739         return *this;
740     }
741
742     CNodeRef(const CNodeRef& other):
743         _pnode(other._pnode)
744     {
745         LOCK(cs_vNodes);
746         _pnode->AddRef();
747     }
748 private:
749     CNode *_pnode;
750 };
751
752 static bool ReverseCompareNodeMinPingTime(const CNodeRef &a, const CNodeRef &b)
753 {
754     return a->nMinPingUsecTime > b->nMinPingUsecTime;
755 }
756
757 static bool ReverseCompareNodeTimeConnected(const CNodeRef &a, const CNodeRef &b)
758 {
759     return a->nTimeConnected > b->nTimeConnected;
760 }
761
762 class CompareNetGroupKeyed
763 {
764     std::vector<unsigned char> vchSecretKey;
765 public:
766     CompareNetGroupKeyed()
767     {
768         vchSecretKey.resize(32, 0);
769         GetRandBytes(vchSecretKey.data(), vchSecretKey.size());
770     }
771
772     bool operator()(const CNodeRef &a, const CNodeRef &b)
773     {
774         std::vector<unsigned char> vchGroupA, vchGroupB;
775         CSHA256 hashA, hashB;
776         std::vector<unsigned char> vchA(32), vchB(32);
777
778         vchGroupA = a->addr.GetGroup();
779         vchGroupB = b->addr.GetGroup();
780
781         hashA.Write(begin_ptr(vchGroupA), vchGroupA.size());
782         hashB.Write(begin_ptr(vchGroupB), vchGroupB.size());
783
784         hashA.Write(begin_ptr(vchSecretKey), vchSecretKey.size());
785         hashB.Write(begin_ptr(vchSecretKey), vchSecretKey.size());
786
787         hashA.Finalize(begin_ptr(vchA));
788         hashB.Finalize(begin_ptr(vchB));
789
790         return vchA < vchB;
791     }
792 };
793
794 static bool AttemptToEvictConnection(bool fPreferNewConnection) {
795     std::vector<CNodeRef> vEvictionCandidates;
796     {
797         LOCK(cs_vNodes);
798
799         BOOST_FOREACH(CNode *node, vNodes) {
800             if (node->fWhitelisted)
801                 continue;
802             if (!node->fInbound)
803                 continue;
804             if (node->fDisconnect)
805                 continue;
806             vEvictionCandidates.push_back(CNodeRef(node));
807         }
808     }
809
810     if (vEvictionCandidates.empty()) return false;
811
812     // Protect connections with certain characteristics
813
814     // Check version of eviction candidates and prioritize nodes which do not support network upgrade.
815     std::vector<CNodeRef> vTmpEvictionCandidates;
816     int height;
817     {
818         LOCK(cs_main);
819         height = chainActive.Height();
820     }
821
822     const Consensus::Params& params = Params().GetConsensus();
823     auto nextEpoch = NextEpoch(height, params);
824     if (nextEpoch) {
825         auto idx = nextEpoch.get();
826         int nActivationHeight = params.vUpgrades[idx].nActivationHeight;
827
828         if (nActivationHeight > 0 &&
829             height < nActivationHeight &&
830             height >= nActivationHeight - NETWORK_UPGRADE_PEER_PREFERENCE_BLOCK_PERIOD)
831         {
832             // Find any nodes which don't support the protocol version for the next upgrade
833             for (const CNodeRef &node : vEvictionCandidates) {
834                 if (node->nVersion < params.vUpgrades[idx].nProtocolVersion) {
835                     vTmpEvictionCandidates.push_back(node);
836                 }
837             }
838
839             // Prioritize these nodes by replacing eviction set with them
840             if (vTmpEvictionCandidates.size() > 0) {
841                 vEvictionCandidates = vTmpEvictionCandidates;
842             }
843         }
844     }
845
846     // Deterministically select 4 peers to protect by netgroup.
847     // An attacker cannot predict which netgroups will be protected.
848     static CompareNetGroupKeyed comparerNetGroupKeyed;
849     std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), comparerNetGroupKeyed);
850     vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(4, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
851
852     if (vEvictionCandidates.empty()) return false;
853
854     // Protect the 8 nodes with the best ping times.
855     // An attacker cannot manipulate this metric without physically moving nodes closer to the target.
856     std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeMinPingTime);
857     vEvictionCandidates.erase(vEvictionCandidates.end() - std::min(8, static_cast<int>(vEvictionCandidates.size())), vEvictionCandidates.end());
858
859     if (vEvictionCandidates.empty()) return false;
860
861     // Protect the half of the remaining nodes which have been connected the longest.
862     // This replicates the existing implicit behavior.
863     std::sort(vEvictionCandidates.begin(), vEvictionCandidates.end(), ReverseCompareNodeTimeConnected);
864     vEvictionCandidates.erase(vEvictionCandidates.end() - static_cast<int>(vEvictionCandidates.size() / 2), vEvictionCandidates.end());
865
866     if (vEvictionCandidates.empty()) return false;
867
868     // Identify the network group with the most connections and youngest member.
869     // (vEvictionCandidates is already sorted by reverse connect time)
870     std::vector<unsigned char> naMostConnections;
871     unsigned int nMostConnections = 0;
872     int64_t nMostConnectionsTime = 0;
873     std::map<std::vector<unsigned char>, std::vector<CNodeRef> > mapAddrCounts;
874     BOOST_FOREACH(const CNodeRef &node, vEvictionCandidates) {
875         mapAddrCounts[node->addr.GetGroup()].push_back(node);
876         int64_t grouptime = mapAddrCounts[node->addr.GetGroup()][0]->nTimeConnected;
877         size_t groupsize = mapAddrCounts[node->addr.GetGroup()].size();
878
879         if (groupsize > nMostConnections || (groupsize == nMostConnections && grouptime > nMostConnectionsTime)) {
880             nMostConnections = groupsize;
881             nMostConnectionsTime = grouptime;
882             naMostConnections = node->addr.GetGroup();
883         }
884     }
885
886     // Reduce to the network group with the most connections
887     vEvictionCandidates = mapAddrCounts[naMostConnections];
888
889     // Do not disconnect peers if there is only one unprotected connection from their network group.
890     if (vEvictionCandidates.size() <= 1)
891         // unless we prefer the new connection (for whitelisted peers)
892         if (!fPreferNewConnection)
893             return false;
894
895     // Disconnect from the network group with the most connections
896     vEvictionCandidates[0]->fDisconnect = true;
897
898     return true;
899 }
900
901 static void AcceptConnection(const ListenSocket& hListenSocket) {
902     struct sockaddr_storage sockaddr;
903     socklen_t len = sizeof(sockaddr);
904     SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
905     CAddress addr;
906     int nInbound = 0;
907     int nMaxInbound = nMaxConnections - MAX_OUTBOUND_CONNECTIONS;
908
909     if (hSocket != INVALID_SOCKET)
910         if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
911             LogPrintf("Warning: Unknown socket family\n");
912
913     bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
914     {
915         LOCK(cs_vNodes);
916         BOOST_FOREACH(CNode* pnode, vNodes)
917             if (pnode->fInbound)
918                 nInbound++;
919     }
920
921     if (hSocket == INVALID_SOCKET)
922     {
923         int nErr = WSAGetLastError();
924         if (nErr != WSAEWOULDBLOCK)
925             LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
926         return;
927     }
928
929     if (!IsSelectableSocket(hSocket))
930     {
931         LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
932         CloseSocket(hSocket);
933         return;
934     }
935
936     if (CNode::IsBanned(addr) && !whitelisted)
937     {
938         LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
939         CloseSocket(hSocket);
940         return;
941     }
942
943     if (nInbound >= nMaxInbound)
944     {
945         if (!AttemptToEvictConnection(whitelisted)) {
946             // No connection to evict, disconnect the new connection
947             LogPrint("net", "failed to find an eviction candidate - connection dropped (full)\n");
948             CloseSocket(hSocket);
949             return;
950         }
951     }
952
953     // According to the internet TCP_NODELAY is not carried into accepted sockets
954     // on all platforms.  Set it again here just to be sure.
955     int set = 1;
956 #ifdef WIN32
957     setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int));
958 #else
959     setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&set, sizeof(int));
960 #endif
961
962     CNode* pnode = new CNode(hSocket, addr, "", true);
963     pnode->AddRef();
964     pnode->fWhitelisted = whitelisted;
965
966     LogPrint("net", "connection from %s accepted\n", addr.ToString());
967
968     {
969         LOCK(cs_vNodes);
970         vNodes.push_back(pnode);
971     }
972 }
973
974 void ThreadSocketHandler()
975 {
976     unsigned int nPrevNodeCount = 0;
977     while (true)
978     {
979         //
980         // Disconnect nodes
981         //
982         {
983             LOCK(cs_vNodes);
984             // Disconnect unused nodes
985             vector<CNode*> vNodesCopy = vNodes;
986             BOOST_FOREACH(CNode* pnode, vNodesCopy)
987             {
988                 if (pnode->fDisconnect ||
989                     (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty()))
990                 {
991                     // remove from vNodes
992                     vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
993
994                     // release outbound grant (if any)
995                     pnode->grantOutbound.Release();
996
997                     // close socket and cleanup
998                     pnode->CloseSocketDisconnect();
999
1000                     // hold in disconnected pool until all refs are released
1001                     if (pnode->fNetworkNode || pnode->fInbound)
1002                         pnode->Release();
1003                     vNodesDisconnected.push_back(pnode);
1004                 }
1005             }
1006         }
1007         {
1008             // Delete disconnected nodes
1009             list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
1010             BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
1011             {
1012                 // wait until threads are done using it
1013                 if (pnode->GetRefCount() <= 0)
1014                 {
1015                     bool fDelete = false;
1016                     {
1017                         TRY_LOCK(pnode->cs_vSend, lockSend);
1018                         if (lockSend)
1019                         {
1020                             TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1021                             if (lockRecv)
1022                             {
1023                                 TRY_LOCK(pnode->cs_inventory, lockInv);
1024                                 if (lockInv)
1025                                     fDelete = true;
1026                             }
1027                         }
1028                     }
1029                     if (fDelete)
1030                     {
1031                         vNodesDisconnected.remove(pnode);
1032                         delete pnode;
1033                     }
1034                 }
1035             }
1036         }
1037         if(vNodes.size() != nPrevNodeCount) {
1038             nPrevNodeCount = vNodes.size();
1039             uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
1040         }
1041
1042         //
1043         // Find which sockets have data to receive
1044         //
1045         struct timeval timeout;
1046         timeout.tv_sec  = 0;
1047         timeout.tv_usec = 50000; // frequency to poll pnode->vSend
1048
1049         fd_set fdsetRecv;
1050         fd_set fdsetSend;
1051         fd_set fdsetError;
1052         FD_ZERO(&fdsetRecv);
1053         FD_ZERO(&fdsetSend);
1054         FD_ZERO(&fdsetError);
1055         SOCKET hSocketMax = 0;
1056         bool have_fds = false;
1057
1058         BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket) {
1059             FD_SET(hListenSocket.socket, &fdsetRecv);
1060             hSocketMax = max(hSocketMax, hListenSocket.socket);
1061             have_fds = true;
1062         }
1063
1064         {
1065             LOCK(cs_vNodes);
1066             BOOST_FOREACH(CNode* pnode, vNodes)
1067             {
1068                 if (pnode->hSocket == INVALID_SOCKET)
1069                     continue;
1070                 FD_SET(pnode->hSocket, &fdsetError);
1071                 hSocketMax = max(hSocketMax, pnode->hSocket);
1072                 have_fds = true;
1073
1074                 // Implement the following logic:
1075                 // * If there is data to send, select() for sending data. As this only
1076                 //   happens when optimistic write failed, we choose to first drain the
1077                 //   write buffer in this case before receiving more. This avoids
1078                 //   needlessly queueing received data, if the remote peer is not themselves
1079                 //   receiving data. This means properly utilizing TCP flow control signaling.
1080                 // * Otherwise, if there is no (complete) message in the receive buffer,
1081                 //   or there is space left in the buffer, select() for receiving data.
1082                 // * (if neither of the above applies, there is certainly one message
1083                 //   in the receiver buffer ready to be processed).
1084                 // Together, that means that at least one of the following is always possible,
1085                 // so we don't deadlock:
1086                 // * We send some data.
1087                 // * We wait for data to be received (and disconnect after timeout).
1088                 // * We process a message in the buffer (message handler thread).
1089                 {
1090                     TRY_LOCK(pnode->cs_vSend, lockSend);
1091                     if (lockSend && !pnode->vSendMsg.empty()) {
1092                         FD_SET(pnode->hSocket, &fdsetSend);
1093                         continue;
1094                     }
1095                 }
1096                 {
1097                     TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1098                     if (lockRecv && (
1099                         pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
1100                         pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
1101                         FD_SET(pnode->hSocket, &fdsetRecv);
1102                 }
1103             }
1104         }
1105
1106         int nSelect = select(have_fds ? hSocketMax + 1 : 0,
1107                              &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
1108         boost::this_thread::interruption_point();
1109
1110         if (nSelect == SOCKET_ERROR)
1111         {
1112             if (have_fds)
1113             {
1114                 int nErr = WSAGetLastError();
1115                 LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
1116                 for (unsigned int i = 0; i <= hSocketMax; i++)
1117                     FD_SET(i, &fdsetRecv);
1118             }
1119             FD_ZERO(&fdsetSend);
1120             FD_ZERO(&fdsetError);
1121             MilliSleep(timeout.tv_usec/1000);
1122         }
1123
1124         //
1125         // Accept new connections
1126         //
1127         BOOST_FOREACH(const ListenSocket& hListenSocket, vhListenSocket)
1128         {
1129             if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv))
1130             {
1131                 AcceptConnection(hListenSocket);
1132             }
1133         }
1134
1135         //
1136         // Service each socket
1137         //
1138         vector<CNode*> vNodesCopy;
1139         {
1140             LOCK(cs_vNodes);
1141             vNodesCopy = vNodes;
1142             BOOST_FOREACH(CNode* pnode, vNodesCopy)
1143                 pnode->AddRef();
1144         }
1145         BOOST_FOREACH(CNode* pnode, vNodesCopy)
1146         {
1147             boost::this_thread::interruption_point();
1148
1149             //
1150             // Receive
1151             //
1152             if (pnode->hSocket == INVALID_SOCKET)
1153                 continue;
1154             if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
1155             {
1156                 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1157                 if (lockRecv)
1158                 {
1159                     {
1160                         // typical socket buffer is 8K-64K
1161                         char pchBuf[0x10000];
1162                         int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
1163                         if (nBytes > 0)
1164                         {
1165                             if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
1166                                 pnode->CloseSocketDisconnect();
1167                             pnode->nLastRecv = GetTime();
1168                             pnode->nRecvBytes += nBytes;
1169                             pnode->RecordBytesRecv(nBytes);
1170                         }
1171                         else if (nBytes == 0)
1172                         {
1173                             // socket closed gracefully
1174                             if (!pnode->fDisconnect)
1175                                 LogPrint("net", "socket closed\n");
1176                             pnode->CloseSocketDisconnect();
1177                         }
1178                         else if (nBytes < 0)
1179                         {
1180                             // error
1181                             int nErr = WSAGetLastError();
1182                             if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
1183                             {
1184                                 if (!pnode->fDisconnect)
1185                                     LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
1186                                 pnode->CloseSocketDisconnect();
1187                             }
1188                         }
1189                     }
1190                 }
1191             }
1192
1193             //
1194             // Send
1195             //
1196             if (pnode->hSocket == INVALID_SOCKET)
1197                 continue;
1198             if (FD_ISSET(pnode->hSocket, &fdsetSend))
1199             {
1200                 TRY_LOCK(pnode->cs_vSend, lockSend);
1201                 if (lockSend)
1202                     SocketSendData(pnode);
1203             }
1204
1205             //
1206             // Inactivity checking
1207             //
1208             int64_t nTime = GetTime();
1209             if (nTime - pnode->nTimeConnected > 60)
1210             {
1211                 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
1212                 {
1213                     LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
1214                     pnode->fDisconnect = true;
1215                 }
1216                 else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL)
1217                 {
1218                     LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
1219                     pnode->fDisconnect = true;
1220                 }
1221                 else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60))
1222                 {
1223                     LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
1224                     pnode->fDisconnect = true;
1225                 }
1226                 else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros())
1227                 {
1228                     LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
1229                     pnode->fDisconnect = true;
1230                 }
1231             }
1232         }
1233         {
1234             LOCK(cs_vNodes);
1235             BOOST_FOREACH(CNode* pnode, vNodesCopy)
1236                 pnode->Release();
1237         }
1238     }
1239 }
1240
1241
1242 void ThreadDNSAddressSeed()
1243 {
1244     // goal: only query DNS seeds if address need is acute
1245     if ((addrman.size() > 0) &&
1246         (!GetBoolArg("-forcednsseed", false))) {
1247         MilliSleep(11 * 1000);
1248
1249         LOCK(cs_vNodes);
1250         if (vNodes.size() >= 2) {
1251             LogPrintf("P2P peers available. Skipped DNS seeding.\n");
1252             return;
1253         }
1254     }
1255
1256     const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds();
1257     int found = 0;
1258
1259     LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
1260
1261     BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) {
1262         if (HaveNameProxy()) {
1263             AddOneShot(seed.host);
1264         } else {
1265             vector<CNetAddr> vIPs;
1266             vector<CAddress> vAdd;
1267             if (LookupHost(seed.host.c_str(), vIPs))
1268             {
1269                 BOOST_FOREACH(const CNetAddr& ip, vIPs)
1270                 {
1271                     int nOneDay = 24*3600;
1272                     CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
1273                     addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1274                     vAdd.push_back(addr);
1275                     found++;
1276                 }
1277             }
1278             addrman.Add(vAdd, CNetAddr(seed.name, true));
1279         }
1280     }
1281
1282     LogPrintf("%d addresses found from DNS seeds\n", found);
1283 }
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296 void DumpAddresses()
1297 {
1298     int64_t nStart = GetTimeMillis();
1299
1300     CAddrDB adb;
1301     adb.Write(addrman);
1302
1303     LogPrint("net", "Flushed %d addresses to peers.dat  %dms\n",
1304            addrman.size(), GetTimeMillis() - nStart);
1305 }
1306
1307 void static ProcessOneShot()
1308 {
1309     string strDest;
1310     {
1311         LOCK(cs_vOneShots);
1312         if (vOneShots.empty())
1313             return;
1314         strDest = vOneShots.front();
1315         vOneShots.pop_front();
1316     }
1317     CAddress addr;
1318     CSemaphoreGrant grant(*semOutbound, true);
1319     if (grant) {
1320         if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1321             AddOneShot(strDest);
1322     }
1323 }
1324
1325 void ThreadOpenConnections()
1326 {
1327     // Connect to specific addresses
1328     if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1329     {
1330         for (int64_t nLoop = 0;; nLoop++)
1331         {
1332             ProcessOneShot();
1333             BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-connect"])
1334             {
1335                 CAddress addr;
1336                 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1337                 for (int i = 0; i < 10 && i < nLoop; i++)
1338                 {
1339                     MilliSleep(500);
1340                 }
1341             }
1342             MilliSleep(500);
1343         }
1344     }
1345
1346     // Initiate network connections
1347     int64_t nStart = GetTime();
1348     while (true)
1349     {
1350         ProcessOneShot();
1351
1352         MilliSleep(500);
1353
1354         CSemaphoreGrant grant(*semOutbound);
1355         boost::this_thread::interruption_point();
1356
1357         // Add seed nodes if DNS seeds are all down (an infrastructure attack?).
1358         if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
1359             static bool done = false;
1360             if (!done) {
1361                 LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
1362                 addrman.Add(convertSeed6(Params().FixedSeeds()), CNetAddr("127.0.0.1"));
1363                 done = true;
1364             }
1365         }
1366
1367         //
1368         // Choose an address to connect to based on most recently seen
1369         //
1370         CAddress addrConnect;
1371
1372         // Only connect out to one peer per network group (/16 for IPv4).
1373         // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1374         int nOutbound = 0;
1375         set<vector<unsigned char> > setConnected;
1376         {
1377             LOCK(cs_vNodes);
1378             BOOST_FOREACH(CNode* pnode, vNodes) {
1379                 if (!pnode->fInbound) {
1380                     setConnected.insert(pnode->addr.GetGroup());
1381                     nOutbound++;
1382                 }
1383             }
1384         }
1385
1386         int64_t nANow = GetAdjustedTime();
1387
1388         int nTries = 0;
1389         while (true)
1390         {
1391             CAddrInfo addr = addrman.Select();
1392
1393             // if we selected an invalid address, restart
1394             if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1395                 break;
1396
1397             // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1398             // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1399             // already-connected network ranges, ...) before trying new addrman addresses.
1400             nTries++;
1401             if (nTries > 100)
1402                 break;
1403
1404             if (IsLimited(addr))
1405                 continue;
1406
1407             // only consider very recently tried nodes after 30 failed attempts
1408             if (nANow - addr.nLastTry < 600 && nTries < 30)
1409                 continue;
1410
1411             // do not allow non-default ports, unless after 50 invalid addresses selected already
1412             if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
1413                 continue;
1414
1415             addrConnect = addr;
1416             break;
1417         }
1418
1419         if (addrConnect.IsValid())
1420             OpenNetworkConnection(addrConnect, &grant);
1421     }
1422 }
1423
1424 void ThreadOpenAddedConnections()
1425 {
1426     {
1427         LOCK(cs_vAddedNodes);
1428         vAddedNodes = mapMultiArgs["-addnode"];
1429     }
1430
1431     if (HaveNameProxy()) {
1432         while(true) {
1433             list<string> lAddresses(0);
1434             {
1435                 LOCK(cs_vAddedNodes);
1436                 BOOST_FOREACH(const std::string& strAddNode, vAddedNodes)
1437                     lAddresses.push_back(strAddNode);
1438             }
1439             BOOST_FOREACH(const std::string& strAddNode, lAddresses) {
1440                 CAddress addr;
1441                 CSemaphoreGrant grant(*semOutbound);
1442                 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1443                 MilliSleep(500);
1444             }
1445             MilliSleep(120000); // Retry every 2 minutes
1446         }
1447     }
1448
1449     for (unsigned int i = 0; true; i++)
1450     {
1451         list<string> lAddresses(0);
1452         {
1453             LOCK(cs_vAddedNodes);
1454             BOOST_FOREACH(const std::string& strAddNode, vAddedNodes)
1455                 lAddresses.push_back(strAddNode);
1456         }
1457
1458         list<vector<CService> > lservAddressesToAdd(0);
1459         BOOST_FOREACH(const std::string& strAddNode, lAddresses) {
1460             vector<CService> vservNode(0);
1461             if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
1462             {
1463                 lservAddressesToAdd.push_back(vservNode);
1464                 {
1465                     LOCK(cs_setservAddNodeAddresses);
1466                     BOOST_FOREACH(const CService& serv, vservNode)
1467                         setservAddNodeAddresses.insert(serv);
1468                 }
1469             }
1470         }
1471         // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1472         // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1473         {
1474             LOCK(cs_vNodes);
1475             BOOST_FOREACH(CNode* pnode, vNodes)
1476                 for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
1477                     BOOST_FOREACH(const CService& addrNode, *(it))
1478                         if (pnode->addr == addrNode)
1479                         {
1480                             it = lservAddressesToAdd.erase(it);
1481                             it--;
1482                             break;
1483                         }
1484         }
1485         BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd)
1486         {
1487             CSemaphoreGrant grant(*semOutbound);
1488             OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
1489             MilliSleep(500);
1490         }
1491         MilliSleep(120000); // Retry every 2 minutes
1492     }
1493 }
1494
1495 // if successful, this moves the passed grant to the constructed node
1496 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *pszDest, bool fOneShot)
1497 {
1498     //
1499     // Initiate outbound network connection
1500     //
1501     boost::this_thread::interruption_point();
1502     if (!pszDest) {
1503         if (IsLocal(addrConnect) ||
1504             FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1505             FindNode(addrConnect.ToStringIPPort()))
1506             return false;
1507     } else if (FindNode(std::string(pszDest)))
1508         return false;
1509
1510     CNode* pnode = ConnectNode(addrConnect, pszDest);
1511     boost::this_thread::interruption_point();
1512
1513     if (!pnode)
1514         return false;
1515     if (grantOutbound)
1516         grantOutbound->MoveTo(pnode->grantOutbound);
1517     pnode->fNetworkNode = true;
1518     if (fOneShot)
1519         pnode->fOneShot = true;
1520
1521     return true;
1522 }
1523
1524
1525 void ThreadMessageHandler()
1526 {
1527     boost::mutex condition_mutex;
1528     boost::unique_lock<boost::mutex> lock(condition_mutex);
1529
1530     SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1531     while (true)
1532     {
1533         vector<CNode*> vNodesCopy;
1534         {
1535             LOCK(cs_vNodes);
1536             vNodesCopy = vNodes;
1537             BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1538                 pnode->AddRef();
1539             }
1540         }
1541
1542         // Poll the connected nodes for messages
1543         CNode* pnodeTrickle = NULL;
1544         if (!vNodesCopy.empty())
1545             pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1546
1547         bool fSleep = true;
1548
1549         BOOST_FOREACH(CNode* pnode, vNodesCopy)
1550         {
1551             if (pnode->fDisconnect)
1552                 continue;
1553
1554             // Receive messages
1555             {
1556                 TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
1557                 if (lockRecv)
1558                 {
1559                     if (!g_signals.ProcessMessages(pnode))
1560                         pnode->CloseSocketDisconnect();
1561
1562                     if (pnode->nSendSize < SendBufferSize())
1563                     {
1564                         if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete()))
1565                         {
1566                             fSleep = false;
1567                         }
1568                     }
1569                 }
1570             }
1571             boost::this_thread::interruption_point();
1572
1573             // Send messages
1574             {
1575                 TRY_LOCK(pnode->cs_vSend, lockSend);
1576                 if (lockSend)
1577                     g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted);
1578             }
1579             boost::this_thread::interruption_point();
1580         }
1581
1582         {
1583             LOCK(cs_vNodes);
1584             BOOST_FOREACH(CNode* pnode, vNodesCopy)
1585                 pnode->Release();
1586         }
1587
1588         if (fSleep)
1589             messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100));
1590     }
1591 }
1592
1593
1594
1595
1596
1597
1598 bool BindListenPort(const CService &addrBind, string& strError, bool fWhitelisted)
1599 {
1600     strError = "";
1601     int nOne = 1;
1602
1603     // Create socket for listening for incoming connections
1604     struct sockaddr_storage sockaddr;
1605     socklen_t len = sizeof(sockaddr);
1606     if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1607     {
1608         strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
1609         LogPrintf("%s\n", strError);
1610         return false;
1611     }
1612
1613     SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1614     if (hListenSocket == INVALID_SOCKET)
1615     {
1616         strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
1617         LogPrintf("%s\n", strError);
1618         return false;
1619     }
1620     if (!IsSelectableSocket(hListenSocket))
1621     {
1622         strError = "Error: Couldn't create a listenable socket for incoming connections";
1623         LogPrintf("%s\n", strError);
1624         return false;
1625     }
1626
1627
1628 #ifndef WIN32
1629 #ifdef SO_NOSIGPIPE
1630     // Different way of disabling SIGPIPE on BSD
1631     setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1632 #endif
1633     // Allow binding if the port is still in TIME_WAIT state after
1634     // the program was closed and restarted.
1635     setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1636     // Disable Nagle's algorithm
1637     setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (void*)&nOne, sizeof(int));
1638 #else
1639     setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&nOne, sizeof(int));
1640     setsockopt(hListenSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&nOne, sizeof(int));
1641 #endif
1642
1643     // Set to non-blocking, incoming connections will also inherit this
1644     if (!SetSocketNonBlocking(hListenSocket, true)) {
1645         strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
1646         LogPrintf("%s\n", strError);
1647         return false;
1648     }
1649
1650     // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1651     // and enable it by default or not. Try to enable it, if possible.
1652     if (addrBind.IsIPv6()) {
1653 #ifdef IPV6_V6ONLY
1654 #ifdef WIN32
1655         setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1656 #else
1657         setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1658 #endif
1659 #endif
1660 #ifdef WIN32
1661         int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
1662         setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
1663 #endif
1664     }
1665
1666     if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1667     {
1668         int nErr = WSAGetLastError();
1669         if (nErr == WSAEADDRINUSE)
1670             strError = strprintf(_("Unable to bind to %s on this computer. Zcash is probably already running."), addrBind.ToString());
1671         else
1672             strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
1673         LogPrintf("%s\n", strError);
1674         CloseSocket(hListenSocket);
1675         return false;
1676     }
1677     LogPrintf("Bound to %s\n", addrBind.ToString());
1678
1679     // Listen for incoming connections
1680     if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1681     {
1682         strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
1683         LogPrintf("%s\n", strError);
1684         CloseSocket(hListenSocket);
1685         return false;
1686     }
1687
1688     vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
1689
1690     if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
1691         AddLocal(addrBind, LOCAL_BIND);
1692
1693     return true;
1694 }
1695
1696 void static Discover(boost::thread_group& threadGroup)
1697 {
1698     if (!fDiscover)
1699         return;
1700
1701 #ifdef WIN32
1702     // Get local host IP
1703     char pszHostName[256] = "";
1704     if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1705     {
1706         vector<CNetAddr> vaddr;
1707         if (LookupHost(pszHostName, vaddr))
1708         {
1709             BOOST_FOREACH (const CNetAddr &addr, vaddr)
1710             {
1711                 if (AddLocal(addr, LOCAL_IF))
1712                     LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
1713             }
1714         }
1715     }
1716 #else
1717     // Get local host ip
1718     struct ifaddrs* myaddrs;
1719     if (getifaddrs(&myaddrs) == 0)
1720     {
1721         for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1722         {
1723             if (ifa->ifa_addr == NULL) continue;
1724             if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1725             if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1726             if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1727             if (ifa->ifa_addr->sa_family == AF_INET)
1728             {
1729                 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1730                 CNetAddr addr(s4->sin_addr);
1731                 if (AddLocal(addr, LOCAL_IF))
1732                     LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
1733             }
1734             else if (ifa->ifa_addr->sa_family == AF_INET6)
1735             {
1736                 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1737                 CNetAddr addr(s6->sin6_addr);
1738                 if (AddLocal(addr, LOCAL_IF))
1739                     LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
1740             }
1741         }
1742         freeifaddrs(myaddrs);
1743     }
1744 #endif
1745 }
1746
1747 void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler)
1748 {
1749     uiInterface.InitMessage(_("Loading addresses..."));
1750     // Load addresses for peers.dat
1751     int64_t nStart = GetTimeMillis();
1752     {
1753         CAddrDB adb;
1754         if (!adb.Read(addrman))
1755             LogPrintf("Invalid or missing peers.dat; recreating\n");
1756     }
1757     LogPrintf("Loaded %i addresses from peers.dat  %dms\n",
1758            addrman.size(), GetTimeMillis() - nStart);
1759     fAddressesInitialized = true;
1760
1761     if (semOutbound == NULL) {
1762         // initialize semaphore
1763         int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
1764         semOutbound = new CSemaphore(nMaxOutbound);
1765     }
1766
1767     if (pnodeLocalHost == NULL)
1768         pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1769
1770     Discover(threadGroup);
1771
1772     //
1773     // Start threads
1774     //
1775
1776     if (!GetBoolArg("-dnsseed", true))
1777         LogPrintf("DNS seeding disabled\n");
1778     else
1779         threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
1780
1781     // Send and receive from sockets, accept connections
1782     threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
1783
1784     // Initiate outbound connections from -addnode
1785     threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
1786
1787     // Initiate outbound connections
1788     threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
1789
1790     // Process messages
1791     threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
1792
1793     // Dump network addresses
1794     scheduler.scheduleEvery(&DumpAddresses, DUMP_ADDRESSES_INTERVAL);
1795 }
1796
1797 bool StopNode()
1798 {
1799     LogPrintf("StopNode()\n");
1800     if (semOutbound)
1801         for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1802             semOutbound->post();
1803
1804     if (fAddressesInitialized)
1805     {
1806         DumpAddresses();
1807         fAddressesInitialized = false;
1808     }
1809
1810     return true;
1811 }
1812
1813 static class CNetCleanup
1814 {
1815 public:
1816     CNetCleanup() {}
1817
1818     ~CNetCleanup()
1819     {
1820         // Close sockets
1821         BOOST_FOREACH(CNode* pnode, vNodes)
1822             if (pnode->hSocket != INVALID_SOCKET)
1823                 CloseSocket(pnode->hSocket);
1824         BOOST_FOREACH(ListenSocket& hListenSocket, vhListenSocket)
1825             if (hListenSocket.socket != INVALID_SOCKET)
1826                 if (!CloseSocket(hListenSocket.socket))
1827                     LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
1828
1829         // clean up some globals (to help leak detection)
1830         BOOST_FOREACH(CNode *pnode, vNodes)
1831             delete pnode;
1832         BOOST_FOREACH(CNode *pnode, vNodesDisconnected)
1833             delete pnode;
1834         vNodes.clear();
1835         vNodesDisconnected.clear();
1836         vhListenSocket.clear();
1837         delete semOutbound;
1838         semOutbound = NULL;
1839         delete pnodeLocalHost;
1840         pnodeLocalHost = NULL;
1841
1842 #ifdef WIN32
1843         // Shutdown Windows Sockets
1844         WSACleanup();
1845 #endif
1846     }
1847 }
1848 instance_of_cnetcleanup;
1849
1850
1851
1852
1853
1854
1855
1856 void RelayTransaction(const CTransaction& tx)
1857 {
1858     CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
1859     ss.reserve(10000);
1860     ss << tx;
1861     RelayTransaction(tx, ss);
1862 }
1863
1864 void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
1865 {
1866     CInv inv(MSG_TX, tx.GetHash());
1867     {
1868         LOCK(cs_mapRelay);
1869         // Expire old relay messages
1870         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
1871         {
1872             mapRelay.erase(vRelayExpiration.front().second);
1873             vRelayExpiration.pop_front();
1874         }
1875
1876         // Save original serialized message so newer versions are preserved
1877         mapRelay.insert(std::make_pair(inv, ss));
1878         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1879     }
1880     LOCK(cs_vNodes);
1881     BOOST_FOREACH(CNode* pnode, vNodes)
1882     {
1883         if(!pnode->fRelayTxes)
1884             continue;
1885         LOCK(pnode->cs_filter);
1886         if (pnode->pfilter)
1887         {
1888             if (pnode->pfilter->IsRelevantAndUpdate(tx))
1889                 pnode->PushInventory(inv);
1890         } else
1891             pnode->PushInventory(inv);
1892     }
1893 }
1894
1895 void CNode::RecordBytesRecv(uint64_t bytes)
1896 {
1897     LOCK(cs_totalBytesRecv);
1898     nTotalBytesRecv += bytes;
1899 }
1900
1901 void CNode::RecordBytesSent(uint64_t bytes)
1902 {
1903     LOCK(cs_totalBytesSent);
1904     nTotalBytesSent += bytes;
1905 }
1906
1907 uint64_t CNode::GetTotalBytesRecv()
1908 {
1909     LOCK(cs_totalBytesRecv);
1910     return nTotalBytesRecv;
1911 }
1912
1913 uint64_t CNode::GetTotalBytesSent()
1914 {
1915     LOCK(cs_totalBytesSent);
1916     return nTotalBytesSent;
1917 }
1918
1919 void CNode::Fuzz(int nChance)
1920 {
1921     if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
1922     if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
1923
1924     switch (GetRand(3))
1925     {
1926     case 0:
1927         // xor a random byte with a random value:
1928         if (!ssSend.empty()) {
1929             CDataStream::size_type pos = GetRand(ssSend.size());
1930             ssSend[pos] ^= (unsigned char)(GetRand(256));
1931         }
1932         break;
1933     case 1:
1934         // delete a random byte:
1935         if (!ssSend.empty()) {
1936             CDataStream::size_type pos = GetRand(ssSend.size());
1937             ssSend.erase(ssSend.begin()+pos);
1938         }
1939         break;
1940     case 2:
1941         // insert a random byte at a random position
1942         {
1943             CDataStream::size_type pos = GetRand(ssSend.size());
1944             char ch = (char)GetRand(256);
1945             ssSend.insert(ssSend.begin()+pos, ch);
1946         }
1947         break;
1948     }
1949     // Chance of more than one change half the time:
1950     // (more changes exponentially less likely):
1951     Fuzz(2);
1952 }
1953
1954 //
1955 // CAddrDB
1956 //
1957
1958 CAddrDB::CAddrDB()
1959 {
1960     pathAddr = GetDataDir() / "peers.dat";
1961 }
1962
1963 bool CAddrDB::Write(const CAddrMan& addr)
1964 {
1965     // Generate random temporary filename
1966     unsigned short randv = 0;
1967     GetRandBytes((unsigned char*)&randv, sizeof(randv));
1968     std::string tmpfn = strprintf("peers.dat.%04x", randv);
1969
1970     // serialize addresses, checksum data up to that point, then append csum
1971     CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
1972     ssPeers << FLATDATA(Params().MessageStart());
1973     ssPeers << addr;
1974     uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
1975     ssPeers << hash;
1976
1977     // open temp output file, and associate with CAutoFile
1978     boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
1979     FILE *file = fopen(pathTmp.string().c_str(), "wb");
1980     CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
1981     if (fileout.IsNull())
1982         return error("%s: Failed to open file %s", __func__, pathTmp.string());
1983
1984     // Write and commit header, data
1985     try {
1986         fileout << ssPeers;
1987     }
1988     catch (const std::exception& e) {
1989         return error("%s: Serialize or I/O error - %s", __func__, e.what());
1990     }
1991     FileCommit(fileout.Get());
1992     fileout.fclose();
1993
1994     // replace existing peers.dat, if any, with new peers.dat.XXXX
1995     if (!RenameOver(pathTmp, pathAddr))
1996         return error("%s: Rename-into-place failed", __func__);
1997
1998     return true;
1999 }
2000
2001 bool CAddrDB::Read(CAddrMan& addr)
2002 {
2003     // open input file, and associate with CAutoFile
2004     FILE *file = fopen(pathAddr.string().c_str(), "rb");
2005     CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
2006     if (filein.IsNull())
2007         return error("%s: Failed to open file %s", __func__, pathAddr.string());
2008
2009     // use file size to size memory buffer
2010     int fileSize = boost::filesystem::file_size(pathAddr);
2011     int dataSize = fileSize - sizeof(uint256);
2012     // Don't try to resize to a negative number if file is small
2013     if (dataSize < 0)
2014         dataSize = 0;
2015     vector<unsigned char> vchData;
2016     vchData.resize(dataSize);
2017     uint256 hashIn;
2018
2019     // read data and checksum from file
2020     try {
2021         filein.read((char *)&vchData[0], dataSize);
2022         filein >> hashIn;
2023     }
2024     catch (const std::exception& e) {
2025         return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2026     }
2027     filein.fclose();
2028
2029     CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
2030
2031     // verify stored checksum matches input data
2032     uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
2033     if (hashIn != hashTmp)
2034         return error("%s: Checksum mismatch, data corrupted", __func__);
2035
2036     unsigned char pchMsgTmp[4];
2037     try {
2038         // de-serialize file header (network specific magic number) and ..
2039         ssPeers >> FLATDATA(pchMsgTmp);
2040
2041         // ... verify the network matches ours
2042         if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
2043             return error("%s: Invalid network magic number", __func__);
2044
2045         // de-serialize address data into one CAddrMan object
2046         ssPeers >> addr;
2047     }
2048     catch (const std::exception& e) {
2049         return error("%s: Deserialize or I/O error - %s", __func__, e.what());
2050     }
2051
2052     return true;
2053 }
2054
2055 unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
2056 unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
2057
2058 CNode::CNode(SOCKET hSocketIn, const CAddress& addrIn, const std::string& addrNameIn, bool fInboundIn) :
2059     ssSend(SER_NETWORK, INIT_PROTO_VERSION),
2060     addrKnown(5000, 0.001),
2061     setInventoryKnown(SendBufferSize() / 1000)
2062 {
2063     nServices = 0;
2064     hSocket = hSocketIn;
2065     nRecvVersion = INIT_PROTO_VERSION;
2066     nLastSend = 0;
2067     nLastRecv = 0;
2068     nSendBytes = 0;
2069     nRecvBytes = 0;
2070     nTimeConnected = GetTime();
2071     nTimeOffset = 0;
2072     addr = addrIn;
2073     addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
2074     nVersion = 0;
2075     strSubVer = "";
2076     fWhitelisted = false;
2077     fOneShot = false;
2078     fClient = false; // set by version message
2079     fInbound = fInboundIn;
2080     fNetworkNode = false;
2081     fSuccessfullyConnected = false;
2082     fDisconnect = false;
2083     nRefCount = 0;
2084     nSendSize = 0;
2085     nSendOffset = 0;
2086     hashContinue = uint256();
2087     nStartingHeight = -1;
2088     fGetAddr = false;
2089     fRelayTxes = false;
2090     fSentAddr = false;
2091     pfilter = new CBloomFilter();
2092     nPingNonceSent = 0;
2093     nPingUsecStart = 0;
2094     nPingUsecTime = 0;
2095     fPingQueued = false;
2096     nMinPingUsecTime = std::numeric_limits<int64_t>::max();
2097
2098     {
2099         LOCK(cs_nLastNodeId);
2100         id = nLastNodeId++;
2101     }
2102
2103     if (fLogIPs)
2104         LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
2105     else
2106         LogPrint("net", "Added connection peer=%d\n", id);
2107
2108     // Be shy and don't send version until we hear
2109     if (hSocket != INVALID_SOCKET && !fInbound)
2110         PushVersion();
2111
2112     GetNodeSignals().InitializeNode(GetId(), this);
2113 }
2114
2115 CNode::~CNode()
2116 {
2117     CloseSocket(hSocket);
2118
2119     if (pfilter)
2120         delete pfilter;
2121
2122     GetNodeSignals().FinalizeNode(GetId());
2123 }
2124
2125 void CNode::AskFor(const CInv& inv)
2126 {
2127     if (mapAskFor.size() > MAPASKFOR_MAX_SZ || setAskFor.size() > SETASKFOR_MAX_SZ)
2128         return;
2129     // a peer may not have multiple non-responded queue positions for a single inv item
2130     if (!setAskFor.insert(inv.hash).second)
2131         return;
2132
2133     // We're using mapAskFor as a priority queue,
2134     // the key is the earliest time the request can be sent
2135     int64_t nRequestTime;
2136     limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
2137     if (it != mapAlreadyAskedFor.end())
2138         nRequestTime = it->second;
2139     else
2140         nRequestTime = 0;
2141     LogPrint("net", "askfor %s  %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000), id);
2142
2143     // Make sure not to reuse time indexes to keep things in the same order
2144     int64_t nNow = GetTimeMicros() - 1000000;
2145     static int64_t nLastTime;
2146     ++nLastTime;
2147     nNow = std::max(nNow, nLastTime);
2148     nLastTime = nNow;
2149
2150     // Each retry is 2 minutes after the last
2151     nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
2152     if (it != mapAlreadyAskedFor.end())
2153         mapAlreadyAskedFor.update(it, nRequestTime);
2154     else
2155         mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
2156     mapAskFor.insert(std::make_pair(nRequestTime, inv));
2157 }
2158
2159 void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
2160 {
2161     ENTER_CRITICAL_SECTION(cs_vSend);
2162     assert(ssSend.size() == 0);
2163     ssSend << CMessageHeader(Params().MessageStart(), pszCommand, 0);
2164     LogPrint("net", "sending: %s ", SanitizeString(pszCommand));
2165 }
2166
2167 void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
2168 {
2169     ssSend.clear();
2170
2171     LEAVE_CRITICAL_SECTION(cs_vSend);
2172
2173     LogPrint("net", "(aborted)\n");
2174 }
2175
2176 void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
2177 {
2178     // The -*messagestest options are intentionally not documented in the help message,
2179     // since they are only used during development to debug the networking code and are
2180     // not intended for end-users.
2181     if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0)
2182     {
2183         LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
2184         AbortMessage();
2185         return;
2186     }
2187     if (mapArgs.count("-fuzzmessagestest"))
2188         Fuzz(GetArg("-fuzzmessagestest", 10));
2189
2190     if (ssSend.size() == 0)
2191     {
2192         LEAVE_CRITICAL_SECTION(cs_vSend);
2193         return;
2194     }
2195     // Set the size
2196     unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
2197     WriteLE32((uint8_t*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], nSize);
2198
2199     // Set the checksum
2200     uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
2201     unsigned int nChecksum = 0;
2202     memcpy(&nChecksum, &hash, sizeof(nChecksum));
2203     assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
2204     memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
2205
2206     LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
2207
2208     std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
2209     ssSend.GetAndClear(*it);
2210     nSendSize += (*it).size();
2211
2212     // If write queue empty, attempt "optimistic write"
2213     if (it == vSendMsg.begin())
2214         SocketSendData(this);
2215
2216     LEAVE_CRITICAL_SECTION(cs_vSend);
2217 }
This page took 0.150433 seconds and 4 git commands to generate.