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