cd826d688964c08b17df50ea9b887725cae53ba5
[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 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
436
437
438 CNode* FindNode(const CNetAddr& ip)
439 {
440     {
441         LOCK(cs_vNodes);
442         BOOST_FOREACH(CNode* pnode, vNodes)
443             if ((CNetAddr)pnode->addr == ip)
444                 return (pnode);
445     }
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     {
461         LOCK(cs_vNodes);
462         BOOST_FOREACH(CNode* pnode, vNodes)
463             if ((CService)pnode->addr == addr)
464                 return (pnode);
465     }
466     return NULL;
467 }
468
469 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
470 {
471     if (pszDest == NULL) {
472         if (IsLocal(addrConnect))
473             return NULL;
474
475         // Look for an existing connection
476         CNode* pnode = FindNode((CService)addrConnect);
477         if (pnode)
478         {
479             if (nTimeout != 0)
480                 pnode->AddRef(nTimeout);
481             else
482                 pnode->AddRef();
483             return pnode;
484         }
485     }
486
487
488     /// debug print
489     printf("trying connection %s lastseen=%.1fhrs\n",
490         pszDest ? pszDest : addrConnect.ToString().c_str(),
491         pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
492
493     // Connect
494     SOCKET hSocket;
495     if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
496     {
497         addrman.Attempt(addrConnect);
498
499         /// debug print
500         printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
501
502         // Set to non-blocking
503 #ifdef WIN32
504         u_long nOne = 1;
505         if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
506             printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
507 #else
508         if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
509             printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
510 #endif
511
512         // Add node
513         CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
514         if (nTimeout != 0)
515             pnode->AddRef(nTimeout);
516         else
517             pnode->AddRef();
518
519         {
520             LOCK(cs_vNodes);
521             vNodes.push_back(pnode);
522         }
523
524         pnode->nTimeConnected = GetTime();
525         return pnode;
526     }
527     else
528     {
529         return NULL;
530     }
531 }
532
533 void CNode::CloseSocketDisconnect()
534 {
535     fDisconnect = true;
536     if (hSocket != INVALID_SOCKET)
537     {
538         printf("disconnecting node %s\n", addrName.c_str());
539         closesocket(hSocket);
540         hSocket = INVALID_SOCKET;
541         vRecv.clear();
542     }
543
544     // in case this fails, we'll empty the recv buffer when the CNode is deleted
545     TRY_LOCK(cs_vRecv, lockRecv);
546     if (lockRecv)
547         vRecv.clear();
548
549     // if this was the sync node, we'll need a new one
550     if (this == pnodeSync)
551         pnodeSync = NULL;
552 }
553
554 void CNode::Cleanup()
555 {
556 }
557
558
559 void CNode::PushVersion()
560 {
561     /// when NTP implemented, change to just nTime = GetAdjustedTime()
562     int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
563     CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
564     CAddress addrMe = GetLocalAddress(&addr);
565     RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
566     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());
567     PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
568                 nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
569 }
570
571
572
573
574
575 std::map<CNetAddr, int64> CNode::setBanned;
576 CCriticalSection CNode::cs_setBanned;
577
578 void CNode::ClearBanned()
579 {
580     setBanned.clear();
581 }
582
583 bool CNode::IsBanned(CNetAddr ip)
584 {
585     bool fResult = false;
586     {
587         LOCK(cs_setBanned);
588         std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
589         if (i != setBanned.end())
590         {
591             int64 t = (*i).second;
592             if (GetTime() < t)
593                 fResult = true;
594         }
595     }
596     return fResult;
597 }
598
599 bool CNode::Misbehaving(int howmuch)
600 {
601     if (addr.IsLocal())
602     {
603         printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
604         return false;
605     }
606
607     nMisbehavior += howmuch;
608     if (nMisbehavior >= GetArg("-banscore", 100))
609     {
610         int64 banTime = GetTime()+GetArg("-bantime", 60*60*24);  // Default 24-hour ban
611         printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
612         {
613             LOCK(cs_setBanned);
614             if (setBanned[addr] < banTime)
615                 setBanned[addr] = banTime;
616         }
617         CloseSocketDisconnect();
618         return true;
619     } else
620         printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
621     return false;
622 }
623
624 #undef X
625 #define X(name) stats.name = name
626 void CNode::copyStats(CNodeStats &stats)
627 {
628     X(nServices);
629     X(nLastSend);
630     X(nLastRecv);
631     X(nTimeConnected);
632     X(addrName);
633     X(nVersion);
634     X(strSubVer);
635     X(fInbound);
636     X(nReleaseTime);
637     X(nStartingHeight);
638     X(nMisbehavior);
639 }
640 #undef X
641
642
643
644
645
646
647
648
649
650
651 void ThreadSocketHandler(void* parg)
652 {
653     // Make this thread recognisable as the networking thread
654     RenameThread("novacoin-net");
655
656     try
657     {
658         vnThreadsRunning[THREAD_SOCKETHANDLER]++;
659         ThreadSocketHandler2(parg);
660         vnThreadsRunning[THREAD_SOCKETHANDLER]--;
661     }
662     catch (std::exception& e) {
663         vnThreadsRunning[THREAD_SOCKETHANDLER]--;
664         PrintException(&e, "ThreadSocketHandler()");
665     } catch (...) {
666         vnThreadsRunning[THREAD_SOCKETHANDLER]--;
667         throw; // support pthread_cancel()
668     }
669     printf("ThreadSocketHandler exited\n");
670 }
671
672 void ThreadSocketHandler2(void* parg)
673 {
674     printf("ThreadSocketHandler started\n");
675     list<CNode*> vNodesDisconnected;
676     unsigned int nPrevNodeCount = 0;
677
678     while (true)
679     {
680         //
681         // Disconnect nodes
682         //
683         {
684             LOCK(cs_vNodes);
685             // Disconnect unused nodes
686             vector<CNode*> vNodesCopy = vNodes;
687             BOOST_FOREACH(CNode* pnode, vNodesCopy)
688             {
689                 if (pnode->fDisconnect ||
690                     (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
691                 {
692                     // remove from vNodes
693                     vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
694
695                     // release outbound grant (if any)
696                     pnode->grantOutbound.Release();
697
698                     // close socket and cleanup
699                     pnode->CloseSocketDisconnect();
700                     pnode->Cleanup();
701
702                     // hold in disconnected pool until all refs are released
703                     pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
704                     if (pnode->fNetworkNode || pnode->fInbound)
705                         pnode->Release();
706                     vNodesDisconnected.push_back(pnode);
707                 }
708             }
709
710             // Delete disconnected nodes
711             list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
712             BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
713             {
714                 // wait until threads are done using it
715                 if (pnode->GetRefCount() <= 0)
716                 {
717                     bool fDelete = false;
718                     {
719                         TRY_LOCK(pnode->cs_vSend, lockSend);
720                         if (lockSend)
721                         {
722                             TRY_LOCK(pnode->cs_vRecv, lockRecv);
723                             if (lockRecv)
724                             {
725                                 TRY_LOCK(pnode->cs_mapRequests, lockReq);
726                                 if (lockReq)
727                                 {
728                                     TRY_LOCK(pnode->cs_inventory, lockInv);
729                                     if (lockInv)
730                                         fDelete = true;
731                                 }
732                             }
733                         }
734                     }
735                     if (fDelete)
736                     {
737                         vNodesDisconnected.remove(pnode);
738                         delete pnode;
739                     }
740                 }
741             }
742         }
743         if (vNodes.size() != nPrevNodeCount)
744         {
745             nPrevNodeCount = vNodes.size();
746             uiInterface.NotifyNumConnectionsChanged(vNodes.size());
747         }
748
749
750         //
751         // Find which sockets have data to receive
752         //
753         struct timeval timeout;
754         timeout.tv_sec  = 0;
755         timeout.tv_usec = 50000; // frequency to poll pnode->vSend
756
757         fd_set fdsetRecv;
758         fd_set fdsetSend;
759         fd_set fdsetError;
760         FD_ZERO(&fdsetRecv);
761         FD_ZERO(&fdsetSend);
762         FD_ZERO(&fdsetError);
763         SOCKET hSocketMax = 0;
764         bool have_fds = false;
765
766         BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
767             FD_SET(hListenSocket, &fdsetRecv);
768             hSocketMax = max(hSocketMax, hListenSocket);
769             have_fds = true;
770         }
771         {
772             LOCK(cs_vNodes);
773             BOOST_FOREACH(CNode* pnode, vNodes)
774             {
775                 if (pnode->hSocket == INVALID_SOCKET)
776                     continue;
777                 FD_SET(pnode->hSocket, &fdsetRecv);
778                 FD_SET(pnode->hSocket, &fdsetError);
779                 hSocketMax = max(hSocketMax, pnode->hSocket);
780                 have_fds = true;
781                 {
782                     TRY_LOCK(pnode->cs_vSend, lockSend);
783                     if (lockSend && !pnode->vSend.empty())
784                         FD_SET(pnode->hSocket, &fdsetSend);
785                 }
786             }
787         }
788
789         vnThreadsRunning[THREAD_SOCKETHANDLER]--;
790         int nSelect = select(have_fds ? hSocketMax + 1 : 0,
791                              &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
792         vnThreadsRunning[THREAD_SOCKETHANDLER]++;
793         if (fShutdown)
794             return;
795         if (nSelect == SOCKET_ERROR)
796         {
797             if (have_fds)
798             {
799                 int nErr = WSAGetLastError();
800                 printf("socket select error %d\n", nErr);
801                 for (unsigned int i = 0; i <= hSocketMax; i++)
802                     FD_SET(i, &fdsetRecv);
803             }
804             FD_ZERO(&fdsetSend);
805             FD_ZERO(&fdsetError);
806             Sleep(timeout.tv_usec/1000);
807         }
808
809
810         //
811         // Accept new connections
812         //
813         BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
814         if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
815         {
816 #ifdef USE_IPV6
817             struct sockaddr_storage sockaddr;
818 #else
819             struct sockaddr sockaddr;
820 #endif
821             socklen_t len = sizeof(sockaddr);
822             SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
823             CAddress addr;
824             int nInbound = 0;
825
826             if (hSocket != INVALID_SOCKET)
827                 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
828                     printf("Warning: Unknown socket family\n");
829
830             {
831                 LOCK(cs_vNodes);
832                 BOOST_FOREACH(CNode* pnode, vNodes)
833                     if (pnode->fInbound)
834                         nInbound++;
835             }
836
837             if (hSocket == INVALID_SOCKET)
838             {
839                 int nErr = WSAGetLastError();
840                 if (nErr != WSAEWOULDBLOCK)
841                     printf("socket error accept failed: %d\n", nErr);
842             }
843             else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
844             {
845                 {
846                     LOCK(cs_setservAddNodeAddresses);
847                     if (!setservAddNodeAddresses.count(addr))
848                         closesocket(hSocket);
849                 }
850             }
851             else if (CNode::IsBanned(addr))
852             {
853                 printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
854                 closesocket(hSocket);
855             }
856             else
857             {
858                 printf("accepted connection %s\n", addr.ToString().c_str());
859                 CNode* pnode = new CNode(hSocket, addr, "", true);
860                 pnode->AddRef();
861                 {
862                     LOCK(cs_vNodes);
863                     vNodes.push_back(pnode);
864                 }
865             }
866         }
867
868
869         //
870         // Service each socket
871         //
872         vector<CNode*> vNodesCopy;
873         {
874             LOCK(cs_vNodes);
875             vNodesCopy = vNodes;
876             BOOST_FOREACH(CNode* pnode, vNodesCopy)
877                 pnode->AddRef();
878         }
879         BOOST_FOREACH(CNode* pnode, vNodesCopy)
880         {
881             if (fShutdown)
882                 return;
883
884             //
885             // Receive
886             //
887             if (pnode->hSocket == INVALID_SOCKET)
888                 continue;
889             if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
890             {
891                 TRY_LOCK(pnode->cs_vRecv, lockRecv);
892                 if (lockRecv)
893                 {
894                     CDataStream& vRecv = pnode->vRecv;
895                     unsigned int nPos = vRecv.size();
896
897                     if (nPos > ReceiveBufferSize()) {
898                         if (!pnode->fDisconnect)
899                             printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
900                         pnode->CloseSocketDisconnect();
901                     }
902                     else {
903                         // typical socket buffer is 8K-64K
904                         char pchBuf[0x10000];
905                         int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
906                         if (nBytes > 0)
907                         {
908                             vRecv.resize(nPos + nBytes);
909                             memcpy(&vRecv[nPos], pchBuf, nBytes);
910                             pnode->nLastRecv = GetTime();
911                         }
912                         else if (nBytes == 0)
913                         {
914                             // socket closed gracefully
915                             if (!pnode->fDisconnect)
916                                 printf("socket closed\n");
917                             pnode->CloseSocketDisconnect();
918                         }
919                         else if (nBytes < 0)
920                         {
921                             // error
922                             int nErr = WSAGetLastError();
923                             if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
924                             {
925                                 if (!pnode->fDisconnect)
926                                     printf("socket recv error %d\n", nErr);
927                                 pnode->CloseSocketDisconnect();
928                             }
929                         }
930                     }
931                 }
932             }
933
934             //
935             // Send
936             //
937             if (pnode->hSocket == INVALID_SOCKET)
938                 continue;
939             if (FD_ISSET(pnode->hSocket, &fdsetSend))
940             {
941                 TRY_LOCK(pnode->cs_vSend, lockSend);
942                 if (lockSend)
943                 {
944                     CDataStream& vSend = pnode->vSend;
945                     if (!vSend.empty())
946                     {
947                         int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
948                         if (nBytes > 0)
949                         {
950                             vSend.erase(vSend.begin(), vSend.begin() + nBytes);
951                             pnode->nLastSend = GetTime();
952                         }
953                         else if (nBytes < 0)
954                         {
955                             // error
956                             int nErr = WSAGetLastError();
957                             if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
958                             {
959                                 printf("socket send error %d\n", nErr);
960                                 pnode->CloseSocketDisconnect();
961                             }
962                         }
963                     }
964                 }
965             }
966
967             //
968             // Inactivity checking
969             //
970             if (pnode->vSend.empty())
971                 pnode->nLastSendEmpty = GetTime();
972             if (GetTime() - pnode->nTimeConnected > 60)
973             {
974                 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
975                 {
976                     printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
977                     pnode->fDisconnect = true;
978                 }
979                 else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
980                 {
981                     printf("socket not sending\n");
982                     pnode->fDisconnect = true;
983                 }
984                 else if (GetTime() - pnode->nLastRecv > 90*60)
985                 {
986                     printf("socket inactivity timeout\n");
987                     pnode->fDisconnect = true;
988                 }
989             }
990         }
991         {
992             LOCK(cs_vNodes);
993             BOOST_FOREACH(CNode* pnode, vNodesCopy)
994                 pnode->Release();
995         }
996
997         Sleep(10);
998     }
999 }
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009 #ifdef USE_UPNP
1010 void ThreadMapPort(void* parg)
1011 {
1012     // Make this thread recognisable as the UPnP thread
1013     RenameThread("novacoin-UPnP");
1014
1015     try
1016     {
1017         vnThreadsRunning[THREAD_UPNP]++;
1018         ThreadMapPort2(parg);
1019         vnThreadsRunning[THREAD_UPNP]--;
1020     }
1021     catch (std::exception& e) {
1022         vnThreadsRunning[THREAD_UPNP]--;
1023         PrintException(&e, "ThreadMapPort()");
1024     } catch (...) {
1025         vnThreadsRunning[THREAD_UPNP]--;
1026         PrintException(NULL, "ThreadMapPort()");
1027     }
1028     printf("ThreadMapPort exited\n");
1029 }
1030
1031 void ThreadMapPort2(void* parg)
1032 {
1033     printf("ThreadMapPort started\n");
1034
1035     std::string port = strprintf("%u", GetListenPort());
1036     const char * multicastif = 0;
1037     const char * minissdpdpath = 0;
1038     struct UPNPDev * devlist = 0;
1039     char lanaddr[64];
1040
1041 #ifndef UPNPDISCOVER_SUCCESS
1042     /* miniupnpc 1.5 */
1043     devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1044 #else
1045     /* miniupnpc 1.6 */
1046     int error = 0;
1047     devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1048 #endif
1049
1050     struct UPNPUrls urls;
1051     struct IGDdatas data;
1052     int r;
1053
1054     r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1055     if (r == 1)
1056     {
1057         if (fDiscover) {
1058             char externalIPAddress[40];
1059             r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1060             if(r != UPNPCOMMAND_SUCCESS)
1061                 printf("UPnP: GetExternalIPAddress() returned %d\n", r);
1062             else
1063             {
1064                 if(externalIPAddress[0])
1065                 {
1066                     printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
1067                     AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
1068                 }
1069                 else
1070                     printf("UPnP: GetExternalIPAddress failed.\n");
1071             }
1072         }
1073
1074         string strDesc = "NovaCoin " + FormatFullVersion();
1075 #ifndef UPNPDISCOVER_SUCCESS
1076         /* miniupnpc 1.5 */
1077         r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1078                             port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1079 #else
1080         /* miniupnpc 1.6 */
1081         r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1082                             port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1083 #endif
1084
1085         if(r!=UPNPCOMMAND_SUCCESS)
1086             printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1087                 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1088         else
1089             printf("UPnP Port Mapping successful.\n");
1090         int i = 1;
1091         while (true)
1092         {
1093             if (fShutdown || !fUseUPnP)
1094             {
1095                 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1096                 printf("UPNP_DeletePortMapping() returned : %d\n", r);
1097                 freeUPNPDevlist(devlist); devlist = 0;
1098                 FreeUPNPUrls(&urls);
1099                 return;
1100             }
1101             if (i % 600 == 0) // Refresh every 20 minutes
1102             {
1103 #ifndef UPNPDISCOVER_SUCCESS
1104                 /* miniupnpc 1.5 */
1105                 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1106                                     port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1107 #else
1108                 /* miniupnpc 1.6 */
1109                 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1110                                     port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1111 #endif
1112
1113                 if(r!=UPNPCOMMAND_SUCCESS)
1114                     printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1115                         port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1116                 else
1117                     printf("UPnP Port Mapping successful.\n");;
1118             }
1119             Sleep(2000);
1120             i++;
1121         }
1122     } else {
1123         printf("No valid UPnP IGDs found\n");
1124         freeUPNPDevlist(devlist); devlist = 0;
1125         if (r != 0)
1126             FreeUPNPUrls(&urls);
1127         while (true)
1128         {
1129             if (fShutdown || !fUseUPnP)
1130                 return;
1131             Sleep(2000);
1132         }
1133     }
1134 }
1135
1136 void MapPort()
1137 {
1138     if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
1139     {
1140         if (!NewThread(ThreadMapPort, NULL))
1141             printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
1142     }
1143 }
1144 #else
1145 void MapPort()
1146 {
1147     // Intentionally left blank.
1148 }
1149 #endif
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159 // DNS seeds
1160 // Each pair gives a source name and a seed name.
1161 // The first name is used as information source for addrman.
1162 // The second name should resolve to a list of seed addresses.
1163 static const char *strDNSSeed[][2] = {
1164     {"novacoin.su", "dnsseed.novacoin.su"},
1165     {"novacoin.ru", "dnsseed.novacoin.ru"},
1166     {"novaco.in", "dnsseed.novaco.in"},
1167 };
1168
1169 void ThreadDNSAddressSeed(void* parg)
1170 {
1171     // Make this thread recognisable as the DNS seeding thread
1172     RenameThread("novacoin-dnsseed");
1173
1174     try
1175     {
1176         vnThreadsRunning[THREAD_DNSSEED]++;
1177         ThreadDNSAddressSeed2(parg);
1178         vnThreadsRunning[THREAD_DNSSEED]--;
1179     }
1180     catch (std::exception& e) {
1181         vnThreadsRunning[THREAD_DNSSEED]--;
1182         PrintException(&e, "ThreadDNSAddressSeed()");
1183     } catch (...) {
1184         vnThreadsRunning[THREAD_DNSSEED]--;
1185         throw; // support pthread_cancel()
1186     }
1187     printf("ThreadDNSAddressSeed exited\n");
1188 }
1189
1190 void ThreadDNSAddressSeed2(void* parg)
1191 {
1192     printf("ThreadDNSAddressSeed started\n");
1193     int found = 0;
1194
1195     if (!fTestNet)
1196     {
1197         printf("Loading addresses from DNS seeds (could take a while)\n");
1198
1199         for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
1200             if (HaveNameProxy()) {
1201                 AddOneShot(strDNSSeed[seed_idx][1]);
1202             } else {
1203                 vector<CNetAddr> vaddr;
1204                 vector<CAddress> vAdd;
1205                 if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
1206                 {
1207                     BOOST_FOREACH(CNetAddr& ip, vaddr)
1208                     {
1209                         int nOneDay = 24*3600;
1210                         CAddress addr = CAddress(CService(ip, GetDefaultPort()));
1211                         addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1212                         vAdd.push_back(addr);
1213                         found++;
1214                     }
1215                 }
1216                 addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
1217             }
1218         }
1219     }
1220
1221     printf("%d addresses found from DNS seeds\n", found);
1222 }
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235 unsigned int pnSeed[] =
1236 {
1237     0x90EF78BC, 0x33F1C851, 0x36F1C851, 0xC6F5C851,
1238 };
1239
1240 void DumpAddresses()
1241 {
1242     int64 nStart = GetTimeMillis();
1243
1244     CAddrDB adb;
1245     adb.Write(addrman);
1246
1247     printf("Flushed %d addresses to peers.dat  %"PRI64d"ms\n",
1248            addrman.size(), GetTimeMillis() - nStart);
1249 }
1250
1251 void ThreadDumpAddress2(void* parg)
1252 {
1253     vnThreadsRunning[THREAD_DUMPADDRESS]++;
1254     while (!fShutdown)
1255     {
1256         DumpAddresses();
1257         vnThreadsRunning[THREAD_DUMPADDRESS]--;
1258         Sleep(600000);
1259         vnThreadsRunning[THREAD_DUMPADDRESS]++;
1260     }
1261     vnThreadsRunning[THREAD_DUMPADDRESS]--;
1262 }
1263
1264 void ThreadDumpAddress(void* parg)
1265 {
1266     // Make this thread recognisable as the address dumping thread
1267     RenameThread("novacoin-adrdump");
1268
1269     try
1270     {
1271         ThreadDumpAddress2(parg);
1272     }
1273     catch (std::exception& e) {
1274         PrintException(&e, "ThreadDumpAddress()");
1275     }
1276     printf("ThreadDumpAddress exited\n");
1277 }
1278
1279 void ThreadOpenConnections(void* parg)
1280 {
1281     // Make this thread recognisable as the connection opening thread
1282     RenameThread("novacoin-opencon");
1283
1284     try
1285     {
1286         vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1287         ThreadOpenConnections2(parg);
1288         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1289     }
1290     catch (std::exception& e) {
1291         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1292         PrintException(&e, "ThreadOpenConnections()");
1293     } catch (...) {
1294         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1295         PrintException(NULL, "ThreadOpenConnections()");
1296     }
1297     printf("ThreadOpenConnections exited\n");
1298 }
1299
1300 void static ProcessOneShot()
1301 {
1302     string strDest;
1303     {
1304         LOCK(cs_vOneShots);
1305         if (vOneShots.empty())
1306             return;
1307         strDest = vOneShots.front();
1308         vOneShots.pop_front();
1309     }
1310     CAddress addr;
1311     CSemaphoreGrant grant(*semOutbound, true);
1312     if (grant) {
1313         if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1314             AddOneShot(strDest);
1315     }
1316 }
1317
1318 // ppcoin: stake minter thread
1319 void static ThreadStakeMinter(void* parg)
1320 {
1321     printf("ThreadStakeMinter started\n");
1322     CWallet* pwallet = (CWallet*)parg;
1323     try
1324     {
1325         vnThreadsRunning[THREAD_MINTER]++;
1326         StakeMiner(pwallet);
1327         vnThreadsRunning[THREAD_MINTER]--;
1328     }
1329     catch (std::exception& e) {
1330         vnThreadsRunning[THREAD_MINTER]--;
1331         PrintException(&e, "ThreadStakeMinter()");
1332     } catch (...) {
1333         vnThreadsRunning[THREAD_MINTER]--;
1334         PrintException(NULL, "ThreadStakeMinter()");
1335     }
1336     printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
1337 }
1338
1339 void ThreadOpenConnections2(void* parg)
1340 {
1341     printf("ThreadOpenConnections started\n");
1342
1343     // Connect to specific addresses
1344     if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1345     {
1346         for (int64 nLoop = 0;; nLoop++)
1347         {
1348             ProcessOneShot();
1349             BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1350             {
1351                 CAddress addr;
1352                 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1353                 for (int i = 0; i < 10 && i < nLoop; i++)
1354                 {
1355                     Sleep(500);
1356                     if (fShutdown)
1357                         return;
1358                 }
1359             }
1360             Sleep(500);
1361         }
1362     }
1363
1364     // Initiate network connections
1365     int64 nStart = GetTime();
1366     while (true)
1367     {
1368         ProcessOneShot();
1369
1370         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1371         Sleep(500);
1372         vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1373         if (fShutdown)
1374             return;
1375
1376
1377         vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1378         CSemaphoreGrant grant(*semOutbound);
1379         vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1380         if (fShutdown)
1381             return;
1382
1383         // Add seed nodes if IRC isn't working
1384         if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
1385         {
1386             std::vector<CAddress> vAdd;
1387             for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
1388             {
1389                 // It'll only connect to one or two seed nodes because once it connects,
1390                 // it'll get a pile of addresses with newer timestamps.
1391                 // Seed nodes are given a random 'last seen time' of between one and two
1392                 // weeks ago.
1393                 const int64 nOneWeek = 7*24*60*60;
1394                 struct in_addr ip;
1395                 memcpy(&ip, &pnSeed[i], sizeof(ip));
1396                 CAddress addr(CService(ip, GetDefaultPort()));
1397                 addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
1398                 vAdd.push_back(addr);
1399             }
1400             addrman.Add(vAdd, CNetAddr("127.0.0.1"));
1401         }
1402
1403         //
1404         // Choose an address to connect to based on most recently seen
1405         //
1406         CAddress addrConnect;
1407
1408         // Only connect out to one peer per network group (/16 for IPv4).
1409         // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1410         int nOutbound = 0;
1411         set<vector<unsigned char> > setConnected;
1412         {
1413             LOCK(cs_vNodes);
1414             BOOST_FOREACH(CNode* pnode, vNodes) {
1415                 if (!pnode->fInbound) {
1416                     setConnected.insert(pnode->addr.GetGroup());
1417                     nOutbound++;
1418                 }
1419             }
1420         }
1421
1422         int64 nANow = GetAdjustedTime();
1423
1424         int nTries = 0;
1425         while (true)
1426         {
1427             // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
1428             CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
1429
1430             // if we selected an invalid address, restart
1431             if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1432                 break;
1433
1434             // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1435             // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1436             // already-connected network ranges, ...) before trying new addrman addresses.
1437             nTries++;
1438             if (nTries > 100)
1439                 break;
1440
1441             if (IsLimited(addr))
1442                 continue;
1443
1444             // only consider very recently tried nodes after 30 failed attempts
1445             if (nANow - addr.nLastTry < 600 && nTries < 30)
1446                 continue;
1447
1448             // do not allow non-default ports, unless after 50 invalid addresses selected already
1449             if (addr.GetPort() != GetDefaultPort() && nTries < 50)
1450                 continue;
1451
1452             addrConnect = addr;
1453             break;
1454         }
1455
1456         if (addrConnect.IsValid())
1457             OpenNetworkConnection(addrConnect, &grant);
1458     }
1459 }
1460
1461 void ThreadOpenAddedConnections(void* parg)
1462 {
1463     // Make this thread recognisable as the connection opening thread
1464     RenameThread("novacoin-opencon");
1465
1466     try
1467     {
1468         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1469         ThreadOpenAddedConnections2(parg);
1470         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1471     }
1472     catch (std::exception& e) {
1473         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1474         PrintException(&e, "ThreadOpenAddedConnections()");
1475     } catch (...) {
1476         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1477         PrintException(NULL, "ThreadOpenAddedConnections()");
1478     }
1479     printf("ThreadOpenAddedConnections exited\n");
1480 }
1481
1482 void ThreadOpenAddedConnections2(void* parg)
1483 {
1484     printf("ThreadOpenAddedConnections started\n");
1485
1486     if (mapArgs.count("-addnode") == 0)
1487         return;
1488
1489     if (HaveNameProxy()) {
1490         while(!fShutdown) {
1491             BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
1492                 CAddress addr;
1493                 CSemaphoreGrant grant(*semOutbound);
1494                 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1495                 Sleep(500);
1496             }
1497             vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1498             Sleep(120000); // Retry every 2 minutes
1499             vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1500         }
1501         return;
1502     }
1503
1504     vector<vector<CService> > vservAddressesToAdd(0);
1505     BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
1506     {
1507         vector<CService> vservNode(0);
1508         if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
1509         {
1510             vservAddressesToAdd.push_back(vservNode);
1511             {
1512                 LOCK(cs_setservAddNodeAddresses);
1513                 BOOST_FOREACH(CService& serv, vservNode)
1514                     setservAddNodeAddresses.insert(serv);
1515             }
1516         }
1517     }
1518     while (true)
1519     {
1520         vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
1521         // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1522         // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1523         {
1524             LOCK(cs_vNodes);
1525             BOOST_FOREACH(CNode* pnode, vNodes)
1526                 for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
1527                     BOOST_FOREACH(CService& addrNode, *(it))
1528                         if (pnode->addr == addrNode)
1529                         {
1530                             it = vservConnectAddresses.erase(it);
1531                             it--;
1532                             break;
1533                         }
1534         }
1535         BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
1536         {
1537             CSemaphoreGrant grant(*semOutbound);
1538             OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
1539             Sleep(500);
1540             if (fShutdown)
1541                 return;
1542         }
1543         if (fShutdown)
1544             return;
1545         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1546         Sleep(120000); // Retry every 2 minutes
1547         vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1548         if (fShutdown)
1549             return;
1550     }
1551 }
1552
1553 // if successful, this moves the passed grant to the constructed node
1554 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
1555 {
1556     //
1557     // Initiate outbound network connection
1558     //
1559     if (fShutdown)
1560         return false;
1561     if (!strDest)
1562         if (IsLocal(addrConnect) ||
1563             FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1564             FindNode(addrConnect.ToStringIPPort().c_str()))
1565             return false;
1566     if (strDest && FindNode(strDest))
1567         return false;
1568
1569     vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1570     CNode* pnode = ConnectNode(addrConnect, strDest);
1571     vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1572     if (fShutdown)
1573         return false;
1574     if (!pnode)
1575         return false;
1576     if (grantOutbound)
1577         grantOutbound->MoveTo(pnode->grantOutbound);
1578     pnode->fNetworkNode = true;
1579     if (fOneShot)
1580         pnode->fOneShot = true;
1581
1582     return true;
1583 }
1584
1585 // for now, use a very simple selection metric: the node from which we received
1586 // most recently
1587 double static NodeSyncScore(const CNode *pnode) {
1588     return -pnode->nLastRecv;
1589 }
1590
1591 void static StartSync(const vector<CNode*> &vNodes) {
1592     CNode *pnodeNewSync = NULL;
1593     double dBestScore = 0;
1594
1595     // Iterate over all nodes
1596     BOOST_FOREACH(CNode* pnode, vNodes) {
1597         // check preconditions for allowing a sync
1598         if (!pnode->fClient && !pnode->fOneShot &&
1599             !pnode->fDisconnect && pnode->fSuccessfullyConnected &&
1600             (pnode->nStartingHeight > (nBestHeight - 144)) &&
1601             (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
1602             // if ok, compare node's score with the best so far
1603             double dScore = NodeSyncScore(pnode);
1604             if (pnodeNewSync == NULL || dScore > dBestScore) {
1605                 pnodeNewSync = pnode;
1606                 dBestScore = dScore;
1607             }
1608         }
1609     }
1610     // if a new sync candidate was found, start sync!
1611     if (pnodeNewSync) {
1612         pnodeNewSync->fStartSync = true;
1613         pnodeSync = pnodeNewSync;
1614     }
1615 }
1616
1617 void ThreadMessageHandler(void* parg)
1618 {
1619     // Make this thread recognisable as the message handling thread
1620     RenameThread("novacoin-msghand");
1621
1622     try
1623     {
1624         vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1625         ThreadMessageHandler2(parg);
1626         vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1627     }
1628     catch (std::exception& e) {
1629         vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1630         PrintException(&e, "ThreadMessageHandler()");
1631     } catch (...) {
1632         vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1633         PrintException(NULL, "ThreadMessageHandler()");
1634     }
1635     printf("ThreadMessageHandler exited\n");
1636 }
1637
1638 void ThreadMessageHandler2(void* parg)
1639 {
1640     printf("ThreadMessageHandler started\n");
1641     SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1642     while (!fShutdown)
1643     {
1644         bool fHaveSyncNode = false;
1645         vector<CNode*> vNodesCopy;
1646         {
1647             LOCK(cs_vNodes);
1648             vNodesCopy = vNodes;
1649             BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1650                 pnode->AddRef();
1651                 if (pnode == pnodeSync)
1652                     fHaveSyncNode = true;
1653             }
1654         }
1655
1656         if (!fHaveSyncNode)
1657             StartSync(vNodesCopy);
1658
1659         // Poll the connected nodes for messages
1660         CNode* pnodeTrickle = NULL;
1661         if (!vNodesCopy.empty())
1662             pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1663         BOOST_FOREACH(CNode* pnode, vNodesCopy)
1664         {
1665             // Receive messages
1666             {
1667                 TRY_LOCK(pnode->cs_vRecv, lockRecv);
1668                 if (lockRecv)
1669                     ProcessMessages(pnode);
1670             }
1671             if (fShutdown)
1672                 return;
1673
1674             // Send messages
1675             {
1676                 TRY_LOCK(pnode->cs_vSend, lockSend);
1677                 if (lockSend)
1678                     SendMessages(pnode, pnode == pnodeTrickle);
1679             }
1680             if (fShutdown)
1681                 return;
1682         }
1683
1684         {
1685             LOCK(cs_vNodes);
1686             BOOST_FOREACH(CNode* pnode, vNodesCopy)
1687                 pnode->Release();
1688         }
1689
1690         // Wait and allow messages to bunch up.
1691         // Reduce vnThreadsRunning so StopNode has permission to exit while
1692         // we're sleeping, but we must always check fShutdown after doing this.
1693         vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1694         Sleep(100);
1695         if (fRequestShutdown)
1696             StartShutdown();
1697         vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1698         if (fShutdown)
1699             return;
1700     }
1701 }
1702
1703
1704
1705
1706
1707
1708 bool BindListenPort(const CService &addrBind, string& strError)
1709 {
1710     strError = "";
1711     int nOne = 1;
1712
1713 #ifdef WIN32
1714     // Initialize Windows Sockets
1715     WSADATA wsadata;
1716     int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1717     if (ret != NO_ERROR)
1718     {
1719         strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
1720         printf("%s\n", strError.c_str());
1721         return false;
1722     }
1723 #endif
1724
1725     // Create socket for listening for incoming connections
1726 #ifdef USE_IPV6
1727     struct sockaddr_storage sockaddr;
1728 #else
1729     struct sockaddr sockaddr;
1730 #endif
1731     socklen_t len = sizeof(sockaddr);
1732     if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1733     {
1734         strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
1735         printf("%s\n", strError.c_str());
1736         return false;
1737     }
1738
1739     SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1740     if (hListenSocket == INVALID_SOCKET)
1741     {
1742         strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1743         printf("%s\n", strError.c_str());
1744         return false;
1745     }
1746
1747 #ifdef SO_NOSIGPIPE
1748     // Different way of disabling SIGPIPE on BSD
1749     setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1750 #endif
1751
1752 #ifndef WIN32
1753     // Allow binding if the port is still in TIME_WAIT state after
1754     // the program was closed and restarted.  Not an issue on windows.
1755     setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1756 #endif
1757
1758
1759 #ifdef WIN32
1760     // Set to non-blocking, incoming connections will also inherit this
1761     if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1762 #else
1763     if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1764 #endif
1765     {
1766         strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1767         printf("%s\n", strError.c_str());
1768         return false;
1769     }
1770
1771 #ifdef USE_IPV6
1772     // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1773     // and enable it by default or not. Try to enable it, if possible.
1774     if (addrBind.IsIPv6()) {
1775 #ifdef IPV6_V6ONLY
1776 #ifdef WIN32
1777         setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1778 #else
1779         setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1780 #endif
1781 #endif
1782 #ifdef WIN32
1783         int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
1784         int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
1785         // this call is allowed to fail
1786         setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
1787 #endif
1788     }
1789 #endif
1790
1791     if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1792     {
1793         int nErr = WSAGetLastError();
1794         if (nErr == WSAEADDRINUSE)
1795             strError = strprintf(_("Unable to bind to %s on this computer. NovaCoin is probably already running."), addrBind.ToString().c_str());
1796         else
1797             strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
1798         printf("%s\n", strError.c_str());
1799         return false;
1800     }
1801     printf("Bound to %s\n", addrBind.ToString().c_str());
1802
1803     // Listen for incoming connections
1804     if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1805     {
1806         strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1807         printf("%s\n", strError.c_str());
1808         return false;
1809     }
1810
1811     vhListenSocket.push_back(hListenSocket);
1812
1813     if (addrBind.IsRoutable() && fDiscover)
1814         AddLocal(addrBind, LOCAL_BIND);
1815
1816     return true;
1817 }
1818
1819 void static Discover()
1820 {
1821     if (!fDiscover)
1822         return;
1823
1824 #ifdef WIN32
1825     // Get local host IP
1826     char pszHostName[1000] = "";
1827     if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1828     {
1829         vector<CNetAddr> vaddr;
1830         if (LookupHost(pszHostName, vaddr))
1831         {
1832             BOOST_FOREACH (const CNetAddr &addr, vaddr)
1833             {
1834                 AddLocal(addr, LOCAL_IF);
1835             }
1836         }
1837     }
1838 #else
1839     // Get local host ip
1840     struct ifaddrs* myaddrs;
1841     if (getifaddrs(&myaddrs) == 0)
1842     {
1843         for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1844         {
1845             if (ifa->ifa_addr == NULL) continue;
1846             if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1847             if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1848             if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1849             if (ifa->ifa_addr->sa_family == AF_INET)
1850             {
1851                 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1852                 CNetAddr addr(s4->sin_addr);
1853                 if (AddLocal(addr, LOCAL_IF))
1854                     printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1855             }
1856 #ifdef USE_IPV6
1857             else if (ifa->ifa_addr->sa_family == AF_INET6)
1858             {
1859                 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1860                 CNetAddr addr(s6->sin6_addr);
1861                 if (AddLocal(addr, LOCAL_IF))
1862                     printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1863             }
1864 #endif
1865         }
1866         freeifaddrs(myaddrs);
1867     }
1868 #endif
1869
1870     // Don't use external IPv4 discovery, when -onlynet="IPv6"
1871     if (!IsLimited(NET_IPV4))
1872         NewThread(ThreadGetMyExternalIP, NULL);
1873 }
1874
1875 void StartNode(void* parg)
1876 {
1877     // Make this thread recognisable as the startup thread
1878     RenameThread("novacoin-start");
1879
1880     if (semOutbound == NULL) {
1881         // initialize semaphore
1882         int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
1883         semOutbound = new CSemaphore(nMaxOutbound);
1884     }
1885
1886     if (pnodeLocalHost == NULL)
1887         pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1888
1889     Discover();
1890
1891     //
1892     // Start threads
1893     //
1894
1895     if (!GetBoolArg("-dnsseed", true))
1896         printf("DNS seeding disabled\n");
1897     else
1898         if (!NewThread(ThreadDNSAddressSeed, NULL))
1899             printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
1900
1901     // Map ports with UPnP
1902     if (fUseUPnP)
1903         MapPort();
1904
1905     // Get addresses from IRC and advertise ours
1906     if (!NewThread(ThreadIRCSeed, NULL))
1907         printf("Error: NewThread(ThreadIRCSeed) failed\n");
1908
1909     // Send and receive from sockets, accept connections
1910     if (!NewThread(ThreadSocketHandler, NULL))
1911         printf("Error: NewThread(ThreadSocketHandler) failed\n");
1912
1913     // Initiate outbound connections from -addnode
1914     if (!NewThread(ThreadOpenAddedConnections, NULL))
1915         printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
1916
1917     // Initiate outbound connections
1918     if (!NewThread(ThreadOpenConnections, NULL))
1919         printf("Error: NewThread(ThreadOpenConnections) failed\n");
1920
1921     // Process messages
1922     if (!NewThread(ThreadMessageHandler, NULL))
1923         printf("Error: NewThread(ThreadMessageHandler) failed\n");
1924
1925     // Dump network addresses
1926     if (!NewThread(ThreadDumpAddress, NULL))
1927         printf("Error; NewThread(ThreadDumpAddress) failed\n");
1928
1929     // ppcoin: mint proof-of-stake blocks in the background
1930     if (!NewThread(ThreadStakeMinter, pwalletMain))
1931         printf("Error: NewThread(ThreadStakeMinter) failed\n");
1932 }
1933
1934 bool StopNode()
1935 {
1936     printf("StopNode()\n");
1937     fShutdown = true;
1938     nTransactionsUpdated++;
1939     int64 nStart = GetTime();
1940     {
1941         LOCK(cs_main);
1942         ThreadScriptCheckQuit();
1943     }
1944     if (semOutbound)
1945         for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1946             semOutbound->post();
1947     do
1948     {
1949         int nThreadsRunning = 0;
1950         for (int n = 0; n < THREAD_MAX; n++)
1951             nThreadsRunning += vnThreadsRunning[n];
1952         if (nThreadsRunning == 0)
1953             break;
1954         if (GetTime() - nStart > 20)
1955             break;
1956         Sleep(20);
1957     } while(true);
1958     if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
1959     if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
1960     if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
1961     if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
1962     if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
1963 #ifdef USE_UPNP
1964     if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
1965 #endif
1966     if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
1967     if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
1968     if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
1969     if (vnThreadsRunning[THREAD_MINTER] > 0) printf("ThreadStakeMinter still running\n");
1970     if (vnThreadsRunning[THREAD_SCRIPTCHECK] > 0) printf("ThreadScriptCheck still running\n");
1971     while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0 || vnThreadsRunning[THREAD_SCRIPTCHECK] > 0)
1972         Sleep(20);
1973     Sleep(50);
1974     DumpAddresses();
1975     return true;
1976 }
1977
1978 class CNetCleanup
1979 {
1980 public:
1981     CNetCleanup()
1982     {
1983     }
1984     ~CNetCleanup()
1985     {
1986         // Close sockets
1987         BOOST_FOREACH(CNode* pnode, vNodes)
1988             if (pnode->hSocket != INVALID_SOCKET)
1989                 closesocket(pnode->hSocket);
1990         BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
1991             if (hListenSocket != INVALID_SOCKET)
1992                 if (closesocket(hListenSocket) == SOCKET_ERROR)
1993                     printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
1994
1995 #ifdef WIN32
1996         // Shutdown Windows Sockets
1997         WSACleanup();
1998 #endif
1999     }
2000 }
2001 instance_of_cnetcleanup;
2002
2003 void RelayTransaction(const CTransaction& tx, const uint256& hash)
2004 {
2005     CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
2006     ss.reserve(10000);
2007     ss << tx;
2008     RelayTransaction(tx, hash, ss);
2009 }
2010
2011 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
2012 {
2013     CInv inv(MSG_TX, hash);
2014     {
2015         LOCK(cs_mapRelay);
2016         // Expire old relay messages
2017         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
2018         {
2019             mapRelay.erase(vRelayExpiration.front().second);
2020             vRelayExpiration.pop_front();
2021         }
2022
2023         // Save original serialized message so newer versions are preserved
2024         mapRelay.insert(std::make_pair(inv, ss));
2025         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
2026     }
2027
2028     RelayInventory(inv);
2029 }