Add traffic monitor
[novacoin.git] / src / net.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #include "irc.h"
7 #include "db.h"
8 #include "net.h"
9 #include "init.h"
10 #include "strlcpy.h"
11 #include "addrman.h"
12 #include "ui_interface.h"
13
14 #ifdef WIN32
15 #include <string.h>
16 #endif
17
18 #ifdef USE_UPNP
19 #include <miniupnpc/miniwget.h>
20 #include <miniupnpc/miniupnpc.h>
21 #include <miniupnpc/upnpcommands.h>
22 #include <miniupnpc/upnperrors.h>
23 #endif
24
25 using namespace std;
26 using namespace boost;
27
28 static const int MAX_OUTBOUND_CONNECTIONS = 16;
29
30 void ThreadMessageHandler2(void* parg);
31 void ThreadSocketHandler2(void* parg);
32 void ThreadOpenConnections2(void* parg);
33 void ThreadOpenAddedConnections2(void* parg);
34 #ifdef USE_UPNP
35 void ThreadMapPort2(void* parg);
36 #endif
37 void ThreadDNSAddressSeed2(void* parg);
38 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
39
40
41 struct LocalServiceInfo {
42     int nScore;
43     int nPort;
44 };
45
46 //
47 // Global state variables
48 //
49 bool fClient = false;
50 bool fDiscover = true;
51 bool fUseUPnP = false;
52 uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);
53 static CCriticalSection cs_mapLocalHost;
54 static map<CNetAddr, LocalServiceInfo> mapLocalHost;
55 static bool vfReachable[NET_MAX] = {};
56 static bool vfLimited[NET_MAX] = {};
57 static CNode* pnodeLocalHost = NULL;
58 static CNode* pnodeSync = NULL;
59 CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices);
60 uint64 nLocalHostNonce = 0;
61 boost::array<int, THREAD_MAX> vnThreadsRunning;
62 static std::vector<SOCKET> vhListenSocket;
63 CAddrMan addrman;
64
65 vector<CNode*> vNodes;
66 CCriticalSection cs_vNodes;
67 map<CInv, CDataStream> mapRelay;
68 deque<pair<int64, CInv> > vRelayExpiration;
69 CCriticalSection cs_mapRelay;
70 map<CInv, int64> mapAlreadyAskedFor;
71
72 static deque<string> vOneShots;
73 CCriticalSection cs_vOneShots;
74
75 set<CNetAddr> setservAddNodeAddresses;
76 CCriticalSection cs_setservAddNodeAddresses;
77
78 static CSemaphore *semOutbound = NULL;
79
80 void AddOneShot(string strDest)
81 {
82     LOCK(cs_vOneShots);
83     vOneShots.push_back(strDest);
84 }
85
86 unsigned short GetListenPort()
87 {
88     return (unsigned short)(GetArg("-port", GetDefaultPort()));
89 }
90
91 void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
92 {
93     // Filter out duplicate requests
94     if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
95         return;
96     pindexLastGetBlocksBegin = pindexBegin;
97     hashLastGetBlocksEnd = hashEnd;
98
99     PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
100 }
101
102 // find 'best' local address for a particular peer
103 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
104 {
105     if (fNoListen)
106         return false;
107
108     int nBestScore = -1;
109     int nBestReachability = -1;
110     {
111         LOCK(cs_mapLocalHost);
112         for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
113         {
114             int nScore = (*it).second.nScore;
115             int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
116             if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
117             {
118                 addr = CService((*it).first, (*it).second.nPort);
119                 nBestReachability = nReachability;
120                 nBestScore = nScore;
121             }
122         }
123     }
124     return nBestScore >= 0;
125 }
126
127 // get best local address for a particular peer as a CAddress
128 CAddress GetLocalAddress(const CNetAddr *paddrPeer)
129 {
130     CAddress ret(CService("0.0.0.0",0),0);
131     CService addr;
132     if (GetLocal(addr, paddrPeer))
133     {
134         ret = CAddress(addr);
135         ret.nServices = nLocalServices;
136         ret.nTime = GetAdjustedTime();
137     }
138     return ret;
139 }
140
141 bool RecvLine(SOCKET hSocket, string& strLine)
142 {
143     strLine = "";
144     while (true)
145     {
146         char c;
147         int nBytes = recv(hSocket, &c, 1, 0);
148         if (nBytes > 0)
149         {
150             if (c == '\n')
151                 continue;
152             if (c == '\r')
153                 return true;
154             strLine += c;
155             if (strLine.size() >= 9000)
156                 return true;
157         }
158         else if (nBytes <= 0)
159         {
160             if (fShutdown)
161                 return false;
162             if (nBytes < 0)
163             {
164                 int nErr = WSAGetLastError();
165                 if (nErr == WSAEMSGSIZE)
166                     continue;
167                 if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
168                 {
169                     Sleep(10);
170                     continue;
171                 }
172             }
173             if (!strLine.empty())
174                 return true;
175             if (nBytes == 0)
176             {
177                 // socket closed
178                 printf("socket closed\n");
179                 return false;
180             }
181             else
182             {
183                 // socket error
184                 int nErr = WSAGetLastError();
185                 printf("recv failed: %d\n", nErr);
186                 return false;
187             }
188         }
189     }
190 }
191
192 // used when scores of local addresses may have changed
193 // pushes better local address to peers
194 void static AdvertizeLocal()
195 {
196     LOCK(cs_vNodes);
197     BOOST_FOREACH(CNode* pnode, vNodes)
198     {
199         if (pnode->fSuccessfullyConnected)
200         {
201             CAddress addrLocal = GetLocalAddress(&pnode->addr);
202             if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
203             {
204                 pnode->PushAddress(addrLocal);
205                 pnode->addrLocal = addrLocal;
206             }
207         }
208     }
209 }
210
211 void SetReachable(enum Network net, bool fFlag)
212 {
213     LOCK(cs_mapLocalHost);
214     vfReachable[net] = fFlag;
215     if (net == NET_IPV6 && fFlag)
216         vfReachable[NET_IPV4] = true;
217 }
218
219 // learn a new local address
220 bool AddLocal(const CService& addr, int nScore)
221 {
222     if (!addr.IsRoutable())
223         return false;
224
225     if (!fDiscover && nScore < LOCAL_MANUAL)
226         return false;
227
228     if (IsLimited(addr))
229         return false;
230
231     printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
232
233     {
234         LOCK(cs_mapLocalHost);
235         bool fAlready = mapLocalHost.count(addr) > 0;
236         LocalServiceInfo &info = mapLocalHost[addr];
237         if (!fAlready || nScore >= info.nScore) {
238             info.nScore = nScore + (fAlready ? 1 : 0);
239             info.nPort = addr.GetPort();
240         }
241         SetReachable(addr.GetNetwork());
242     }
243
244     AdvertizeLocal();
245
246     return true;
247 }
248
249 bool AddLocal(const CNetAddr &addr, int nScore)
250 {
251     return AddLocal(CService(addr, GetListenPort()), nScore);
252 }
253
254 /** Make a particular network entirely off-limits (no automatic connects to it) */
255 void SetLimited(enum Network net, bool fLimited)
256 {
257     if (net == NET_UNROUTABLE)
258         return;
259     LOCK(cs_mapLocalHost);
260     vfLimited[net] = fLimited;
261 }
262
263 bool IsLimited(enum Network net)
264 {
265     LOCK(cs_mapLocalHost);
266     return vfLimited[net];
267 }
268
269 bool IsLimited(const CNetAddr &addr)
270 {
271     return IsLimited(addr.GetNetwork());
272 }
273
274 /** vote for a local address */
275 bool SeenLocal(const CService& addr)
276 {
277     {
278         LOCK(cs_mapLocalHost);
279         if (mapLocalHost.count(addr) == 0)
280             return false;
281         mapLocalHost[addr].nScore++;
282     }
283
284     AdvertizeLocal();
285
286     return true;
287 }
288
289 /** check whether a given address is potentially local */
290 bool IsLocal(const CService& addr)
291 {
292     LOCK(cs_mapLocalHost);
293     return mapLocalHost.count(addr) > 0;
294 }
295
296 /** check whether a given address is in a network we can probably connect to */
297 bool IsReachable(const CNetAddr& addr)
298 {
299     LOCK(cs_mapLocalHost);
300     enum Network net = addr.GetNetwork();
301     return vfReachable[net] && !vfLimited[net];
302 }
303
304 bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
305 {
306     SOCKET hSocket;
307     if (!ConnectSocket(addrConnect, hSocket))
308         return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
309
310     send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
311
312     string strLine;
313     while (RecvLine(hSocket, strLine))
314     {
315         if (strLine.empty()) // HTTP response is separated from headers by blank line
316         {
317             while (true)
318             {
319                 if (!RecvLine(hSocket, strLine))
320                 {
321                     closesocket(hSocket);
322                     return false;
323                 }
324                 if (pszKeyword == NULL)
325                     break;
326                 if (strLine.find(pszKeyword) != string::npos)
327                 {
328                     strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
329                     break;
330                 }
331             }
332             closesocket(hSocket);
333             if (strLine.find("<") != string::npos)
334                 strLine = strLine.substr(0, strLine.find("<"));
335             strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
336             while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
337                 strLine.resize(strLine.size()-1);
338             CService addr(strLine,0,true);
339             printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
340             if (!addr.IsValid() || !addr.IsRoutable())
341                 return false;
342             ipRet.SetIP(addr);
343             return true;
344         }
345     }
346     closesocket(hSocket);
347     return error("GetMyExternalIP() : connection closed");
348 }
349
350 // We now get our external IP from the IRC server first and only use this as a backup
351 bool GetMyExternalIP(CNetAddr& ipRet)
352 {
353     CService addrConnect;
354     const char* pszGet;
355     const char* pszKeyword;
356
357     for (int nLookup = 0; nLookup <= 1; nLookup++)
358     for (int nHost = 1; nHost <= 2; nHost++)
359     {
360         // We should be phasing out our use of sites like these.  If we need
361         // replacements, we should ask for volunteers to put this simple
362         // php file on their web server that prints the client IP:
363         //  <?php echo $_SERVER["REMOTE_ADDR"]; ?>
364         if (nHost == 1)
365         {
366             addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
367
368             if (nLookup == 1)
369             {
370                 CService addrIP("checkip.dyndns.org", 80, true);
371                 if (addrIP.IsValid())
372                     addrConnect = addrIP;
373             }
374
375             pszGet = "GET / HTTP/1.1\r\n"
376                      "Host: checkip.dyndns.org\r\n"
377                      "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
378                      "Connection: close\r\n"
379                      "\r\n";
380
381             pszKeyword = "Address:";
382         }
383         else if (nHost == 2)
384         {
385             addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
386
387             if (nLookup == 1)
388             {
389                 CService addrIP("www.showmyip.com", 80, true);
390                 if (addrIP.IsValid())
391                     addrConnect = addrIP;
392             }
393
394             pszGet = "GET /simple/ HTTP/1.1\r\n"
395                      "Host: www.showmyip.com\r\n"
396                      "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
397                      "Connection: close\r\n"
398                      "\r\n";
399
400             pszKeyword = NULL; // Returns just IP address
401         }
402
403         if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
404             return true;
405     }
406
407     return false;
408 }
409
410 void ThreadGetMyExternalIP(void* parg)
411 {
412     // Make this thread recognisable as the external IP detection thread
413     RenameThread("novacoin-ext-ip");
414
415     CNetAddr addrLocalHost;
416     if (GetMyExternalIP(addrLocalHost))
417     {
418         printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
419         AddLocal(addrLocalHost, LOCAL_HTTP);
420     }
421 }
422
423
424
425
426
427 void AddressCurrentlyConnected(const CService& addr)
428 {
429     addrman.Connected(addr);
430 }
431
432
433
434
435 uint64_t CNode::nTotalBytesRecv = 0;
436 uint64_t CNode::nTotalBytesSent = 0;
437 CCriticalSection CNode::cs_totalBytesRecv;
438 CCriticalSection CNode::cs_totalBytesSent;
439
440 CNode* FindNode(const CNetAddr& ip)
441 {
442     LOCK(cs_vNodes);
443     BOOST_FOREACH(CNode* pnode, vNodes)
444         if ((CNetAddr)pnode->addr == ip)
445             return (pnode);
446     return NULL;
447 }
448
449 CNode* FindNode(std::string addrName)
450 {
451     LOCK(cs_vNodes);
452     BOOST_FOREACH(CNode* pnode, vNodes)
453         if (pnode->addrName == addrName)
454             return (pnode);
455     return NULL;
456 }
457
458 CNode* FindNode(const CService& addr)
459 {
460     LOCK(cs_vNodes);
461     BOOST_FOREACH(CNode* pnode, vNodes)
462         if ((CService)pnode->addr == addr)
463             return (pnode);
464     return NULL;
465 }
466
467 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
468 {
469     if (pszDest == NULL) {
470         if (IsLocal(addrConnect))
471             return NULL;
472
473         // Look for an existing connection
474         CNode* pnode = FindNode((CService)addrConnect);
475         if (pnode)
476         {
477             if (nTimeout != 0)
478                 pnode->AddRef(nTimeout);
479             else
480                 pnode->AddRef();
481             return pnode;
482         }
483     }
484
485
486     /// debug print
487     printf("trying connection %s lastseen=%.1fhrs\n",
488         pszDest ? pszDest : addrConnect.ToString().c_str(),
489         pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
490
491     // Connect
492     SOCKET hSocket;
493     if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
494     {
495         addrman.Attempt(addrConnect);
496
497         /// debug print
498         printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
499
500         // Set to non-blocking
501 #ifdef WIN32
502         u_long nOne = 1;
503         if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
504             printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
505 #else
506         if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
507             printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
508 #endif
509
510         // Add node
511         CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
512         if (nTimeout != 0)
513             pnode->AddRef(nTimeout);
514         else
515             pnode->AddRef();
516
517         {
518             LOCK(cs_vNodes);
519             vNodes.push_back(pnode);
520         }
521
522         pnode->nTimeConnected = GetTime();
523         return pnode;
524     }
525     else
526     {
527         return NULL;
528     }
529 }
530
531 void CNode::CloseSocketDisconnect()
532 {
533     fDisconnect = true;
534     if (hSocket != INVALID_SOCKET)
535     {
536         printf("disconnecting node %s\n", addrName.c_str());
537         closesocket(hSocket);
538         hSocket = INVALID_SOCKET;
539         vRecv.clear();
540     }
541
542     // in case this fails, we'll empty the recv buffer when the CNode is deleted
543     TRY_LOCK(cs_vRecv, lockRecv);
544     if (lockRecv)
545         vRecv.clear();
546
547     // if this was the sync node, we'll need a new one
548     if (this == pnodeSync)
549         pnodeSync = NULL;
550 }
551
552 void CNode::Cleanup()
553 {
554 }
555
556
557 void CNode::PushVersion()
558 {
559     /// when NTP implemented, change to just nTime = GetAdjustedTime()
560     int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
561     CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
562     CAddress addrMe = GetLocalAddress(&addr);
563     RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
564     printf("send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString().c_str(), addrYou.ToString().c_str(), addr.ToString().c_str());
565     PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
566                 nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
567 }
568
569
570
571
572
573 std::map<CNetAddr, int64> CNode::setBanned;
574 CCriticalSection CNode::cs_setBanned;
575
576 void CNode::ClearBanned()
577 {
578     setBanned.clear();
579 }
580
581 bool CNode::IsBanned(CNetAddr ip)
582 {
583     bool fResult = false;
584     {
585         LOCK(cs_setBanned);
586         std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
587         if (i != setBanned.end())
588         {
589             int64 t = (*i).second;
590             if (GetTime() < t)
591                 fResult = true;
592         }
593     }
594     return fResult;
595 }
596
597 bool CNode::Misbehaving(int howmuch)
598 {
599     if (addr.IsLocal())
600     {
601         printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
602         return false;
603     }
604
605     nMisbehavior += howmuch;
606     if (nMisbehavior >= GetArg("-banscore", 100))
607     {
608         int64 banTime = GetTime()+GetArg("-bantime", 60*60*24);  // Default 24-hour ban
609         printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
610         {
611             LOCK(cs_setBanned);
612             if (setBanned[addr] < banTime)
613                 setBanned[addr] = banTime;
614         }
615         CloseSocketDisconnect();
616         return true;
617     } else
618         printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
619     return false;
620 }
621
622 #undef X
623 #define X(name) stats.name = name
624 void CNode::copyStats(CNodeStats &stats)
625 {
626     X(nServices);
627     X(nLastSend);
628     X(nLastRecv);
629     X(nTimeConnected);
630     X(addrName);
631     X(nVersion);
632     X(strSubVer);
633     X(fInbound);
634     X(nReleaseTime);
635     X(nStartingHeight);
636     X(nMisbehavior);
637     X(nSendBytes);
638     X(nRecvBytes);
639     stats.fSyncNode = (this == pnodeSync);
640 }
641 #undef X
642
643
644
645
646
647
648
649
650
651
652 void ThreadSocketHandler(void* parg)
653 {
654     // Make this thread recognisable as the networking thread
655     RenameThread("novacoin-net");
656
657     try
658     {
659         vnThreadsRunning[THREAD_SOCKETHANDLER]++;
660         ThreadSocketHandler2(parg);
661         vnThreadsRunning[THREAD_SOCKETHANDLER]--;
662     }
663     catch (std::exception& e) {
664         vnThreadsRunning[THREAD_SOCKETHANDLER]--;
665         PrintException(&e, "ThreadSocketHandler()");
666     } catch (...) {
667         vnThreadsRunning[THREAD_SOCKETHANDLER]--;
668         throw; // support pthread_cancel()
669     }
670     printf("ThreadSocketHandler exited\n");
671 }
672
673 void ThreadSocketHandler2(void* parg)
674 {
675     printf("ThreadSocketHandler started\n");
676     list<CNode*> vNodesDisconnected;
677     unsigned int nPrevNodeCount = 0;
678
679     while (true)
680     {
681         //
682         // Disconnect nodes
683         //
684         {
685             LOCK(cs_vNodes);
686             // Disconnect unused nodes
687             vector<CNode*> vNodesCopy = vNodes;
688             BOOST_FOREACH(CNode* pnode, vNodesCopy)
689             {
690                 if (pnode->fDisconnect ||
691                     (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
692                 {
693                     // remove from vNodes
694                     vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
695
696                     // release outbound grant (if any)
697                     pnode->grantOutbound.Release();
698
699                     // close socket and cleanup
700                     pnode->CloseSocketDisconnect();
701                     pnode->Cleanup();
702
703                     // hold in disconnected pool until all refs are released
704                     pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
705                     if (pnode->fNetworkNode || pnode->fInbound)
706                         pnode->Release();
707                     vNodesDisconnected.push_back(pnode);
708                 }
709             }
710
711             // Delete disconnected nodes
712             list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
713             BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
714             {
715                 // wait until threads are done using it
716                 if (pnode->GetRefCount() <= 0)
717                 {
718                     bool fDelete = false;
719                     {
720                         TRY_LOCK(pnode->cs_vSend, lockSend);
721                         if (lockSend)
722                         {
723                             TRY_LOCK(pnode->cs_vRecv, lockRecv);
724                             if (lockRecv)
725                             {
726                                 TRY_LOCK(pnode->cs_mapRequests, lockReq);
727                                 if (lockReq)
728                                 {
729                                     TRY_LOCK(pnode->cs_inventory, lockInv);
730                                     if (lockInv)
731                                         fDelete = true;
732                                 }
733                             }
734                         }
735                     }
736                     if (fDelete)
737                     {
738                         vNodesDisconnected.remove(pnode);
739                         delete pnode;
740                     }
741                 }
742             }
743         }
744         if (vNodes.size() != nPrevNodeCount)
745         {
746             nPrevNodeCount = vNodes.size();
747             uiInterface.NotifyNumConnectionsChanged(vNodes.size());
748         }
749
750
751         //
752         // Find which sockets have data to receive
753         //
754         struct timeval timeout;
755         timeout.tv_sec  = 0;
756         timeout.tv_usec = 50000; // frequency to poll pnode->vSend
757
758         fd_set fdsetRecv;
759         fd_set fdsetSend;
760         fd_set fdsetError;
761         FD_ZERO(&fdsetRecv);
762         FD_ZERO(&fdsetSend);
763         FD_ZERO(&fdsetError);
764         SOCKET hSocketMax = 0;
765         bool have_fds = false;
766
767         BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
768             FD_SET(hListenSocket, &fdsetRecv);
769             hSocketMax = max(hSocketMax, hListenSocket);
770             have_fds = true;
771         }
772         {
773             LOCK(cs_vNodes);
774             BOOST_FOREACH(CNode* pnode, vNodes)
775             {
776                 if (pnode->hSocket == INVALID_SOCKET)
777                     continue;
778                 FD_SET(pnode->hSocket, &fdsetRecv);
779                 FD_SET(pnode->hSocket, &fdsetError);
780                 hSocketMax = max(hSocketMax, pnode->hSocket);
781                 have_fds = true;
782                 {
783                     TRY_LOCK(pnode->cs_vSend, lockSend);
784                     if (lockSend && !pnode->vSend.empty())
785                         FD_SET(pnode->hSocket, &fdsetSend);
786                 }
787             }
788         }
789
790         vnThreadsRunning[THREAD_SOCKETHANDLER]--;
791         int nSelect = select(have_fds ? hSocketMax + 1 : 0,
792                              &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
793         vnThreadsRunning[THREAD_SOCKETHANDLER]++;
794         if (fShutdown)
795             return;
796         if (nSelect == SOCKET_ERROR)
797         {
798             if (have_fds)
799             {
800                 int nErr = WSAGetLastError();
801                 printf("socket select error %d\n", nErr);
802                 for (unsigned int i = 0; i <= hSocketMax; i++)
803                     FD_SET(i, &fdsetRecv);
804             }
805             FD_ZERO(&fdsetSend);
806             FD_ZERO(&fdsetError);
807             Sleep(timeout.tv_usec/1000);
808         }
809
810
811         //
812         // Accept new connections
813         //
814         BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
815         if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
816         {
817 #ifdef USE_IPV6
818             struct sockaddr_storage sockaddr;
819 #else
820             struct sockaddr sockaddr;
821 #endif
822             socklen_t len = sizeof(sockaddr);
823             SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
824             CAddress addr;
825             int nInbound = 0;
826
827             if (hSocket != INVALID_SOCKET)
828                 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
829                     printf("Warning: Unknown socket family\n");
830
831             {
832                 LOCK(cs_vNodes);
833                 BOOST_FOREACH(CNode* pnode, vNodes)
834                     if (pnode->fInbound)
835                         nInbound++;
836             }
837
838             if (hSocket == INVALID_SOCKET)
839             {
840                 int nErr = WSAGetLastError();
841                 if (nErr != WSAEWOULDBLOCK)
842                     printf("socket error accept failed: %d\n", nErr);
843             }
844             else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
845             {
846                 {
847                     LOCK(cs_setservAddNodeAddresses);
848                     if (!setservAddNodeAddresses.count(addr))
849                         closesocket(hSocket);
850                 }
851             }
852             else if (CNode::IsBanned(addr))
853             {
854                 printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
855                 closesocket(hSocket);
856             }
857             else
858             {
859                 printf("accepted connection %s\n", addr.ToString().c_str());
860                 CNode* pnode = new CNode(hSocket, addr, "", true);
861                 pnode->AddRef();
862                 {
863                     LOCK(cs_vNodes);
864                     vNodes.push_back(pnode);
865                 }
866             }
867         }
868
869
870         //
871         // Service each socket
872         //
873         vector<CNode*> vNodesCopy;
874         {
875             LOCK(cs_vNodes);
876             vNodesCopy = vNodes;
877             BOOST_FOREACH(CNode* pnode, vNodesCopy)
878                 pnode->AddRef();
879         }
880         BOOST_FOREACH(CNode* pnode, vNodesCopy)
881         {
882             if (fShutdown)
883                 return;
884
885             //
886             // Receive
887             //
888             if (pnode->hSocket == INVALID_SOCKET)
889                 continue;
890             if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
891             {
892                 TRY_LOCK(pnode->cs_vRecv, lockRecv);
893                 if (lockRecv)
894                 {
895                     CDataStream& vRecv = pnode->vRecv;
896                     unsigned int nPos = vRecv.size();
897
898                     if (nPos > ReceiveBufferSize()) {
899                         if (!pnode->fDisconnect)
900                             printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
901                         pnode->CloseSocketDisconnect();
902                     }
903                     else {
904                         // typical socket buffer is 8K-64K
905                         char pchBuf[0x10000];
906                         int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
907                         if (nBytes > 0)
908                         {
909                             vRecv.resize(nPos + nBytes);
910                             memcpy(&vRecv[nPos], pchBuf, nBytes);
911                             pnode->nLastRecv = GetTime();
912                             pnode->nRecvBytes += nBytes;
913                             pnode->RecordBytesRecv(nBytes);
914                         }
915                         else if (nBytes == 0)
916                         {
917                             // socket closed gracefully
918                             if (!pnode->fDisconnect)
919                                 printf("socket closed\n");
920                             pnode->CloseSocketDisconnect();
921                         }
922                         else if (nBytes < 0)
923                         {
924                             // error
925                             int nErr = WSAGetLastError();
926                             if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
927                             {
928                                 if (!pnode->fDisconnect)
929                                     printf("socket recv error %d\n", nErr);
930                                 pnode->CloseSocketDisconnect();
931                             }
932                         }
933                     }
934                 }
935             }
936
937             //
938             // Send
939             //
940             if (pnode->hSocket == INVALID_SOCKET)
941                 continue;
942             if (FD_ISSET(pnode->hSocket, &fdsetSend))
943             {
944                 TRY_LOCK(pnode->cs_vSend, lockSend);
945                 if (lockSend)
946                 {
947                     CDataStream& vSend = pnode->vSend;
948                     if (!vSend.empty())
949                     {
950                         int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
951                         if (nBytes > 0)
952                         {
953                             vSend.erase(vSend.begin(), vSend.begin() + nBytes);
954                             pnode->nLastSend = GetTime();
955                             pnode->nSendBytes += nBytes;
956                             pnode->RecordBytesSent(nBytes);
957                         }
958                         else if (nBytes < 0)
959                         {
960                             // error
961                             int nErr = WSAGetLastError();
962                             if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
963                             {
964                                 printf("socket send error %d\n", nErr);
965                                 pnode->CloseSocketDisconnect();
966                             }
967                         }
968                     }
969                 }
970             }
971
972             //
973             // Inactivity checking
974             //
975             if (pnode->vSend.empty())
976                 pnode->nLastSendEmpty = GetTime();
977             if (GetTime() - pnode->nTimeConnected > 60)
978             {
979                 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
980                 {
981                     printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
982                     pnode->fDisconnect = true;
983                 }
984                 else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
985                 {
986                     printf("socket not sending\n");
987                     pnode->fDisconnect = true;
988                 }
989                 else if (GetTime() - pnode->nLastRecv > 90*60)
990                 {
991                     printf("socket inactivity timeout\n");
992                     pnode->fDisconnect = true;
993                 }
994             }
995         }
996         {
997             LOCK(cs_vNodes);
998             BOOST_FOREACH(CNode* pnode, vNodesCopy)
999                 pnode->Release();
1000         }
1001
1002         Sleep(10);
1003     }
1004 }
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014 #ifdef USE_UPNP
1015 void ThreadMapPort(void* parg)
1016 {
1017     // Make this thread recognisable as the UPnP thread
1018     RenameThread("novacoin-UPnP");
1019
1020     try
1021     {
1022         vnThreadsRunning[THREAD_UPNP]++;
1023         ThreadMapPort2(parg);
1024         vnThreadsRunning[THREAD_UPNP]--;
1025     }
1026     catch (std::exception& e) {
1027         vnThreadsRunning[THREAD_UPNP]--;
1028         PrintException(&e, "ThreadMapPort()");
1029     } catch (...) {
1030         vnThreadsRunning[THREAD_UPNP]--;
1031         PrintException(NULL, "ThreadMapPort()");
1032     }
1033     printf("ThreadMapPort exited\n");
1034 }
1035
1036 void ThreadMapPort2(void* parg)
1037 {
1038     printf("ThreadMapPort started\n");
1039
1040     std::string port = strprintf("%u", GetListenPort());
1041     const char * multicastif = 0;
1042     const char * minissdpdpath = 0;
1043     struct UPNPDev * devlist = 0;
1044     char lanaddr[64];
1045
1046 #ifndef UPNPDISCOVER_SUCCESS
1047     /* miniupnpc 1.5 */
1048     devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1049 #else
1050     /* miniupnpc 1.6 */
1051     int error = 0;
1052     devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1053 #endif
1054
1055     struct UPNPUrls urls;
1056     struct IGDdatas data;
1057     int r;
1058
1059     r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1060     if (r == 1)
1061     {
1062         if (fDiscover) {
1063             char externalIPAddress[40];
1064             r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1065             if(r != UPNPCOMMAND_SUCCESS)
1066                 printf("UPnP: GetExternalIPAddress() returned %d\n", r);
1067             else
1068             {
1069                 if(externalIPAddress[0])
1070                 {
1071                     printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
1072                     AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
1073                 }
1074                 else
1075                     printf("UPnP: GetExternalIPAddress failed.\n");
1076             }
1077         }
1078
1079         string strDesc = "NovaCoin " + FormatFullVersion();
1080 #ifndef UPNPDISCOVER_SUCCESS
1081         /* miniupnpc 1.5 */
1082         r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1083                             port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1084 #else
1085         /* miniupnpc 1.6 */
1086         r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1087                             port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1088 #endif
1089
1090         if(r!=UPNPCOMMAND_SUCCESS)
1091             printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1092                 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1093         else
1094             printf("UPnP Port Mapping successful.\n");
1095         int i = 1;
1096         while (true)
1097         {
1098             if (fShutdown || !fUseUPnP)
1099             {
1100                 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1101                 printf("UPNP_DeletePortMapping() returned : %d\n", r);
1102                 freeUPNPDevlist(devlist); devlist = 0;
1103                 FreeUPNPUrls(&urls);
1104                 return;
1105             }
1106             if (i % 600 == 0) // Refresh every 20 minutes
1107             {
1108 #ifndef UPNPDISCOVER_SUCCESS
1109                 /* miniupnpc 1.5 */
1110                 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1111                                     port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1112 #else
1113                 /* miniupnpc 1.6 */
1114                 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1115                                     port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1116 #endif
1117
1118                 if(r!=UPNPCOMMAND_SUCCESS)
1119                     printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1120                         port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1121                 else
1122                     printf("UPnP Port Mapping successful.\n");;
1123             }
1124             Sleep(2000);
1125             i++;
1126         }
1127     } else {
1128         printf("No valid UPnP IGDs found\n");
1129         freeUPNPDevlist(devlist); devlist = 0;
1130         if (r != 0)
1131             FreeUPNPUrls(&urls);
1132         while (true)
1133         {
1134             if (fShutdown || !fUseUPnP)
1135                 return;
1136             Sleep(2000);
1137         }
1138     }
1139 }
1140
1141 void MapPort()
1142 {
1143     if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
1144     {
1145         if (!NewThread(ThreadMapPort, NULL))
1146             printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
1147     }
1148 }
1149 #else
1150 void MapPort()
1151 {
1152     // Intentionally left blank.
1153 }
1154 #endif
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164 // DNS seeds
1165 // Each pair gives a source name and a seed name.
1166 // The first name is used as information source for addrman.
1167 // The second name should resolve to a list of seed addresses.
1168 static const char *strDNSSeed[][2] = {
1169     {"novacoin.karelia.pro", "dnsseed.novacoin.karelia.pro"},
1170     {"novacoin.su", "dnsseed.novacoin.su"},
1171     {"novacoin.ru", "dnsseed.novacoin.ru"},
1172     {"novaco.in", "dnsseed.novaco.in"},
1173 };
1174
1175 void ThreadDNSAddressSeed(void* parg)
1176 {
1177     // Make this thread recognisable as the DNS seeding thread
1178     RenameThread("novacoin-dnsseed");
1179
1180     try
1181     {
1182         vnThreadsRunning[THREAD_DNSSEED]++;
1183         ThreadDNSAddressSeed2(parg);
1184         vnThreadsRunning[THREAD_DNSSEED]--;
1185     }
1186     catch (std::exception& e) {
1187         vnThreadsRunning[THREAD_DNSSEED]--;
1188         PrintException(&e, "ThreadDNSAddressSeed()");
1189     } catch (...) {
1190         vnThreadsRunning[THREAD_DNSSEED]--;
1191         throw; // support pthread_cancel()
1192     }
1193     printf("ThreadDNSAddressSeed exited\n");
1194 }
1195
1196 void ThreadDNSAddressSeed2(void* parg)
1197 {
1198     printf("ThreadDNSAddressSeed started\n");
1199     int found = 0;
1200
1201     if (!fTestNet)
1202     {
1203         printf("Loading addresses from DNS seeds (could take a while)\n");
1204
1205         for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
1206             if (HaveNameProxy()) {
1207                 AddOneShot(strDNSSeed[seed_idx][1]);
1208             } else {
1209                 vector<CNetAddr> vaddr;
1210                 vector<CAddress> vAdd;
1211                 if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
1212                 {
1213                     BOOST_FOREACH(CNetAddr& ip, vaddr)
1214                     {
1215                         int nOneDay = 24*3600;
1216                         CAddress addr = CAddress(CService(ip, GetDefaultPort()));
1217                         addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1218                         vAdd.push_back(addr);
1219                         found++;
1220                     }
1221                 }
1222                 addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
1223             }
1224         }
1225     }
1226
1227     printf("%d addresses found from DNS seeds\n", found);
1228 }
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241 unsigned int pnSeed[] =
1242 {
1243     0x90EF78BC, 0x33F1C851, 0x36F1C851, 0xC6F5C851,
1244 };
1245
1246 void DumpAddresses()
1247 {
1248     int64 nStart = GetTimeMillis();
1249
1250     CAddrDB adb;
1251     adb.Write(addrman);
1252
1253     printf("Flushed %d addresses to peers.dat  %"PRI64d"ms\n",
1254            addrman.size(), GetTimeMillis() - nStart);
1255 }
1256
1257 void ThreadDumpAddress2(void* parg)
1258 {
1259     vnThreadsRunning[THREAD_DUMPADDRESS]++;
1260     while (!fShutdown)
1261     {
1262         DumpAddresses();
1263         vnThreadsRunning[THREAD_DUMPADDRESS]--;
1264         Sleep(600000);
1265         vnThreadsRunning[THREAD_DUMPADDRESS]++;
1266     }
1267     vnThreadsRunning[THREAD_DUMPADDRESS]--;
1268 }
1269
1270 void ThreadDumpAddress(void* parg)
1271 {
1272     // Make this thread recognisable as the address dumping thread
1273     RenameThread("novacoin-adrdump");
1274
1275     try
1276     {
1277         ThreadDumpAddress2(parg);
1278     }
1279     catch (std::exception& e) {
1280         PrintException(&e, "ThreadDumpAddress()");
1281     }
1282     printf("ThreadDumpAddress exited\n");
1283 }
1284
1285 void ThreadOpenConnections(void* parg)
1286 {
1287     // Make this thread recognisable as the connection opening thread
1288     RenameThread("novacoin-opencon");
1289
1290     try
1291     {
1292         vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1293         ThreadOpenConnections2(parg);
1294         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1295     }
1296     catch (std::exception& e) {
1297         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1298         PrintException(&e, "ThreadOpenConnections()");
1299     } catch (...) {
1300         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1301         PrintException(NULL, "ThreadOpenConnections()");
1302     }
1303     printf("ThreadOpenConnections exited\n");
1304 }
1305
1306 void static ProcessOneShot()
1307 {
1308     string strDest;
1309     {
1310         LOCK(cs_vOneShots);
1311         if (vOneShots.empty())
1312             return;
1313         strDest = vOneShots.front();
1314         vOneShots.pop_front();
1315     }
1316     CAddress addr;
1317     CSemaphoreGrant grant(*semOutbound, true);
1318     if (grant) {
1319         if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1320             AddOneShot(strDest);
1321     }
1322 }
1323
1324 // ppcoin: stake minter thread
1325 void static ThreadStakeMinter(void* parg)
1326 {
1327     printf("ThreadStakeMinter started\n");
1328     CWallet* pwallet = (CWallet*)parg;
1329     try
1330     {
1331         vnThreadsRunning[THREAD_MINTER]++;
1332         StakeMiner(pwallet);
1333         vnThreadsRunning[THREAD_MINTER]--;
1334     }
1335     catch (std::exception& e) {
1336         vnThreadsRunning[THREAD_MINTER]--;
1337         PrintException(&e, "ThreadStakeMinter()");
1338     } catch (...) {
1339         vnThreadsRunning[THREAD_MINTER]--;
1340         PrintException(NULL, "ThreadStakeMinter()");
1341     }
1342     printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
1343 }
1344
1345 void ThreadOpenConnections2(void* parg)
1346 {
1347     printf("ThreadOpenConnections started\n");
1348
1349     // Connect to specific addresses
1350     if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1351     {
1352         for (int64 nLoop = 0;; nLoop++)
1353         {
1354             ProcessOneShot();
1355             BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1356             {
1357                 CAddress addr;
1358                 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1359                 for (int i = 0; i < 10 && i < nLoop; i++)
1360                 {
1361                     Sleep(500);
1362                     if (fShutdown)
1363                         return;
1364                 }
1365             }
1366             Sleep(500);
1367         }
1368     }
1369
1370     // Initiate network connections
1371     int64 nStart = GetTime();
1372     while (true)
1373     {
1374         ProcessOneShot();
1375
1376         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1377         Sleep(500);
1378         vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1379         if (fShutdown)
1380             return;
1381
1382
1383         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1384         CSemaphoreGrant grant(*semOutbound);
1385         vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1386         if (fShutdown)
1387             return;
1388
1389         // Add seed nodes if IRC isn't working
1390         if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
1391         {
1392             std::vector<CAddress> vAdd;
1393             for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
1394             {
1395                 // It'll only connect to one or two seed nodes because once it connects,
1396                 // it'll get a pile of addresses with newer timestamps.
1397                 // Seed nodes are given a random 'last seen time' of between one and two
1398                 // weeks ago.
1399                 const int64 nOneWeek = 7*24*60*60;
1400                 struct in_addr ip;
1401                 memcpy(&ip, &pnSeed[i], sizeof(ip));
1402                 CAddress addr(CService(ip, GetDefaultPort()));
1403                 addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
1404                 vAdd.push_back(addr);
1405             }
1406             addrman.Add(vAdd, CNetAddr("127.0.0.1"));
1407         }
1408
1409         //
1410         // Choose an address to connect to based on most recently seen
1411         //
1412         CAddress addrConnect;
1413
1414         // Only connect out to one peer per network group (/16 for IPv4).
1415         // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1416         int nOutbound = 0;
1417         set<vector<unsigned char> > setConnected;
1418         {
1419             LOCK(cs_vNodes);
1420             BOOST_FOREACH(CNode* pnode, vNodes) {
1421                 if (!pnode->fInbound) {
1422                     setConnected.insert(pnode->addr.GetGroup());
1423                     nOutbound++;
1424                 }
1425             }
1426         }
1427
1428         int64 nANow = GetAdjustedTime();
1429
1430         int nTries = 0;
1431         while (true)
1432         {
1433             // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
1434             CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
1435
1436             // if we selected an invalid address, restart
1437             if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1438                 break;
1439
1440             // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1441             // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1442             // already-connected network ranges, ...) before trying new addrman addresses.
1443             nTries++;
1444             if (nTries > 100)
1445                 break;
1446
1447             if (IsLimited(addr))
1448                 continue;
1449
1450             // only consider very recently tried nodes after 30 failed attempts
1451             if (nANow - addr.nLastTry < 600 && nTries < 30)
1452                 continue;
1453
1454             // do not allow non-default ports, unless after 50 invalid addresses selected already
1455             if (addr.GetPort() != GetDefaultPort() && nTries < 50)
1456                 continue;
1457
1458             addrConnect = addr;
1459             break;
1460         }
1461
1462         if (addrConnect.IsValid())
1463             OpenNetworkConnection(addrConnect, &grant);
1464     }
1465 }
1466
1467 void ThreadOpenAddedConnections(void* parg)
1468 {
1469     // Make this thread recognisable as the connection opening thread
1470     RenameThread("novacoin-opencon");
1471
1472     try
1473     {
1474         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1475         ThreadOpenAddedConnections2(parg);
1476         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1477     }
1478     catch (std::exception& e) {
1479         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1480         PrintException(&e, "ThreadOpenAddedConnections()");
1481     } catch (...) {
1482         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1483         PrintException(NULL, "ThreadOpenAddedConnections()");
1484     }
1485     printf("ThreadOpenAddedConnections exited\n");
1486 }
1487
1488 void ThreadOpenAddedConnections2(void* parg)
1489 {
1490     printf("ThreadOpenAddedConnections started\n");
1491
1492     if (mapArgs.count("-addnode") == 0)
1493         return;
1494
1495     if (HaveNameProxy()) {
1496         while(!fShutdown) {
1497             BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
1498                 CAddress addr;
1499                 CSemaphoreGrant grant(*semOutbound);
1500                 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1501                 Sleep(500);
1502             }
1503             vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1504             Sleep(120000); // Retry every 2 minutes
1505             vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1506         }
1507         return;
1508     }
1509
1510     vector<vector<CService> > vservAddressesToAdd(0);
1511     BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
1512     {
1513         vector<CService> vservNode(0);
1514         if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
1515         {
1516             vservAddressesToAdd.push_back(vservNode);
1517             {
1518                 LOCK(cs_setservAddNodeAddresses);
1519                 BOOST_FOREACH(CService& serv, vservNode)
1520                     setservAddNodeAddresses.insert(serv);
1521             }
1522         }
1523     }
1524     while (true)
1525     {
1526         vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
1527         // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1528         // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1529         {
1530             LOCK(cs_vNodes);
1531             BOOST_FOREACH(CNode* pnode, vNodes)
1532                 for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
1533                     BOOST_FOREACH(CService& addrNode, *(it))
1534                         if (pnode->addr == addrNode)
1535                         {
1536                             it = vservConnectAddresses.erase(it);
1537                             it--;
1538                             break;
1539                         }
1540         }
1541         BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
1542         {
1543             CSemaphoreGrant grant(*semOutbound);
1544             OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
1545             Sleep(500);
1546             if (fShutdown)
1547                 return;
1548         }
1549         if (fShutdown)
1550             return;
1551         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1552         Sleep(120000); // Retry every 2 minutes
1553         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1554         if (fShutdown)
1555             return;
1556     }
1557 }
1558
1559 // if successful, this moves the passed grant to the constructed node
1560 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
1561 {
1562     //
1563     // Initiate outbound network connection
1564     //
1565     if (fShutdown)
1566         return false;
1567     if (!strDest)
1568         if (IsLocal(addrConnect) ||
1569             FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1570             FindNode(addrConnect.ToStringIPPort().c_str()))
1571             return false;
1572     if (strDest && FindNode(strDest))
1573         return false;
1574
1575     vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1576     CNode* pnode = ConnectNode(addrConnect, strDest);
1577     vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1578     if (fShutdown)
1579         return false;
1580     if (!pnode)
1581         return false;
1582     if (grantOutbound)
1583         grantOutbound->MoveTo(pnode->grantOutbound);
1584     pnode->fNetworkNode = true;
1585     if (fOneShot)
1586         pnode->fOneShot = true;
1587
1588     return true;
1589 }
1590
1591 // for now, use a very simple selection metric: the node from which we received
1592 // most recently
1593 double static NodeSyncScore(const CNode *pnode) {
1594     return -pnode->nLastRecv;
1595 }
1596
1597 void static StartSync(const vector<CNode*> &vNodes) {
1598     CNode *pnodeNewSync = NULL;
1599     double dBestScore = 0;
1600
1601     // Iterate over all nodes
1602     BOOST_FOREACH(CNode* pnode, vNodes) {
1603         // check preconditions for allowing a sync
1604         if (!pnode->fClient && !pnode->fOneShot &&
1605             !pnode->fDisconnect && pnode->fSuccessfullyConnected &&
1606             (pnode->nStartingHeight > (nBestHeight - 144)) &&
1607             (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
1608             // if ok, compare node's score with the best so far
1609             double dScore = NodeSyncScore(pnode);
1610             if (pnodeNewSync == NULL || dScore > dBestScore) {
1611                 pnodeNewSync = pnode;
1612                 dBestScore = dScore;
1613             }
1614         }
1615     }
1616     // if a new sync candidate was found, start sync!
1617     if (pnodeNewSync) {
1618         pnodeNewSync->fStartSync = true;
1619         pnodeSync = pnodeNewSync;
1620     }
1621 }
1622
1623 void ThreadMessageHandler(void* parg)
1624 {
1625     // Make this thread recognisable as the message handling thread
1626     RenameThread("novacoin-msghand");
1627
1628     try
1629     {
1630         vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1631         ThreadMessageHandler2(parg);
1632         vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1633     }
1634     catch (std::exception& e) {
1635         vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1636         PrintException(&e, "ThreadMessageHandler()");
1637     } catch (...) {
1638         vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1639         PrintException(NULL, "ThreadMessageHandler()");
1640     }
1641     printf("ThreadMessageHandler exited\n");
1642 }
1643
1644 void ThreadMessageHandler2(void* parg)
1645 {
1646     printf("ThreadMessageHandler started\n");
1647     SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1648     while (!fShutdown)
1649     {
1650         bool fHaveSyncNode = false;
1651         vector<CNode*> vNodesCopy;
1652         {
1653             LOCK(cs_vNodes);
1654             vNodesCopy = vNodes;
1655             BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1656                 pnode->AddRef();
1657                 if (pnode == pnodeSync)
1658                     fHaveSyncNode = true;
1659             }
1660         }
1661
1662         if (!fHaveSyncNode)
1663             StartSync(vNodesCopy);
1664
1665         // Poll the connected nodes for messages
1666         CNode* pnodeTrickle = NULL;
1667         if (!vNodesCopy.empty())
1668             pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1669         BOOST_FOREACH(CNode* pnode, vNodesCopy)
1670         {
1671             // Receive messages
1672             {
1673                 TRY_LOCK(pnode->cs_vRecv, lockRecv);
1674                 if (lockRecv)
1675                     ProcessMessages(pnode);
1676             }
1677             if (fShutdown)
1678                 return;
1679
1680             // Send messages
1681             {
1682                 TRY_LOCK(pnode->cs_vSend, lockSend);
1683                 if (lockSend)
1684                     SendMessages(pnode, pnode == pnodeTrickle);
1685             }
1686             if (fShutdown)
1687                 return;
1688         }
1689
1690         {
1691             LOCK(cs_vNodes);
1692             BOOST_FOREACH(CNode* pnode, vNodesCopy)
1693                 pnode->Release();
1694         }
1695
1696         // Wait and allow messages to bunch up.
1697         // Reduce vnThreadsRunning so StopNode has permission to exit while
1698         // we're sleeping, but we must always check fShutdown after doing this.
1699         vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1700         Sleep(100);
1701         if (fRequestShutdown)
1702             StartShutdown();
1703         vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1704         if (fShutdown)
1705             return;
1706     }
1707 }
1708
1709
1710
1711
1712
1713
1714 bool BindListenPort(const CService &addrBind, string& strError)
1715 {
1716     strError = "";
1717     int nOne = 1;
1718
1719 #ifdef WIN32
1720     // Initialize Windows Sockets
1721     WSADATA wsadata;
1722     int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1723     if (ret != NO_ERROR)
1724     {
1725         strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
1726         printf("%s\n", strError.c_str());
1727         return false;
1728     }
1729 #endif
1730
1731     // Create socket for listening for incoming connections
1732 #ifdef USE_IPV6
1733     struct sockaddr_storage sockaddr;
1734 #else
1735     struct sockaddr sockaddr;
1736 #endif
1737     socklen_t len = sizeof(sockaddr);
1738     if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1739     {
1740         strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
1741         printf("%s\n", strError.c_str());
1742         return false;
1743     }
1744
1745     SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1746     if (hListenSocket == INVALID_SOCKET)
1747     {
1748         strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1749         printf("%s\n", strError.c_str());
1750         return false;
1751     }
1752
1753 #ifdef SO_NOSIGPIPE
1754     // Different way of disabling SIGPIPE on BSD
1755     setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1756 #endif
1757
1758 #ifndef WIN32
1759     // Allow binding if the port is still in TIME_WAIT state after
1760     // the program was closed and restarted.  Not an issue on windows.
1761     setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1762 #endif
1763
1764
1765 #ifdef WIN32
1766     // Set to non-blocking, incoming connections will also inherit this
1767     if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1768 #else
1769     if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1770 #endif
1771     {
1772         strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1773         printf("%s\n", strError.c_str());
1774         return false;
1775     }
1776
1777 #ifdef USE_IPV6
1778     // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1779     // and enable it by default or not. Try to enable it, if possible.
1780     if (addrBind.IsIPv6()) {
1781 #ifdef IPV6_V6ONLY
1782 #ifdef WIN32
1783         setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1784 #else
1785         setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1786 #endif
1787 #endif
1788 #ifdef WIN32
1789         int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
1790         int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
1791         // this call is allowed to fail
1792         setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
1793 #endif
1794     }
1795 #endif
1796
1797     if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1798     {
1799         int nErr = WSAGetLastError();
1800         if (nErr == WSAEADDRINUSE)
1801             strError = strprintf(_("Unable to bind to %s on this computer. NovaCoin is probably already running."), addrBind.ToString().c_str());
1802         else
1803             strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
1804         printf("%s\n", strError.c_str());
1805         return false;
1806     }
1807     printf("Bound to %s\n", addrBind.ToString().c_str());
1808
1809     // Listen for incoming connections
1810     if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1811     {
1812         strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1813         printf("%s\n", strError.c_str());
1814         return false;
1815     }
1816
1817     vhListenSocket.push_back(hListenSocket);
1818
1819     if (addrBind.IsRoutable() && fDiscover)
1820         AddLocal(addrBind, LOCAL_BIND);
1821
1822     return true;
1823 }
1824
1825 void static Discover()
1826 {
1827     if (!fDiscover)
1828         return;
1829
1830 #ifdef WIN32
1831     // Get local host IP
1832     char pszHostName[1000] = "";
1833     if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1834     {
1835         vector<CNetAddr> vaddr;
1836         if (LookupHost(pszHostName, vaddr))
1837         {
1838             BOOST_FOREACH (const CNetAddr &addr, vaddr)
1839             {
1840                 AddLocal(addr, LOCAL_IF);
1841             }
1842         }
1843     }
1844 #else
1845     // Get local host ip
1846     struct ifaddrs* myaddrs;
1847     if (getifaddrs(&myaddrs) == 0)
1848     {
1849         for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1850         {
1851             if (ifa->ifa_addr == NULL) continue;
1852             if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1853             if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1854             if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1855             if (ifa->ifa_addr->sa_family == AF_INET)
1856             {
1857                 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1858                 CNetAddr addr(s4->sin_addr);
1859                 if (AddLocal(addr, LOCAL_IF))
1860                     printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1861             }
1862 #ifdef USE_IPV6
1863             else if (ifa->ifa_addr->sa_family == AF_INET6)
1864             {
1865                 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1866                 CNetAddr addr(s6->sin6_addr);
1867                 if (AddLocal(addr, LOCAL_IF))
1868                     printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1869             }
1870 #endif
1871         }
1872         freeifaddrs(myaddrs);
1873     }
1874 #endif
1875
1876     // Don't use external IPv4 discovery, when -onlynet="IPv6"
1877     if (!IsLimited(NET_IPV4))
1878         NewThread(ThreadGetMyExternalIP, NULL);
1879 }
1880
1881 void StartNode(void* parg)
1882 {
1883     // Make this thread recognisable as the startup thread
1884     RenameThread("novacoin-start");
1885
1886     if (semOutbound == NULL) {
1887         // initialize semaphore
1888         int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
1889         semOutbound = new CSemaphore(nMaxOutbound);
1890     }
1891
1892     if (pnodeLocalHost == NULL)
1893         pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1894
1895     Discover();
1896
1897     //
1898     // Start threads
1899     //
1900
1901     if (!GetBoolArg("-dnsseed", true))
1902         printf("DNS seeding disabled\n");
1903     else
1904         if (!NewThread(ThreadDNSAddressSeed, NULL))
1905             printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
1906
1907     // Map ports with UPnP
1908     if (fUseUPnP)
1909         MapPort();
1910
1911     // Get addresses from IRC and advertise ours
1912     if (!NewThread(ThreadIRCSeed, NULL))
1913         printf("Error: NewThread(ThreadIRCSeed) failed\n");
1914
1915     // Send and receive from sockets, accept connections
1916     if (!NewThread(ThreadSocketHandler, NULL))
1917         printf("Error: NewThread(ThreadSocketHandler) failed\n");
1918
1919     // Initiate outbound connections from -addnode
1920     if (!NewThread(ThreadOpenAddedConnections, NULL))
1921         printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
1922
1923     // Initiate outbound connections
1924     if (!NewThread(ThreadOpenConnections, NULL))
1925         printf("Error: NewThread(ThreadOpenConnections) failed\n");
1926
1927     // Process messages
1928     if (!NewThread(ThreadMessageHandler, NULL))
1929         printf("Error: NewThread(ThreadMessageHandler) failed\n");
1930
1931     // Dump network addresses
1932     if (!NewThread(ThreadDumpAddress, NULL))
1933         printf("Error; NewThread(ThreadDumpAddress) failed\n");
1934
1935     // ppcoin: mint proof-of-stake blocks in the background
1936     if (!NewThread(ThreadStakeMinter, pwalletMain))
1937         printf("Error: NewThread(ThreadStakeMinter) failed\n");
1938 }
1939
1940 bool StopNode()
1941 {
1942     printf("StopNode()\n");
1943     fShutdown = true;
1944     nTransactionsUpdated++;
1945     int64 nStart = GetTime();
1946     {
1947         LOCK(cs_main);
1948         ThreadScriptCheckQuit();
1949     }
1950     if (semOutbound)
1951         for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1952             semOutbound->post();
1953     do
1954     {
1955         int nThreadsRunning = 0;
1956         for (int n = 0; n < THREAD_MAX; n++)
1957             nThreadsRunning += vnThreadsRunning[n];
1958         if (nThreadsRunning == 0)
1959             break;
1960         if (GetTime() - nStart > 20)
1961             break;
1962         Sleep(20);
1963     } while(true);
1964     if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
1965     if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
1966     if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
1967     if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
1968     if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
1969 #ifdef USE_UPNP
1970     if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
1971 #endif
1972     if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
1973     if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
1974     if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
1975     if (vnThreadsRunning[THREAD_MINTER] > 0) printf("ThreadStakeMinter still running\n");
1976     if (vnThreadsRunning[THREAD_SCRIPTCHECK] > 0) printf("ThreadScriptCheck still running\n");
1977     while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0 || vnThreadsRunning[THREAD_SCRIPTCHECK] > 0)
1978         Sleep(20);
1979     Sleep(50);
1980     DumpAddresses();
1981     return true;
1982 }
1983
1984 class CNetCleanup
1985 {
1986 public:
1987     CNetCleanup()
1988     {
1989     }
1990     ~CNetCleanup()
1991     {
1992         // Close sockets
1993         BOOST_FOREACH(CNode* pnode, vNodes)
1994             if (pnode->hSocket != INVALID_SOCKET)
1995                 closesocket(pnode->hSocket);
1996         BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
1997             if (hListenSocket != INVALID_SOCKET)
1998                 if (closesocket(hListenSocket) == SOCKET_ERROR)
1999                     printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
2000
2001 #ifdef WIN32
2002         // Shutdown Windows Sockets
2003         WSACleanup();
2004 #endif
2005     }
2006 }
2007 instance_of_cnetcleanup;
2008
2009 void RelayTransaction(const CTransaction& tx, const uint256& hash)
2010 {
2011     CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
2012     ss.reserve(10000);
2013     ss << tx;
2014     RelayTransaction(tx, hash, ss);
2015 }
2016
2017 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
2018 {
2019     CInv inv(MSG_TX, hash);
2020     {
2021         LOCK(cs_mapRelay);
2022         // Expire old relay messages
2023         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
2024         {
2025             mapRelay.erase(vRelayExpiration.front().second);
2026             vRelayExpiration.pop_front();
2027         }
2028
2029         // Save original serialized message so newer versions are preserved
2030         mapRelay.insert(std::make_pair(inv, ss));
2031         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
2032     }
2033
2034     RelayInventory(inv);
2035 }
2036
2037 void CNode::RecordBytesRecv(uint64_t bytes)
2038 {
2039     LOCK(cs_totalBytesRecv);
2040     nTotalBytesRecv += bytes;
2041 }
2042
2043 void CNode::RecordBytesSent(uint64_t bytes)
2044 {
2045     LOCK(cs_totalBytesSent);
2046     nTotalBytesSent += bytes;
2047 }
2048
2049 uint64_t CNode::GetTotalBytesRecv()
2050 {
2051     LOCK(cs_totalBytesRecv);
2052     return nTotalBytesRecv;
2053 }
2054
2055 uint64_t CNode::GetTotalBytesSent()
2056 {
2057     LOCK(cs_totalBytesSent);
2058     return nTotalBytesSent;
2059 }