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");
1082 if (fShutdown || !fUseUPnP)
1084 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1085 printf("UPNP_DeletePortMapping() returned : %d\n", r);
1086 freeUPNPDevlist(devlist); devlist = 0;
1087 FreeUPNPUrls(&urls);
1090 if (i % 600 == 0) // Refresh every 20 minutes
1092 #ifndef UPNPDISCOVER_SUCCESS
1094 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1095 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1098 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1099 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1102 if(r!=UPNPCOMMAND_SUCCESS)
1103 printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1104 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1106 printf("UPnP Port Mapping successful.\n");;
1112 printf("No valid UPnP IGDs found\n");
1113 freeUPNPDevlist(devlist); devlist = 0;
1115 FreeUPNPUrls(&urls);
1117 if (fShutdown || !fUseUPnP)
1126 if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
1128 if (!NewThread(ThreadMapPort, NULL))
1129 printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
1135 // Intentionally left blank.
1148 // Each pair gives a source name and a seed name.
1149 // The first name is used as information source for addrman.
1150 // The second name should resolve to a list of seed addresses.
1151 static const char *strDNSSeed[][2] = {
1152 {"novacoin.su", "dnsseed.novacoin.su"},
1155 void ThreadDNSAddressSeed(void* parg)
1157 // Make this thread recognisable as the DNS seeding thread
1158 RenameThread("bitcoin-dnsseed");
1162 vnThreadsRunning[THREAD_DNSSEED]++;
1163 ThreadDNSAddressSeed2(parg);
1164 vnThreadsRunning[THREAD_DNSSEED]--;
1166 catch (std::exception& e) {
1167 vnThreadsRunning[THREAD_DNSSEED]--;
1168 PrintException(&e, "ThreadDNSAddressSeed()");
1170 vnThreadsRunning[THREAD_DNSSEED]--;
1171 throw; // support pthread_cancel()
1173 printf("ThreadDNSAddressSeed exited\n");
1176 void ThreadDNSAddressSeed2(void* parg)
1178 printf("ThreadDNSAddressSeed started\n");
1183 printf("Loading addresses from DNS seeds (could take a while)\n");
1185 for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
1186 if (HaveNameProxy()) {
1187 AddOneShot(strDNSSeed[seed_idx][1]);
1189 vector<CNetAddr> vaddr;
1190 vector<CAddress> vAdd;
1191 if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
1193 BOOST_FOREACH(CNetAddr& ip, vaddr)
1195 int nOneDay = 24*3600;
1196 CAddress addr = CAddress(CService(ip, GetDefaultPort()));
1197 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1198 vAdd.push_back(addr);
1202 addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
1207 printf("%d addresses found from DNS seeds\n", found);
1221 unsigned int pnSeed[] =
1223 0x90EF78BC, 0x33F1C851, 0x36F1C851, 0xC6F5C851,
1226 void DumpAddresses()
1228 int64 nStart = GetTimeMillis();
1233 printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
1234 addrman.size(), GetTimeMillis() - nStart);
1237 void ThreadDumpAddress2(void* parg)
1239 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1243 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1245 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1247 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1250 void ThreadDumpAddress(void* parg)
1252 // Make this thread recognisable as the address dumping thread
1253 RenameThread("bitcoin-adrdump");
1257 ThreadDumpAddress2(parg);
1259 catch (std::exception& e) {
1260 PrintException(&e, "ThreadDumpAddress()");
1262 printf("ThreadDumpAddress exited\n");
1265 void ThreadOpenConnections(void* parg)
1267 // Make this thread recognisable as the connection opening thread
1268 RenameThread("bitcoin-opencon");
1272 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1273 ThreadOpenConnections2(parg);
1274 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1276 catch (std::exception& e) {
1277 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1278 PrintException(&e, "ThreadOpenConnections()");
1280 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1281 PrintException(NULL, "ThreadOpenConnections()");
1283 printf("ThreadOpenConnections exited\n");
1286 void static ProcessOneShot()
1291 if (vOneShots.empty())
1293 strDest = vOneShots.front();
1294 vOneShots.pop_front();
1297 CSemaphoreGrant grant(*semOutbound, true);
1299 if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1300 AddOneShot(strDest);
1304 // ppcoin: stake minter thread
1305 void static ThreadStakeMinter(void* parg)
1307 printf("ThreadStakeMinter started\n");
1308 CWallet* pwallet = (CWallet*)parg;
1311 vnThreadsRunning[THREAD_MINTER]++;
1312 BitcoinMiner(pwallet, true);
1313 vnThreadsRunning[THREAD_MINTER]--;
1315 catch (std::exception& e) {
1316 vnThreadsRunning[THREAD_MINTER]--;
1317 PrintException(&e, "ThreadStakeMinter()");
1319 vnThreadsRunning[THREAD_MINTER]--;
1320 PrintException(NULL, "ThreadStakeMinter()");
1322 printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
1325 void ThreadOpenConnections2(void* parg)
1327 printf("ThreadOpenConnections started\n");
1329 // Connect to specific addresses
1330 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1332 for (int64 nLoop = 0;; nLoop++)
1335 BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1338 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1339 for (int i = 0; i < 10 && i < nLoop; i++)
1350 // Initiate network connections
1351 int64 nStart = GetTime();
1356 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1358 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1363 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1364 CSemaphoreGrant grant(*semOutbound);
1365 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1369 // Add seed nodes if IRC isn't working
1370 if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
1372 std::vector<CAddress> vAdd;
1373 for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
1375 // It'll only connect to one or two seed nodes because once it connects,
1376 // it'll get a pile of addresses with newer timestamps.
1377 // Seed nodes are given a random 'last seen time' of between one and two
1379 const int64 nOneWeek = 7*24*60*60;
1381 memcpy(&ip, &pnSeed[i], sizeof(ip));
1382 CAddress addr(CService(ip, GetDefaultPort()));
1383 addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
1384 vAdd.push_back(addr);
1386 addrman.Add(vAdd, CNetAddr("127.0.0.1"));
1390 // Choose an address to connect to based on most recently seen
1392 CAddress addrConnect;
1394 // Only connect out to one peer per network group (/16 for IPv4).
1395 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1397 set<vector<unsigned char> > setConnected;
1400 BOOST_FOREACH(CNode* pnode, vNodes) {
1401 if (!pnode->fInbound) {
1402 setConnected.insert(pnode->addr.GetGroup());
1408 int64 nANow = GetAdjustedTime();
1413 // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
1414 CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
1416 // if we selected an invalid address, restart
1417 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1420 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1421 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1422 // already-connected network ranges, ...) before trying new addrman addresses.
1427 if (IsLimited(addr))
1430 // only consider very recently tried nodes after 30 failed attempts
1431 if (nANow - addr.nLastTry < 600 && nTries < 30)
1434 // do not allow non-default ports, unless after 50 invalid addresses selected already
1435 if (addr.GetPort() != GetDefaultPort() && nTries < 50)
1442 if (addrConnect.IsValid())
1443 OpenNetworkConnection(addrConnect, &grant);
1447 void ThreadOpenAddedConnections(void* parg)
1449 // Make this thread recognisable as the connection opening thread
1450 RenameThread("bitcoin-opencon");
1454 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1455 ThreadOpenAddedConnections2(parg);
1456 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1458 catch (std::exception& e) {
1459 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1460 PrintException(&e, "ThreadOpenAddedConnections()");
1462 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1463 PrintException(NULL, "ThreadOpenAddedConnections()");
1465 printf("ThreadOpenAddedConnections exited\n");
1468 void ThreadOpenAddedConnections2(void* parg)
1470 printf("ThreadOpenAddedConnections started\n");
1472 if (mapArgs.count("-addnode") == 0)
1475 if (HaveNameProxy()) {
1477 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
1479 CSemaphoreGrant grant(*semOutbound);
1480 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1483 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1484 Sleep(120000); // Retry every 2 minutes
1485 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1490 vector<vector<CService> > vservAddressesToAdd(0);
1491 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
1493 vector<CService> vservNode(0);
1494 if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
1496 vservAddressesToAdd.push_back(vservNode);
1498 LOCK(cs_setservAddNodeAddresses);
1499 BOOST_FOREACH(CService& serv, vservNode)
1500 setservAddNodeAddresses.insert(serv);
1506 vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
1507 // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1508 // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1511 BOOST_FOREACH(CNode* pnode, vNodes)
1512 for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
1513 BOOST_FOREACH(CService& addrNode, *(it))
1514 if (pnode->addr == addrNode)
1516 it = vservConnectAddresses.erase(it);
1521 BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
1523 CSemaphoreGrant grant(*semOutbound);
1524 OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
1531 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1532 Sleep(120000); // Retry every 2 minutes
1533 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1539 // if successful, this moves the passed grant to the constructed node
1540 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
1543 // Initiate outbound network connection
1548 if (IsLocal(addrConnect) ||
1549 FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1550 FindNode(addrConnect.ToStringIPPort().c_str()))
1552 if (strDest && FindNode(strDest))
1555 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1556 CNode* pnode = ConnectNode(addrConnect, strDest);
1557 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1563 grantOutbound->MoveTo(pnode->grantOutbound);
1564 pnode->fNetworkNode = true;
1566 pnode->fOneShot = true;
1578 void ThreadMessageHandler(void* parg)
1580 // Make this thread recognisable as the message handling thread
1581 RenameThread("bitcoin-msghand");
1585 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1586 ThreadMessageHandler2(parg);
1587 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1589 catch (std::exception& e) {
1590 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1591 PrintException(&e, "ThreadMessageHandler()");
1593 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1594 PrintException(NULL, "ThreadMessageHandler()");
1596 printf("ThreadMessageHandler exited\n");
1599 void ThreadMessageHandler2(void* parg)
1601 printf("ThreadMessageHandler started\n");
1602 SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1605 vector<CNode*> vNodesCopy;
1608 vNodesCopy = vNodes;
1609 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1613 // Poll the connected nodes for messages
1614 CNode* pnodeTrickle = NULL;
1615 if (!vNodesCopy.empty())
1616 pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1617 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1621 TRY_LOCK(pnode->cs_vRecv, lockRecv);
1623 ProcessMessages(pnode);
1630 TRY_LOCK(pnode->cs_vSend, lockSend);
1632 SendMessages(pnode, pnode == pnodeTrickle);
1640 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1644 // Wait and allow messages to bunch up.
1645 // Reduce vnThreadsRunning so StopNode has permission to exit while
1646 // we're sleeping, but we must always check fShutdown after doing this.
1647 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1649 if (fRequestShutdown)
1651 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1662 bool BindListenPort(const CService &addrBind, string& strError)
1668 // Initialize Windows Sockets
1670 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1671 if (ret != NO_ERROR)
1673 strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
1674 printf("%s\n", strError.c_str());
1679 // Create socket for listening for incoming connections
1681 struct sockaddr_storage sockaddr;
1683 struct sockaddr sockaddr;
1685 socklen_t len = sizeof(sockaddr);
1686 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1688 strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
1689 printf("%s\n", strError.c_str());
1693 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1694 if (hListenSocket == INVALID_SOCKET)
1696 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1697 printf("%s\n", strError.c_str());
1702 // Different way of disabling SIGPIPE on BSD
1703 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1707 // Allow binding if the port is still in TIME_WAIT state after
1708 // the program was closed and restarted. Not an issue on windows.
1709 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1714 // Set to non-blocking, incoming connections will also inherit this
1715 if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1717 if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1720 strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1721 printf("%s\n", strError.c_str());
1726 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1727 // and enable it by default or not. Try to enable it, if possible.
1728 if (addrBind.IsIPv6()) {
1731 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1733 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1737 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
1738 int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
1739 // this call is allowed to fail
1740 setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
1745 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1747 int nErr = WSAGetLastError();
1748 if (nErr == WSAEADDRINUSE)
1749 strError = strprintf(_("Unable to bind to %s on this computer. NovaCoin is probably already running."), addrBind.ToString().c_str());
1751 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
1752 printf("%s\n", strError.c_str());
1755 printf("Bound to %s\n", addrBind.ToString().c_str());
1757 // Listen for incoming connections
1758 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1760 strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1761 printf("%s\n", strError.c_str());
1765 vhListenSocket.push_back(hListenSocket);
1767 if (addrBind.IsRoutable() && fDiscover)
1768 AddLocal(addrBind, LOCAL_BIND);
1773 void static Discover()
1779 // Get local host IP
1780 char pszHostName[1000] = "";
1781 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1783 vector<CNetAddr> vaddr;
1784 if (LookupHost(pszHostName, vaddr))
1786 BOOST_FOREACH (const CNetAddr &addr, vaddr)
1788 AddLocal(addr, LOCAL_IF);
1793 // Get local host ip
1794 struct ifaddrs* myaddrs;
1795 if (getifaddrs(&myaddrs) == 0)
1797 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1799 if (ifa->ifa_addr == NULL) continue;
1800 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1801 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1802 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1803 if (ifa->ifa_addr->sa_family == AF_INET)
1805 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1806 CNetAddr addr(s4->sin_addr);
1807 if (AddLocal(addr, LOCAL_IF))
1808 printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1811 else if (ifa->ifa_addr->sa_family == AF_INET6)
1813 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1814 CNetAddr addr(s6->sin6_addr);
1815 if (AddLocal(addr, LOCAL_IF))
1816 printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1820 freeifaddrs(myaddrs);
1824 // Don't use external IPv4 discovery, when -onlynet="IPv6"
1825 if (!IsLimited(NET_IPV4))
1826 NewThread(ThreadGetMyExternalIP, NULL);
1829 void StartNode(void* parg)
1831 // Make this thread recognisable as the startup thread
1832 RenameThread("bitcoin-start");
1834 if (semOutbound == NULL) {
1835 // initialize semaphore
1836 int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
1837 semOutbound = new CSemaphore(nMaxOutbound);
1840 if (pnodeLocalHost == NULL)
1841 pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1849 if (!GetBoolArg("-dnsseed", true))
1850 printf("DNS seeding disabled\n");
1852 if (!NewThread(ThreadDNSAddressSeed, NULL))
1853 printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
1855 // Map ports with UPnP
1859 // Get addresses from IRC and advertise ours
1860 if (!NewThread(ThreadIRCSeed, NULL))
1861 printf("Error: NewThread(ThreadIRCSeed) failed\n");
1863 // Send and receive from sockets, accept connections
1864 if (!NewThread(ThreadSocketHandler, NULL))
1865 printf("Error: NewThread(ThreadSocketHandler) failed\n");
1867 // Initiate outbound connections from -addnode
1868 if (!NewThread(ThreadOpenAddedConnections, NULL))
1869 printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
1871 // Initiate outbound connections
1872 if (!NewThread(ThreadOpenConnections, NULL))
1873 printf("Error: NewThread(ThreadOpenConnections) failed\n");
1876 if (!NewThread(ThreadMessageHandler, NULL))
1877 printf("Error: NewThread(ThreadMessageHandler) failed\n");
1879 // Dump network addresses
1880 if (!NewThread(ThreadDumpAddress, NULL))
1881 printf("Error; NewThread(ThreadDumpAddress) failed\n");
1883 // ppcoin: mint proof-of-stake blocks in the background
1884 if (!NewThread(ThreadStakeMinter, pwalletMain))
1885 printf("Error: NewThread(ThreadStakeMinter) failed\n");
1890 printf("StopNode()\n");
1892 nTransactionsUpdated++;
1893 int64 nStart = GetTime();
1895 for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1896 semOutbound->post();
1899 int nThreadsRunning = 0;
1900 for (int n = 0; n < THREAD_MAX; n++)
1901 nThreadsRunning += vnThreadsRunning[n];
1902 if (nThreadsRunning == 0)
1904 if (GetTime() - nStart > 20)
1908 if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
1909 if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
1910 if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
1911 if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
1912 if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
1914 if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
1916 if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
1917 if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
1918 if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
1919 if (vnThreadsRunning[THREAD_MINTER] > 0) printf("ThreadStakeMinter still running\n");
1920 while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0)
1936 BOOST_FOREACH(CNode* pnode, vNodes)
1937 if (pnode->hSocket != INVALID_SOCKET)
1938 closesocket(pnode->hSocket);
1939 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
1940 if (hListenSocket != INVALID_SOCKET)
1941 if (closesocket(hListenSocket) == SOCKET_ERROR)
1942 printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
1945 // Shutdown Windows Sockets
1950 instance_of_cnetcleanup;