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.
12 #include "ui_interface.h"
19 #include <miniupnpc/miniwget.h>
20 #include <miniupnpc/miniupnpc.h>
21 #include <miniupnpc/upnpcommands.h>
22 #include <miniupnpc/upnperrors.h>
26 using namespace boost;
28 static const int MAX_OUTBOUND_CONNECTIONS = 16;
30 void ThreadMessageHandler2(void* parg);
31 void ThreadSocketHandler2(void* parg);
32 void ThreadOpenConnections2(void* parg);
33 void ThreadOpenAddedConnections2(void* parg);
35 void ThreadMapPort2(void* parg);
37 void ThreadDNSAddressSeed2(void* parg);
38 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
41 struct LocalServiceInfo {
47 // Global state variables
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 CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices);
59 uint64 nLocalHostNonce = 0;
60 array<int, THREAD_MAX> vnThreadsRunning;
61 static std::vector<SOCKET> vhListenSocket;
64 vector<CNode*> vNodes;
65 CCriticalSection cs_vNodes;
66 map<CInv, CDataStream> mapRelay;
67 deque<pair<int64, CInv> > vRelayExpiration;
68 CCriticalSection cs_mapRelay;
69 map<CInv, int64> mapAlreadyAskedFor;
71 static deque<string> vOneShots;
72 CCriticalSection cs_vOneShots;
74 set<CNetAddr> setservAddNodeAddresses;
75 CCriticalSection cs_setservAddNodeAddresses;
77 static CSemaphore *semOutbound = NULL;
79 void AddOneShot(string strDest)
82 vOneShots.push_back(strDest);
85 unsigned short GetListenPort()
87 return (unsigned short)(GetArg("-port", GetDefaultPort()));
90 void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
92 // Filter out duplicate requests
93 if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
95 pindexLastGetBlocksBegin = pindexBegin;
96 hashLastGetBlocksEnd = hashEnd;
98 PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
101 // find 'best' local address for a particular peer
102 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
108 int nBestReachability = -1;
110 LOCK(cs_mapLocalHost);
111 for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
113 int nScore = (*it).second.nScore;
114 int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
115 if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
117 addr = CService((*it).first, (*it).second.nPort);
118 nBestReachability = nReachability;
123 return nBestScore >= 0;
126 // get best local address for a particular peer as a CAddress
127 CAddress GetLocalAddress(const CNetAddr *paddrPeer)
129 CAddress ret(CService("0.0.0.0",0),0);
131 if (GetLocal(addr, paddrPeer))
133 ret = CAddress(addr);
134 ret.nServices = nLocalServices;
135 ret.nTime = GetAdjustedTime();
140 bool RecvLine(SOCKET hSocket, string& strLine)
146 int nBytes = recv(hSocket, &c, 1, 0);
154 if (strLine.size() >= 9000)
157 else if (nBytes <= 0)
163 int nErr = WSAGetLastError();
164 if (nErr == WSAEMSGSIZE)
166 if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
172 if (!strLine.empty())
177 printf("socket closed\n");
183 int nErr = WSAGetLastError();
184 printf("recv failed: %d\n", nErr);
191 // used when scores of local addresses may have changed
192 // pushes better local address to peers
193 void static AdvertizeLocal()
196 BOOST_FOREACH(CNode* pnode, vNodes)
198 if (pnode->fSuccessfullyConnected)
200 CAddress addrLocal = GetLocalAddress(&pnode->addr);
201 if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
203 pnode->PushAddress(addrLocal);
204 pnode->addrLocal = addrLocal;
210 void SetReachable(enum Network net, bool fFlag)
212 LOCK(cs_mapLocalHost);
213 vfReachable[net] = fFlag;
214 if (net == NET_IPV6 && fFlag)
215 vfReachable[NET_IPV4] = true;
218 // learn a new local address
219 bool AddLocal(const CService& addr, int nScore)
221 if (!addr.IsRoutable())
224 if (!fDiscover && nScore < LOCAL_MANUAL)
230 printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
233 LOCK(cs_mapLocalHost);
234 bool fAlready = mapLocalHost.count(addr) > 0;
235 LocalServiceInfo &info = mapLocalHost[addr];
236 if (!fAlready || nScore >= info.nScore) {
237 info.nScore = nScore + (fAlready ? 1 : 0);
238 info.nPort = addr.GetPort();
240 SetReachable(addr.GetNetwork());
248 bool AddLocal(const CNetAddr &addr, int nScore)
250 return AddLocal(CService(addr, GetListenPort()), nScore);
253 /** Make a particular network entirely off-limits (no automatic connects to it) */
254 void SetLimited(enum Network net, bool fLimited)
256 if (net == NET_UNROUTABLE)
258 LOCK(cs_mapLocalHost);
259 vfLimited[net] = fLimited;
262 bool IsLimited(enum Network net)
264 LOCK(cs_mapLocalHost);
265 return vfLimited[net];
268 bool IsLimited(const CNetAddr &addr)
270 return IsLimited(addr.GetNetwork());
273 /** vote for a local address */
274 bool SeenLocal(const CService& addr)
277 LOCK(cs_mapLocalHost);
278 if (mapLocalHost.count(addr) == 0)
280 mapLocalHost[addr].nScore++;
288 /** check whether a given address is potentially local */
289 bool IsLocal(const CService& addr)
291 LOCK(cs_mapLocalHost);
292 return mapLocalHost.count(addr) > 0;
295 /** check whether a given address is in a network we can probably connect to */
296 bool IsReachable(const CNetAddr& addr)
298 LOCK(cs_mapLocalHost);
299 enum Network net = addr.GetNetwork();
300 return vfReachable[net] && !vfLimited[net];
303 bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
306 if (!ConnectSocket(addrConnect, hSocket))
307 return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
309 send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
312 while (RecvLine(hSocket, strLine))
314 if (strLine.empty()) // HTTP response is separated from headers by blank line
318 if (!RecvLine(hSocket, strLine))
320 closesocket(hSocket);
323 if (pszKeyword == NULL)
325 if (strLine.find(pszKeyword) != string::npos)
327 strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
331 closesocket(hSocket);
332 if (strLine.find("<") != string::npos)
333 strLine = strLine.substr(0, strLine.find("<"));
334 strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));
335 while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))
336 strLine.resize(strLine.size()-1);
337 CService addr(strLine,0,true);
338 printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());
339 if (!addr.IsValid() || !addr.IsRoutable())
345 closesocket(hSocket);
346 return error("GetMyExternalIP() : connection closed");
349 // We now get our external IP from the IRC server first and only use this as a backup
350 bool GetMyExternalIP(CNetAddr& ipRet)
352 CService addrConnect;
354 const char* pszKeyword;
356 for (int nLookup = 0; nLookup <= 1; nLookup++)
357 for (int nHost = 1; nHost <= 2; nHost++)
359 // We should be phasing out our use of sites like these. If we need
360 // replacements, we should ask for volunteers to put this simple
361 // php file on their web server that prints the client IP:
362 // <?php echo $_SERVER["REMOTE_ADDR"]; ?>
365 addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
369 CService addrIP("checkip.dyndns.org", 80, true);
370 if (addrIP.IsValid())
371 addrConnect = addrIP;
374 pszGet = "GET / HTTP/1.1\r\n"
375 "Host: checkip.dyndns.org\r\n"
376 "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
377 "Connection: close\r\n"
380 pszKeyword = "Address:";
384 addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
388 CService addrIP("www.showmyip.com", 80, true);
389 if (addrIP.IsValid())
390 addrConnect = addrIP;
393 pszGet = "GET /simple/ HTTP/1.1\r\n"
394 "Host: www.showmyip.com\r\n"
395 "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"
396 "Connection: close\r\n"
399 pszKeyword = NULL; // Returns just IP address
402 if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
409 void ThreadGetMyExternalIP(void* parg)
411 // Make this thread recognisable as the external IP detection thread
412 RenameThread("bitcoin-ext-ip");
414 CNetAddr addrLocalHost;
415 if (GetMyExternalIP(addrLocalHost))
417 printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
418 AddLocal(addrLocalHost, LOCAL_HTTP);
426 void AddressCurrentlyConnected(const CService& addr)
428 addrman.Connected(addr);
437 CNode* FindNode(const CNetAddr& ip)
441 BOOST_FOREACH(CNode* pnode, vNodes)
442 if ((CNetAddr)pnode->addr == ip)
448 CNode* FindNode(std::string addrName)
451 BOOST_FOREACH(CNode* pnode, vNodes)
452 if (pnode->addrName == addrName)
457 CNode* FindNode(const CService& addr)
461 BOOST_FOREACH(CNode* pnode, vNodes)
462 if ((CService)pnode->addr == addr)
468 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
470 if (pszDest == NULL) {
471 if (IsLocal(addrConnect))
474 // Look for an existing connection
475 CNode* pnode = FindNode((CService)addrConnect);
479 pnode->AddRef(nTimeout);
488 printf("trying connection %s lastseen=%.1fhrs\n",
489 pszDest ? pszDest : addrConnect.ToString().c_str(),
490 pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
494 if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
496 addrman.Attempt(addrConnect);
499 printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
501 // Set to non-blocking
504 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
505 printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
507 if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
508 printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
512 CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
514 pnode->AddRef(nTimeout);
520 vNodes.push_back(pnode);
523 pnode->nTimeConnected = GetTime();
532 void CNode::CloseSocketDisconnect()
535 if (hSocket != INVALID_SOCKET)
537 printf("disconnecting node %s\n", addrName.c_str());
538 closesocket(hSocket);
539 hSocket = INVALID_SOCKET;
544 void CNode::Cleanup()
549 void CNode::PushVersion()
551 /// when NTP implemented, change to just nTime = GetAdjustedTime()
552 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
553 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
554 CAddress addrMe = GetLocalAddress(&addr);
555 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
556 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());
557 PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
558 nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
565 std::map<CNetAddr, int64> CNode::setBanned;
566 CCriticalSection CNode::cs_setBanned;
568 void CNode::ClearBanned()
573 bool CNode::IsBanned(CNetAddr ip)
575 bool fResult = false;
578 std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
579 if (i != setBanned.end())
581 int64 t = (*i).second;
589 bool CNode::Misbehaving(int howmuch)
593 printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
597 nMisbehavior += howmuch;
598 if (nMisbehavior >= GetArg("-banscore", 100))
600 int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
601 printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
604 if (setBanned[addr] < banTime)
605 setBanned[addr] = banTime;
607 CloseSocketDisconnect();
610 printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
615 #define X(name) stats.name = name
616 void CNode::copyStats(CNodeStats &stats)
641 void ThreadSocketHandler(void* parg)
643 // Make this thread recognisable as the networking thread
644 RenameThread("bitcoin-net");
648 vnThreadsRunning[THREAD_SOCKETHANDLER]++;
649 ThreadSocketHandler2(parg);
650 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
652 catch (std::exception& e) {
653 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
654 PrintException(&e, "ThreadSocketHandler()");
656 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
657 throw; // support pthread_cancel()
659 printf("ThreadSocketHandler exited\n");
662 void ThreadSocketHandler2(void* parg)
664 printf("ThreadSocketHandler started\n");
665 list<CNode*> vNodesDisconnected;
666 unsigned int nPrevNodeCount = 0;
675 // Disconnect unused nodes
676 vector<CNode*> vNodesCopy = vNodes;
677 BOOST_FOREACH(CNode* pnode, vNodesCopy)
679 if (pnode->fDisconnect ||
680 (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
682 // remove from vNodes
683 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
685 // release outbound grant (if any)
686 pnode->grantOutbound.Release();
688 // close socket and cleanup
689 pnode->CloseSocketDisconnect();
692 // hold in disconnected pool until all refs are released
693 pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
694 if (pnode->fNetworkNode || pnode->fInbound)
696 vNodesDisconnected.push_back(pnode);
700 // Delete disconnected nodes
701 list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
702 BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
704 // wait until threads are done using it
705 if (pnode->GetRefCount() <= 0)
707 bool fDelete = false;
709 TRY_LOCK(pnode->cs_vSend, lockSend);
712 TRY_LOCK(pnode->cs_vRecv, lockRecv);
715 TRY_LOCK(pnode->cs_mapRequests, lockReq);
718 TRY_LOCK(pnode->cs_inventory, lockInv);
727 vNodesDisconnected.remove(pnode);
733 if (vNodes.size() != nPrevNodeCount)
735 nPrevNodeCount = vNodes.size();
736 uiInterface.NotifyNumConnectionsChanged(vNodes.size());
741 // Find which sockets have data to receive
743 struct timeval timeout;
745 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
752 FD_ZERO(&fdsetError);
753 SOCKET hSocketMax = 0;
754 bool have_fds = false;
756 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
757 FD_SET(hListenSocket, &fdsetRecv);
758 hSocketMax = max(hSocketMax, hListenSocket);
763 BOOST_FOREACH(CNode* pnode, vNodes)
765 if (pnode->hSocket == INVALID_SOCKET)
767 FD_SET(pnode->hSocket, &fdsetRecv);
768 FD_SET(pnode->hSocket, &fdsetError);
769 hSocketMax = max(hSocketMax, pnode->hSocket);
772 TRY_LOCK(pnode->cs_vSend, lockSend);
773 if (lockSend && !pnode->vSend.empty())
774 FD_SET(pnode->hSocket, &fdsetSend);
779 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
780 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
781 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
782 vnThreadsRunning[THREAD_SOCKETHANDLER]++;
785 if (nSelect == SOCKET_ERROR)
789 int nErr = WSAGetLastError();
790 printf("socket select error %d\n", nErr);
791 for (unsigned int i = 0; i <= hSocketMax; i++)
792 FD_SET(i, &fdsetRecv);
795 FD_ZERO(&fdsetError);
796 Sleep(timeout.tv_usec/1000);
801 // Accept new connections
803 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
804 if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
807 struct sockaddr_storage sockaddr;
809 struct sockaddr sockaddr;
811 socklen_t len = sizeof(sockaddr);
812 SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
816 if (hSocket != INVALID_SOCKET)
817 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
818 printf("Warning: Unknown socket family\n");
822 BOOST_FOREACH(CNode* pnode, vNodes)
827 if (hSocket == INVALID_SOCKET)
829 int nErr = WSAGetLastError();
830 if (nErr != WSAEWOULDBLOCK)
831 printf("socket error accept failed: %d\n", nErr);
833 else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
836 LOCK(cs_setservAddNodeAddresses);
837 if (!setservAddNodeAddresses.count(addr))
838 closesocket(hSocket);
841 else if (CNode::IsBanned(addr))
843 printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
844 closesocket(hSocket);
848 printf("accepted connection %s\n", addr.ToString().c_str());
849 CNode* pnode = new CNode(hSocket, addr, "", true);
853 vNodes.push_back(pnode);
860 // Service each socket
862 vector<CNode*> vNodesCopy;
866 BOOST_FOREACH(CNode* pnode, vNodesCopy)
869 BOOST_FOREACH(CNode* pnode, vNodesCopy)
877 if (pnode->hSocket == INVALID_SOCKET)
879 if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
881 TRY_LOCK(pnode->cs_vRecv, lockRecv);
884 CDataStream& vRecv = pnode->vRecv;
885 unsigned int nPos = vRecv.size();
887 if (nPos > ReceiveBufferSize()) {
888 if (!pnode->fDisconnect)
889 printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
890 pnode->CloseSocketDisconnect();
893 // typical socket buffer is 8K-64K
894 char pchBuf[0x10000];
895 int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
898 vRecv.resize(nPos + nBytes);
899 memcpy(&vRecv[nPos], pchBuf, nBytes);
900 pnode->nLastRecv = GetTime();
902 else if (nBytes == 0)
904 // socket closed gracefully
905 if (!pnode->fDisconnect)
906 printf("socket closed\n");
907 pnode->CloseSocketDisconnect();
912 int nErr = WSAGetLastError();
913 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
915 if (!pnode->fDisconnect)
916 printf("socket recv error %d\n", nErr);
917 pnode->CloseSocketDisconnect();
927 if (pnode->hSocket == INVALID_SOCKET)
929 if (FD_ISSET(pnode->hSocket, &fdsetSend))
931 TRY_LOCK(pnode->cs_vSend, lockSend);
934 CDataStream& vSend = pnode->vSend;
937 int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
940 vSend.erase(vSend.begin(), vSend.begin() + nBytes);
941 pnode->nLastSend = GetTime();
946 int nErr = WSAGetLastError();
947 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
949 printf("socket send error %d\n", nErr);
950 pnode->CloseSocketDisconnect();
958 // Inactivity checking
960 if (pnode->vSend.empty())
961 pnode->nLastSendEmpty = GetTime();
962 if (GetTime() - pnode->nTimeConnected > 60)
964 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
966 printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
967 pnode->fDisconnect = true;
969 else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
971 printf("socket not sending\n");
972 pnode->fDisconnect = true;
974 else if (GetTime() - pnode->nLastRecv > 90*60)
976 printf("socket inactivity timeout\n");
977 pnode->fDisconnect = true;
983 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1000 void ThreadMapPort(void* parg)
1002 // Make this thread recognisable as the UPnP thread
1003 RenameThread("bitcoin-UPnP");
1007 vnThreadsRunning[THREAD_UPNP]++;
1008 ThreadMapPort2(parg);
1009 vnThreadsRunning[THREAD_UPNP]--;
1011 catch (std::exception& e) {
1012 vnThreadsRunning[THREAD_UPNP]--;
1013 PrintException(&e, "ThreadMapPort()");
1015 vnThreadsRunning[THREAD_UPNP]--;
1016 PrintException(NULL, "ThreadMapPort()");
1018 printf("ThreadMapPort exited\n");
1021 void ThreadMapPort2(void* parg)
1023 printf("ThreadMapPort started\n");
1025 std::string port = strprintf("%u", GetListenPort());
1026 const char * multicastif = 0;
1027 const char * minissdpdpath = 0;
1028 struct UPNPDev * devlist = 0;
1031 #ifndef UPNPDISCOVER_SUCCESS
1033 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1037 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1040 struct UPNPUrls urls;
1041 struct IGDdatas data;
1044 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1048 char externalIPAddress[40];
1049 r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1050 if(r != UPNPCOMMAND_SUCCESS)
1051 printf("UPnP: GetExternalIPAddress() returned %d\n", r);
1054 if(externalIPAddress[0])
1056 printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
1057 AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
1060 printf("UPnP: GetExternalIPAddress failed.\n");
1064 string strDesc = "NovaCoin " + FormatFullVersion();
1065 #ifndef UPNPDISCOVER_SUCCESS
1067 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1068 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1071 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1072 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1075 if(r!=UPNPCOMMAND_SUCCESS)
1076 printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1077 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1079 printf("UPnP Port Mapping successful.\n");
1083 if (fShutdown || !fUseUPnP)
1085 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1086 printf("UPNP_DeletePortMapping() returned : %d\n", r);
1087 freeUPNPDevlist(devlist); devlist = 0;
1088 FreeUPNPUrls(&urls);
1091 if (i % 600 == 0) // Refresh every 20 minutes
1093 #ifndef UPNPDISCOVER_SUCCESS
1095 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1096 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1099 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1100 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1103 if(r!=UPNPCOMMAND_SUCCESS)
1104 printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1105 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1107 printf("UPnP Port Mapping successful.\n");;
1113 printf("No valid UPnP IGDs found\n");
1114 freeUPNPDevlist(devlist); devlist = 0;
1116 FreeUPNPUrls(&urls);
1119 if (fShutdown || !fUseUPnP)
1128 if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
1130 if (!NewThread(ThreadMapPort, NULL))
1131 printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
1137 // Intentionally left blank.
1150 // Each pair gives a source name and a seed name.
1151 // The first name is used as information source for addrman.
1152 // The second name should resolve to a list of seed addresses.
1153 static const char *strDNSSeed[][2] = {
1154 {"novacoin.su", "dnsseed.novacoin.su"},
1157 void ThreadDNSAddressSeed(void* parg)
1159 // Make this thread recognisable as the DNS seeding thread
1160 RenameThread("bitcoin-dnsseed");
1164 vnThreadsRunning[THREAD_DNSSEED]++;
1165 ThreadDNSAddressSeed2(parg);
1166 vnThreadsRunning[THREAD_DNSSEED]--;
1168 catch (std::exception& e) {
1169 vnThreadsRunning[THREAD_DNSSEED]--;
1170 PrintException(&e, "ThreadDNSAddressSeed()");
1172 vnThreadsRunning[THREAD_DNSSEED]--;
1173 throw; // support pthread_cancel()
1175 printf("ThreadDNSAddressSeed exited\n");
1178 void ThreadDNSAddressSeed2(void* parg)
1180 printf("ThreadDNSAddressSeed started\n");
1185 printf("Loading addresses from DNS seeds (could take a while)\n");
1187 for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
1188 if (HaveNameProxy()) {
1189 AddOneShot(strDNSSeed[seed_idx][1]);
1191 vector<CNetAddr> vaddr;
1192 vector<CAddress> vAdd;
1193 if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
1195 BOOST_FOREACH(CNetAddr& ip, vaddr)
1197 int nOneDay = 24*3600;
1198 CAddress addr = CAddress(CService(ip, GetDefaultPort()));
1199 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1200 vAdd.push_back(addr);
1204 addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
1209 printf("%d addresses found from DNS seeds\n", found);
1223 unsigned int pnSeed[] =
1225 0x90EF78BC, 0x33F1C851, 0x36F1C851, 0xC6F5C851,
1228 void DumpAddresses()
1230 int64 nStart = GetTimeMillis();
1235 printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
1236 addrman.size(), GetTimeMillis() - nStart);
1239 void ThreadDumpAddress2(void* parg)
1241 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1245 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1247 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1249 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1252 void ThreadDumpAddress(void* parg)
1254 // Make this thread recognisable as the address dumping thread
1255 RenameThread("bitcoin-adrdump");
1259 ThreadDumpAddress2(parg);
1261 catch (std::exception& e) {
1262 PrintException(&e, "ThreadDumpAddress()");
1264 printf("ThreadDumpAddress exited\n");
1267 void ThreadOpenConnections(void* parg)
1269 // Make this thread recognisable as the connection opening thread
1270 RenameThread("bitcoin-opencon");
1274 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1275 ThreadOpenConnections2(parg);
1276 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1278 catch (std::exception& e) {
1279 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1280 PrintException(&e, "ThreadOpenConnections()");
1282 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1283 PrintException(NULL, "ThreadOpenConnections()");
1285 printf("ThreadOpenConnections exited\n");
1288 void static ProcessOneShot()
1293 if (vOneShots.empty())
1295 strDest = vOneShots.front();
1296 vOneShots.pop_front();
1299 CSemaphoreGrant grant(*semOutbound, true);
1301 if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1302 AddOneShot(strDest);
1306 // ppcoin: stake minter thread
1307 void static ThreadStakeMinter(void* parg)
1309 printf("ThreadStakeMinter started\n");
1310 CWallet* pwallet = (CWallet*)parg;
1313 vnThreadsRunning[THREAD_MINTER]++;
1314 StakeMiner(pwallet);
1315 vnThreadsRunning[THREAD_MINTER]--;
1317 catch (std::exception& e) {
1318 vnThreadsRunning[THREAD_MINTER]--;
1319 PrintException(&e, "ThreadStakeMinter()");
1321 vnThreadsRunning[THREAD_MINTER]--;
1322 PrintException(NULL, "ThreadStakeMinter()");
1324 printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
1327 void ThreadOpenConnections2(void* parg)
1329 printf("ThreadOpenConnections started\n");
1331 // Connect to specific addresses
1332 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1334 for (int64 nLoop = 0;; nLoop++)
1337 BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1340 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1341 for (int i = 0; i < 10 && i < nLoop; i++)
1352 // Initiate network connections
1353 int64 nStart = GetTime();
1358 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1360 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1365 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1366 CSemaphoreGrant grant(*semOutbound);
1367 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1371 // Add seed nodes if IRC isn't working
1372 if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
1374 std::vector<CAddress> vAdd;
1375 for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
1377 // It'll only connect to one or two seed nodes because once it connects,
1378 // it'll get a pile of addresses with newer timestamps.
1379 // Seed nodes are given a random 'last seen time' of between one and two
1381 const int64 nOneWeek = 7*24*60*60;
1383 memcpy(&ip, &pnSeed[i], sizeof(ip));
1384 CAddress addr(CService(ip, GetDefaultPort()));
1385 addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
1386 vAdd.push_back(addr);
1388 addrman.Add(vAdd, CNetAddr("127.0.0.1"));
1392 // Choose an address to connect to based on most recently seen
1394 CAddress addrConnect;
1396 // Only connect out to one peer per network group (/16 for IPv4).
1397 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1399 set<vector<unsigned char> > setConnected;
1402 BOOST_FOREACH(CNode* pnode, vNodes) {
1403 if (!pnode->fInbound) {
1404 setConnected.insert(pnode->addr.GetGroup());
1410 int64 nANow = GetAdjustedTime();
1415 // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
1416 CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
1418 // if we selected an invalid address, restart
1419 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1422 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1423 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1424 // already-connected network ranges, ...) before trying new addrman addresses.
1429 if (IsLimited(addr))
1432 // only consider very recently tried nodes after 30 failed attempts
1433 if (nANow - addr.nLastTry < 600 && nTries < 30)
1436 // do not allow non-default ports, unless after 50 invalid addresses selected already
1437 if (addr.GetPort() != GetDefaultPort() && nTries < 50)
1444 if (addrConnect.IsValid())
1445 OpenNetworkConnection(addrConnect, &grant);
1449 void ThreadOpenAddedConnections(void* parg)
1451 // Make this thread recognisable as the connection opening thread
1452 RenameThread("bitcoin-opencon");
1456 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1457 ThreadOpenAddedConnections2(parg);
1458 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1460 catch (std::exception& e) {
1461 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1462 PrintException(&e, "ThreadOpenAddedConnections()");
1464 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1465 PrintException(NULL, "ThreadOpenAddedConnections()");
1467 printf("ThreadOpenAddedConnections exited\n");
1470 void ThreadOpenAddedConnections2(void* parg)
1472 printf("ThreadOpenAddedConnections started\n");
1474 if (mapArgs.count("-addnode") == 0)
1477 if (HaveNameProxy()) {
1479 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
1481 CSemaphoreGrant grant(*semOutbound);
1482 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1485 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1486 Sleep(120000); // Retry every 2 minutes
1487 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1492 vector<vector<CService> > vservAddressesToAdd(0);
1493 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
1495 vector<CService> vservNode(0);
1496 if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
1498 vservAddressesToAdd.push_back(vservNode);
1500 LOCK(cs_setservAddNodeAddresses);
1501 BOOST_FOREACH(CService& serv, vservNode)
1502 setservAddNodeAddresses.insert(serv);
1508 vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
1509 // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1510 // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1513 BOOST_FOREACH(CNode* pnode, vNodes)
1514 for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
1515 BOOST_FOREACH(CService& addrNode, *(it))
1516 if (pnode->addr == addrNode)
1518 it = vservConnectAddresses.erase(it);
1523 BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
1525 CSemaphoreGrant grant(*semOutbound);
1526 OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
1533 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1534 Sleep(120000); // Retry every 2 minutes
1535 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1541 // if successful, this moves the passed grant to the constructed node
1542 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
1545 // Initiate outbound network connection
1550 if (IsLocal(addrConnect) ||
1551 FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1552 FindNode(addrConnect.ToStringIPPort().c_str()))
1554 if (strDest && FindNode(strDest))
1557 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1558 CNode* pnode = ConnectNode(addrConnect, strDest);
1559 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1565 grantOutbound->MoveTo(pnode->grantOutbound);
1566 pnode->fNetworkNode = true;
1568 pnode->fOneShot = true;
1580 void ThreadMessageHandler(void* parg)
1582 // Make this thread recognisable as the message handling thread
1583 RenameThread("bitcoin-msghand");
1587 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1588 ThreadMessageHandler2(parg);
1589 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1591 catch (std::exception& e) {
1592 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1593 PrintException(&e, "ThreadMessageHandler()");
1595 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1596 PrintException(NULL, "ThreadMessageHandler()");
1598 printf("ThreadMessageHandler exited\n");
1601 void ThreadMessageHandler2(void* parg)
1603 printf("ThreadMessageHandler started\n");
1604 SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1607 vector<CNode*> vNodesCopy;
1610 vNodesCopy = vNodes;
1611 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1615 // Poll the connected nodes for messages
1616 CNode* pnodeTrickle = NULL;
1617 if (!vNodesCopy.empty())
1618 pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1619 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1623 TRY_LOCK(pnode->cs_vRecv, lockRecv);
1625 ProcessMessages(pnode);
1632 TRY_LOCK(pnode->cs_vSend, lockSend);
1634 SendMessages(pnode, pnode == pnodeTrickle);
1642 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1646 // Wait and allow messages to bunch up.
1647 // Reduce vnThreadsRunning so StopNode has permission to exit while
1648 // we're sleeping, but we must always check fShutdown after doing this.
1649 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1651 if (fRequestShutdown)
1653 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1664 bool BindListenPort(const CService &addrBind, string& strError)
1670 // Initialize Windows Sockets
1672 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1673 if (ret != NO_ERROR)
1675 strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
1676 printf("%s\n", strError.c_str());
1681 // Create socket for listening for incoming connections
1683 struct sockaddr_storage sockaddr;
1685 struct sockaddr sockaddr;
1687 socklen_t len = sizeof(sockaddr);
1688 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1690 strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
1691 printf("%s\n", strError.c_str());
1695 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1696 if (hListenSocket == INVALID_SOCKET)
1698 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1699 printf("%s\n", strError.c_str());
1704 // Different way of disabling SIGPIPE on BSD
1705 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1709 // Allow binding if the port is still in TIME_WAIT state after
1710 // the program was closed and restarted. Not an issue on windows.
1711 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1716 // Set to non-blocking, incoming connections will also inherit this
1717 if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1719 if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1722 strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1723 printf("%s\n", strError.c_str());
1728 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1729 // and enable it by default or not. Try to enable it, if possible.
1730 if (addrBind.IsIPv6()) {
1733 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1735 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1739 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
1740 int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
1741 // this call is allowed to fail
1742 setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
1747 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1749 int nErr = WSAGetLastError();
1750 if (nErr == WSAEADDRINUSE)
1751 strError = strprintf(_("Unable to bind to %s on this computer. NovaCoin is probably already running."), addrBind.ToString().c_str());
1753 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
1754 printf("%s\n", strError.c_str());
1757 printf("Bound to %s\n", addrBind.ToString().c_str());
1759 // Listen for incoming connections
1760 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1762 strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1763 printf("%s\n", strError.c_str());
1767 vhListenSocket.push_back(hListenSocket);
1769 if (addrBind.IsRoutable() && fDiscover)
1770 AddLocal(addrBind, LOCAL_BIND);
1775 void static Discover()
1781 // Get local host IP
1782 char pszHostName[1000] = "";
1783 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1785 vector<CNetAddr> vaddr;
1786 if (LookupHost(pszHostName, vaddr))
1788 BOOST_FOREACH (const CNetAddr &addr, vaddr)
1790 AddLocal(addr, LOCAL_IF);
1795 // Get local host ip
1796 struct ifaddrs* myaddrs;
1797 if (getifaddrs(&myaddrs) == 0)
1799 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1801 if (ifa->ifa_addr == NULL) continue;
1802 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1803 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1804 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1805 if (ifa->ifa_addr->sa_family == AF_INET)
1807 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1808 CNetAddr addr(s4->sin_addr);
1809 if (AddLocal(addr, LOCAL_IF))
1810 printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1813 else if (ifa->ifa_addr->sa_family == AF_INET6)
1815 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1816 CNetAddr addr(s6->sin6_addr);
1817 if (AddLocal(addr, LOCAL_IF))
1818 printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1822 freeifaddrs(myaddrs);
1826 // Don't use external IPv4 discovery, when -onlynet="IPv6"
1827 if (!IsLimited(NET_IPV4))
1828 NewThread(ThreadGetMyExternalIP, NULL);
1831 void StartNode(void* parg)
1833 // Make this thread recognisable as the startup thread
1834 RenameThread("bitcoin-start");
1836 if (semOutbound == NULL) {
1837 // initialize semaphore
1838 int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
1839 semOutbound = new CSemaphore(nMaxOutbound);
1842 if (pnodeLocalHost == NULL)
1843 pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1851 if (!GetBoolArg("-dnsseed", true))
1852 printf("DNS seeding disabled\n");
1854 if (!NewThread(ThreadDNSAddressSeed, NULL))
1855 printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
1857 // Map ports with UPnP
1861 // Get addresses from IRC and advertise ours
1862 if (!NewThread(ThreadIRCSeed, NULL))
1863 printf("Error: NewThread(ThreadIRCSeed) failed\n");
1865 // Send and receive from sockets, accept connections
1866 if (!NewThread(ThreadSocketHandler, NULL))
1867 printf("Error: NewThread(ThreadSocketHandler) failed\n");
1869 // Initiate outbound connections from -addnode
1870 if (!NewThread(ThreadOpenAddedConnections, NULL))
1871 printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
1873 // Initiate outbound connections
1874 if (!NewThread(ThreadOpenConnections, NULL))
1875 printf("Error: NewThread(ThreadOpenConnections) failed\n");
1878 if (!NewThread(ThreadMessageHandler, NULL))
1879 printf("Error: NewThread(ThreadMessageHandler) failed\n");
1881 // Dump network addresses
1882 if (!NewThread(ThreadDumpAddress, NULL))
1883 printf("Error; NewThread(ThreadDumpAddress) failed\n");
1885 // ppcoin: mint proof-of-stake blocks in the background
1886 if (!NewThread(ThreadStakeMinter, pwalletMain))
1887 printf("Error: NewThread(ThreadStakeMinter) failed\n");
1892 printf("StopNode()\n");
1894 nTransactionsUpdated++;
1895 int64 nStart = GetTime();
1897 for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1898 semOutbound->post();
1901 int nThreadsRunning = 0;
1902 for (int n = 0; n < THREAD_MAX; n++)
1903 nThreadsRunning += vnThreadsRunning[n];
1904 if (nThreadsRunning == 0)
1906 if (GetTime() - nStart > 20)
1910 if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
1911 if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
1912 if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
1913 if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
1914 if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
1916 if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
1918 if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
1919 if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
1920 if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
1921 if (vnThreadsRunning[THREAD_MINTER] > 0) printf("ThreadStakeMinter still running\n");
1922 while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
1938 BOOST_FOREACH(CNode* pnode, vNodes)
1939 if (pnode->hSocket != INVALID_SOCKET)
1940 closesocket(pnode->hSocket);
1941 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
1942 if (hListenSocket != INVALID_SOCKET)
1943 if (closesocket(hListenSocket) == SOCKET_ERROR)
1944 printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
1947 // Shutdown Windows Sockets
1952 instance_of_cnetcleanup;