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 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;
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;
72 static deque<string> vOneShots;
73 CCriticalSection cs_vOneShots;
75 set<CNetAddr> setservAddNodeAddresses;
76 CCriticalSection cs_setservAddNodeAddresses;
78 static CSemaphore *semOutbound = NULL;
80 void AddOneShot(string strDest)
83 vOneShots.push_back(strDest);
86 unsigned short GetListenPort()
88 return (unsigned short)(GetArg("-port", GetDefaultPort()));
91 void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)
93 // Filter out duplicate requests
94 if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)
96 pindexLastGetBlocksBegin = pindexBegin;
97 hashLastGetBlocksEnd = hashEnd;
99 PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);
102 // find 'best' local address for a particular peer
103 bool GetLocal(CService& addr, const CNetAddr *paddrPeer)
109 int nBestReachability = -1;
111 LOCK(cs_mapLocalHost);
112 for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++)
114 int nScore = (*it).second.nScore;
115 int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
116 if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore))
118 addr = CService((*it).first, (*it).second.nPort);
119 nBestReachability = nReachability;
124 return nBestScore >= 0;
127 // get best local address for a particular peer as a CAddress
128 CAddress GetLocalAddress(const CNetAddr *paddrPeer)
130 CAddress ret(CService("0.0.0.0",0),0);
132 if (GetLocal(addr, paddrPeer))
134 ret = CAddress(addr);
135 ret.nServices = nLocalServices;
136 ret.nTime = GetAdjustedTime();
141 bool RecvLine(SOCKET hSocket, string& strLine)
147 int nBytes = recv(hSocket, &c, 1, 0);
155 if (strLine.size() >= 9000)
158 else if (nBytes <= 0)
164 int nErr = WSAGetLastError();
165 if (nErr == WSAEMSGSIZE)
167 if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS)
173 if (!strLine.empty())
178 printf("socket closed\n");
184 int nErr = WSAGetLastError();
185 printf("recv failed: %d\n", nErr);
192 // used when scores of local addresses may have changed
193 // pushes better local address to peers
194 void static AdvertizeLocal()
197 BOOST_FOREACH(CNode* pnode, vNodes)
199 if (pnode->fSuccessfullyConnected)
201 CAddress addrLocal = GetLocalAddress(&pnode->addr);
202 if (addrLocal.IsRoutable() && (CService)addrLocal != (CService)pnode->addrLocal)
204 pnode->PushAddress(addrLocal);
205 pnode->addrLocal = addrLocal;
211 void SetReachable(enum Network net, bool fFlag)
213 LOCK(cs_mapLocalHost);
214 vfReachable[net] = fFlag;
215 if (net == NET_IPV6 && fFlag)
216 vfReachable[NET_IPV4] = true;
219 // learn a new local address
220 bool AddLocal(const CService& addr, int nScore)
222 if (!addr.IsRoutable())
225 if (!fDiscover && nScore < LOCAL_MANUAL)
231 printf("AddLocal(%s,%i)\n", addr.ToString().c_str(), nScore);
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();
241 SetReachable(addr.GetNetwork());
249 bool AddLocal(const CNetAddr &addr, int nScore)
251 return AddLocal(CService(addr, GetListenPort()), nScore);
254 /** Make a particular network entirely off-limits (no automatic connects to it) */
255 void SetLimited(enum Network net, bool fLimited)
257 if (net == NET_UNROUTABLE)
259 LOCK(cs_mapLocalHost);
260 vfLimited[net] = fLimited;
263 bool IsLimited(enum Network net)
265 LOCK(cs_mapLocalHost);
266 return vfLimited[net];
269 bool IsLimited(const CNetAddr &addr)
271 return IsLimited(addr.GetNetwork());
274 /** vote for a local address */
275 bool SeenLocal(const CService& addr)
278 LOCK(cs_mapLocalHost);
279 if (mapLocalHost.count(addr) == 0)
281 mapLocalHost[addr].nScore++;
289 /** check whether a given address is potentially local */
290 bool IsLocal(const CService& addr)
292 LOCK(cs_mapLocalHost);
293 return mapLocalHost.count(addr) > 0;
296 /** check whether a given address is in a network we can probably connect to */
297 bool IsReachable(const CNetAddr& addr)
299 LOCK(cs_mapLocalHost);
300 enum Network net = addr.GetNetwork();
301 return vfReachable[net] && !vfLimited[net];
304 bool GetMyExternalIP2(const CService& addrConnect, const char* pszGet, const char* pszKeyword, CNetAddr& ipRet)
307 if (!ConnectSocket(addrConnect, hSocket))
308 return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());
310 send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);
313 while (RecvLine(hSocket, strLine))
315 if (strLine.empty()) // HTTP response is separated from headers by blank line
319 if (!RecvLine(hSocket, strLine))
321 closesocket(hSocket);
324 if (pszKeyword == NULL)
326 if (strLine.find(pszKeyword) != string::npos)
328 strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));
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())
346 closesocket(hSocket);
347 return error("GetMyExternalIP() : connection closed");
350 // We now get our external IP from the IRC server first and only use this as a backup
351 bool GetMyExternalIP(CNetAddr& ipRet)
353 CService addrConnect;
355 const char* pszKeyword;
357 for (int nLookup = 0; nLookup <= 1; nLookup++)
358 for (int nHost = 1; nHost <= 2; nHost++)
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"]; ?>
366 addrConnect = CService("91.198.22.70",80); // checkip.dyndns.org
370 CService addrIP("checkip.dyndns.org", 80, true);
371 if (addrIP.IsValid())
372 addrConnect = addrIP;
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"
381 pszKeyword = "Address:";
385 addrConnect = CService("74.208.43.192", 80); // www.showmyip.com
389 CService addrIP("www.showmyip.com", 80, true);
390 if (addrIP.IsValid())
391 addrConnect = addrIP;
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"
400 pszKeyword = NULL; // Returns just IP address
403 if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))
410 void ThreadGetMyExternalIP(void* parg)
412 // Make this thread recognisable as the external IP detection thread
413 RenameThread("novacoin-ext-ip");
415 CNetAddr addrLocalHost;
416 if (GetMyExternalIP(addrLocalHost))
418 printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());
419 AddLocal(addrLocalHost, LOCAL_HTTP);
427 void AddressCurrentlyConnected(const CService& addr)
429 addrman.Connected(addr);
438 CNode* FindNode(const CNetAddr& ip)
442 BOOST_FOREACH(CNode* pnode, vNodes)
443 if ((CNetAddr)pnode->addr == ip)
449 CNode* FindNode(std::string addrName)
452 BOOST_FOREACH(CNode* pnode, vNodes)
453 if (pnode->addrName == addrName)
458 CNode* FindNode(const CService& addr)
462 BOOST_FOREACH(CNode* pnode, vNodes)
463 if ((CService)pnode->addr == addr)
469 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
471 if (pszDest == NULL) {
472 if (IsLocal(addrConnect))
475 // Look for an existing connection
476 CNode* pnode = FindNode((CService)addrConnect);
480 pnode->AddRef(nTimeout);
489 printf("trying connection %s lastseen=%.1fhrs\n",
490 pszDest ? pszDest : addrConnect.ToString().c_str(),
491 pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
495 if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
497 addrman.Attempt(addrConnect);
500 printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
502 // Set to non-blocking
505 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
506 printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
508 if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
509 printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
513 CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
515 pnode->AddRef(nTimeout);
521 vNodes.push_back(pnode);
524 pnode->nTimeConnected = GetTime();
533 void CNode::CloseSocketDisconnect()
536 if (hSocket != INVALID_SOCKET)
538 printf("disconnecting node %s\n", addrName.c_str());
539 closesocket(hSocket);
540 hSocket = INVALID_SOCKET;
544 // in case this fails, we'll empty the recv buffer when the CNode is deleted
545 TRY_LOCK(cs_vRecv, lockRecv);
549 // if this was the sync node, we'll need a new one
550 if (this == pnodeSync)
554 void CNode::Cleanup()
559 void CNode::PushVersion()
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);
575 std::map<CNetAddr, int64> CNode::setBanned;
576 CCriticalSection CNode::cs_setBanned;
578 void CNode::ClearBanned()
583 bool CNode::IsBanned(CNetAddr ip)
585 bool fResult = false;
588 std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
589 if (i != setBanned.end())
591 int64 t = (*i).second;
599 bool CNode::Misbehaving(int howmuch)
603 printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
607 nMisbehavior += howmuch;
608 if (nMisbehavior >= GetArg("-banscore", 100))
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);
614 if (setBanned[addr] < banTime)
615 setBanned[addr] = banTime;
617 CloseSocketDisconnect();
620 printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
625 #define X(name) stats.name = name
626 void CNode::copyStats(CNodeStats &stats)
641 stats.fSyncNode = (this == pnodeSync);
654 void ThreadSocketHandler(void* parg)
656 // Make this thread recognisable as the networking thread
657 RenameThread("novacoin-net");
661 vnThreadsRunning[THREAD_SOCKETHANDLER]++;
662 ThreadSocketHandler2(parg);
663 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
665 catch (std::exception& e) {
666 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
667 PrintException(&e, "ThreadSocketHandler()");
669 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
670 throw; // support pthread_cancel()
672 printf("ThreadSocketHandler exited\n");
675 void ThreadSocketHandler2(void* parg)
677 printf("ThreadSocketHandler started\n");
678 list<CNode*> vNodesDisconnected;
679 unsigned int nPrevNodeCount = 0;
688 // Disconnect unused nodes
689 vector<CNode*> vNodesCopy = vNodes;
690 BOOST_FOREACH(CNode* pnode, vNodesCopy)
692 if (pnode->fDisconnect ||
693 (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
695 // remove from vNodes
696 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
698 // release outbound grant (if any)
699 pnode->grantOutbound.Release();
701 // close socket and cleanup
702 pnode->CloseSocketDisconnect();
705 // hold in disconnected pool until all refs are released
706 pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
707 if (pnode->fNetworkNode || pnode->fInbound)
709 vNodesDisconnected.push_back(pnode);
713 // Delete disconnected nodes
714 list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
715 BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
717 // wait until threads are done using it
718 if (pnode->GetRefCount() <= 0)
720 bool fDelete = false;
722 TRY_LOCK(pnode->cs_vSend, lockSend);
725 TRY_LOCK(pnode->cs_vRecv, lockRecv);
728 TRY_LOCK(pnode->cs_mapRequests, lockReq);
731 TRY_LOCK(pnode->cs_inventory, lockInv);
740 vNodesDisconnected.remove(pnode);
746 if (vNodes.size() != nPrevNodeCount)
748 nPrevNodeCount = vNodes.size();
749 uiInterface.NotifyNumConnectionsChanged(vNodes.size());
754 // Find which sockets have data to receive
756 struct timeval timeout;
758 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
765 FD_ZERO(&fdsetError);
766 SOCKET hSocketMax = 0;
767 bool have_fds = false;
769 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
770 FD_SET(hListenSocket, &fdsetRecv);
771 hSocketMax = max(hSocketMax, hListenSocket);
776 BOOST_FOREACH(CNode* pnode, vNodes)
778 if (pnode->hSocket == INVALID_SOCKET)
780 FD_SET(pnode->hSocket, &fdsetRecv);
781 FD_SET(pnode->hSocket, &fdsetError);
782 hSocketMax = max(hSocketMax, pnode->hSocket);
785 TRY_LOCK(pnode->cs_vSend, lockSend);
786 if (lockSend && !pnode->vSend.empty())
787 FD_SET(pnode->hSocket, &fdsetSend);
792 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
793 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
794 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
795 vnThreadsRunning[THREAD_SOCKETHANDLER]++;
798 if (nSelect == SOCKET_ERROR)
802 int nErr = WSAGetLastError();
803 printf("socket select error %d\n", nErr);
804 for (unsigned int i = 0; i <= hSocketMax; i++)
805 FD_SET(i, &fdsetRecv);
808 FD_ZERO(&fdsetError);
809 Sleep(timeout.tv_usec/1000);
814 // Accept new connections
816 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
817 if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
820 struct sockaddr_storage sockaddr;
822 struct sockaddr sockaddr;
824 socklen_t len = sizeof(sockaddr);
825 SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
829 if (hSocket != INVALID_SOCKET)
830 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
831 printf("Warning: Unknown socket family\n");
835 BOOST_FOREACH(CNode* pnode, vNodes)
840 if (hSocket == INVALID_SOCKET)
842 int nErr = WSAGetLastError();
843 if (nErr != WSAEWOULDBLOCK)
844 printf("socket error accept failed: %d\n", nErr);
846 else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
849 LOCK(cs_setservAddNodeAddresses);
850 if (!setservAddNodeAddresses.count(addr))
851 closesocket(hSocket);
854 else if (CNode::IsBanned(addr))
856 printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
857 closesocket(hSocket);
861 printf("accepted connection %s\n", addr.ToString().c_str());
862 CNode* pnode = new CNode(hSocket, addr, "", true);
866 vNodes.push_back(pnode);
873 // Service each socket
875 vector<CNode*> vNodesCopy;
879 BOOST_FOREACH(CNode* pnode, vNodesCopy)
882 BOOST_FOREACH(CNode* pnode, vNodesCopy)
890 if (pnode->hSocket == INVALID_SOCKET)
892 if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
894 TRY_LOCK(pnode->cs_vRecv, lockRecv);
897 CDataStream& vRecv = pnode->vRecv;
898 unsigned int nPos = vRecv.size();
900 if (nPos > ReceiveBufferSize()) {
901 if (!pnode->fDisconnect)
902 printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
903 pnode->CloseSocketDisconnect();
906 // typical socket buffer is 8K-64K
907 char pchBuf[0x10000];
908 int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
911 vRecv.resize(nPos + nBytes);
912 memcpy(&vRecv[nPos], pchBuf, nBytes);
913 pnode->nLastRecv = GetTime();
914 pnode->nRecvBytes += nBytes;
916 else if (nBytes == 0)
918 // socket closed gracefully
919 if (!pnode->fDisconnect)
920 printf("socket closed\n");
921 pnode->CloseSocketDisconnect();
926 int nErr = WSAGetLastError();
927 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
929 if (!pnode->fDisconnect)
930 printf("socket recv error %d\n", nErr);
931 pnode->CloseSocketDisconnect();
941 if (pnode->hSocket == INVALID_SOCKET)
943 if (FD_ISSET(pnode->hSocket, &fdsetSend))
945 TRY_LOCK(pnode->cs_vSend, lockSend);
948 CDataStream& vSend = pnode->vSend;
951 int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
954 vSend.erase(vSend.begin(), vSend.begin() + nBytes);
955 pnode->nLastSend = GetTime();
956 pnode->nSendBytes += nBytes;
961 int nErr = WSAGetLastError();
962 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
964 printf("socket send error %d\n", nErr);
965 pnode->CloseSocketDisconnect();
973 // Inactivity checking
975 if (pnode->vSend.empty())
976 pnode->nLastSendEmpty = GetTime();
977 if (GetTime() - pnode->nTimeConnected > 60)
979 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
981 printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
982 pnode->fDisconnect = true;
984 else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
986 printf("socket not sending\n");
987 pnode->fDisconnect = true;
989 else if (GetTime() - pnode->nLastRecv > 90*60)
991 printf("socket inactivity timeout\n");
992 pnode->fDisconnect = true;
998 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1015 void ThreadMapPort(void* parg)
1017 // Make this thread recognisable as the UPnP thread
1018 RenameThread("novacoin-UPnP");
1022 vnThreadsRunning[THREAD_UPNP]++;
1023 ThreadMapPort2(parg);
1024 vnThreadsRunning[THREAD_UPNP]--;
1026 catch (std::exception& e) {
1027 vnThreadsRunning[THREAD_UPNP]--;
1028 PrintException(&e, "ThreadMapPort()");
1030 vnThreadsRunning[THREAD_UPNP]--;
1031 PrintException(NULL, "ThreadMapPort()");
1033 printf("ThreadMapPort exited\n");
1036 void ThreadMapPort2(void* parg)
1038 printf("ThreadMapPort started\n");
1040 std::string port = strprintf("%u", GetListenPort());
1041 const char * multicastif = 0;
1042 const char * minissdpdpath = 0;
1043 struct UPNPDev * devlist = 0;
1046 #ifndef UPNPDISCOVER_SUCCESS
1048 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1052 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1055 struct UPNPUrls urls;
1056 struct IGDdatas data;
1059 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1063 char externalIPAddress[40];
1064 r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1065 if(r != UPNPCOMMAND_SUCCESS)
1066 printf("UPnP: GetExternalIPAddress() returned %d\n", r);
1069 if(externalIPAddress[0])
1071 printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
1072 AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
1075 printf("UPnP: GetExternalIPAddress failed.\n");
1079 string strDesc = "NovaCoin " + FormatFullVersion();
1080 #ifndef UPNPDISCOVER_SUCCESS
1082 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1083 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1086 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1087 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1090 if(r!=UPNPCOMMAND_SUCCESS)
1091 printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1092 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1094 printf("UPnP Port Mapping successful.\n");
1098 if (fShutdown || !fUseUPnP)
1100 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1101 printf("UPNP_DeletePortMapping() returned : %d\n", r);
1102 freeUPNPDevlist(devlist); devlist = 0;
1103 FreeUPNPUrls(&urls);
1106 if (i % 600 == 0) // Refresh every 20 minutes
1108 #ifndef UPNPDISCOVER_SUCCESS
1110 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1111 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1114 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1115 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1118 if(r!=UPNPCOMMAND_SUCCESS)
1119 printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1120 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1122 printf("UPnP Port Mapping successful.\n");;
1128 printf("No valid UPnP IGDs found\n");
1129 freeUPNPDevlist(devlist); devlist = 0;
1131 FreeUPNPUrls(&urls);
1134 if (fShutdown || !fUseUPnP)
1143 if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
1145 if (!NewThread(ThreadMapPort, NULL))
1146 printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
1152 // Intentionally left blank.
1165 // Each pair gives a source name and a seed name.
1166 // The first name is used as information source for addrman.
1167 // The second name should resolve to a list of seed addresses.
1168 static const char *strDNSSeed[][2] = {
1169 {"novacoin.su", "dnsseed.novacoin.su"},
1170 {"novacoin.ru", "dnsseed.novacoin.ru"},
1171 {"novaco.in", "dnsseed.novaco.in"},
1174 void ThreadDNSAddressSeed(void* parg)
1176 // Make this thread recognisable as the DNS seeding thread
1177 RenameThread("novacoin-dnsseed");
1181 vnThreadsRunning[THREAD_DNSSEED]++;
1182 ThreadDNSAddressSeed2(parg);
1183 vnThreadsRunning[THREAD_DNSSEED]--;
1185 catch (std::exception& e) {
1186 vnThreadsRunning[THREAD_DNSSEED]--;
1187 PrintException(&e, "ThreadDNSAddressSeed()");
1189 vnThreadsRunning[THREAD_DNSSEED]--;
1190 throw; // support pthread_cancel()
1192 printf("ThreadDNSAddressSeed exited\n");
1195 void ThreadDNSAddressSeed2(void* parg)
1197 printf("ThreadDNSAddressSeed started\n");
1202 printf("Loading addresses from DNS seeds (could take a while)\n");
1204 for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
1205 if (HaveNameProxy()) {
1206 AddOneShot(strDNSSeed[seed_idx][1]);
1208 vector<CNetAddr> vaddr;
1209 vector<CAddress> vAdd;
1210 if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
1212 BOOST_FOREACH(CNetAddr& ip, vaddr)
1214 int nOneDay = 24*3600;
1215 CAddress addr = CAddress(CService(ip, GetDefaultPort()));
1216 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1217 vAdd.push_back(addr);
1221 addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
1226 printf("%d addresses found from DNS seeds\n", found);
1240 unsigned int pnSeed[] =
1242 0x90EF78BC, 0x33F1C851, 0x36F1C851, 0xC6F5C851,
1245 void DumpAddresses()
1247 int64 nStart = GetTimeMillis();
1252 printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
1253 addrman.size(), GetTimeMillis() - nStart);
1256 void ThreadDumpAddress2(void* parg)
1258 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1262 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1264 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1266 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1269 void ThreadDumpAddress(void* parg)
1271 // Make this thread recognisable as the address dumping thread
1272 RenameThread("novacoin-adrdump");
1276 ThreadDumpAddress2(parg);
1278 catch (std::exception& e) {
1279 PrintException(&e, "ThreadDumpAddress()");
1281 printf("ThreadDumpAddress exited\n");
1284 void ThreadOpenConnections(void* parg)
1286 // Make this thread recognisable as the connection opening thread
1287 RenameThread("novacoin-opencon");
1291 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1292 ThreadOpenConnections2(parg);
1293 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1295 catch (std::exception& e) {
1296 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1297 PrintException(&e, "ThreadOpenConnections()");
1299 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1300 PrintException(NULL, "ThreadOpenConnections()");
1302 printf("ThreadOpenConnections exited\n");
1305 void static ProcessOneShot()
1310 if (vOneShots.empty())
1312 strDest = vOneShots.front();
1313 vOneShots.pop_front();
1316 CSemaphoreGrant grant(*semOutbound, true);
1318 if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1319 AddOneShot(strDest);
1323 // ppcoin: stake minter thread
1324 void static ThreadStakeMinter(void* parg)
1326 printf("ThreadStakeMinter started\n");
1327 CWallet* pwallet = (CWallet*)parg;
1330 vnThreadsRunning[THREAD_MINTER]++;
1331 StakeMiner(pwallet);
1332 vnThreadsRunning[THREAD_MINTER]--;
1334 catch (std::exception& e) {
1335 vnThreadsRunning[THREAD_MINTER]--;
1336 PrintException(&e, "ThreadStakeMinter()");
1338 vnThreadsRunning[THREAD_MINTER]--;
1339 PrintException(NULL, "ThreadStakeMinter()");
1341 printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
1344 void ThreadOpenConnections2(void* parg)
1346 printf("ThreadOpenConnections started\n");
1348 // Connect to specific addresses
1349 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1351 for (int64 nLoop = 0;; nLoop++)
1354 BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1357 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1358 for (int i = 0; i < 10 && i < nLoop; i++)
1369 // Initiate network connections
1370 int64 nStart = GetTime();
1375 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1377 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1382 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1383 CSemaphoreGrant grant(*semOutbound);
1384 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1388 // Add seed nodes if IRC isn't working
1389 if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
1391 std::vector<CAddress> vAdd;
1392 for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
1394 // It'll only connect to one or two seed nodes because once it connects,
1395 // it'll get a pile of addresses with newer timestamps.
1396 // Seed nodes are given a random 'last seen time' of between one and two
1398 const int64 nOneWeek = 7*24*60*60;
1400 memcpy(&ip, &pnSeed[i], sizeof(ip));
1401 CAddress addr(CService(ip, GetDefaultPort()));
1402 addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
1403 vAdd.push_back(addr);
1405 addrman.Add(vAdd, CNetAddr("127.0.0.1"));
1409 // Choose an address to connect to based on most recently seen
1411 CAddress addrConnect;
1413 // Only connect out to one peer per network group (/16 for IPv4).
1414 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1416 set<vector<unsigned char> > setConnected;
1419 BOOST_FOREACH(CNode* pnode, vNodes) {
1420 if (!pnode->fInbound) {
1421 setConnected.insert(pnode->addr.GetGroup());
1427 int64 nANow = GetAdjustedTime();
1432 // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
1433 CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
1435 // if we selected an invalid address, restart
1436 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1439 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1440 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1441 // already-connected network ranges, ...) before trying new addrman addresses.
1446 if (IsLimited(addr))
1449 // only consider very recently tried nodes after 30 failed attempts
1450 if (nANow - addr.nLastTry < 600 && nTries < 30)
1453 // do not allow non-default ports, unless after 50 invalid addresses selected already
1454 if (addr.GetPort() != GetDefaultPort() && nTries < 50)
1461 if (addrConnect.IsValid())
1462 OpenNetworkConnection(addrConnect, &grant);
1466 void ThreadOpenAddedConnections(void* parg)
1468 // Make this thread recognisable as the connection opening thread
1469 RenameThread("novacoin-opencon");
1473 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1474 ThreadOpenAddedConnections2(parg);
1475 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1477 catch (std::exception& e) {
1478 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1479 PrintException(&e, "ThreadOpenAddedConnections()");
1481 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1482 PrintException(NULL, "ThreadOpenAddedConnections()");
1484 printf("ThreadOpenAddedConnections exited\n");
1487 void ThreadOpenAddedConnections2(void* parg)
1489 printf("ThreadOpenAddedConnections started\n");
1491 if (mapArgs.count("-addnode") == 0)
1494 if (HaveNameProxy()) {
1496 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
1498 CSemaphoreGrant grant(*semOutbound);
1499 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1502 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1503 Sleep(120000); // Retry every 2 minutes
1504 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1509 vector<vector<CService> > vservAddressesToAdd(0);
1510 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
1512 vector<CService> vservNode(0);
1513 if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
1515 vservAddressesToAdd.push_back(vservNode);
1517 LOCK(cs_setservAddNodeAddresses);
1518 BOOST_FOREACH(CService& serv, vservNode)
1519 setservAddNodeAddresses.insert(serv);
1525 vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
1526 // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1527 // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1530 BOOST_FOREACH(CNode* pnode, vNodes)
1531 for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
1532 BOOST_FOREACH(CService& addrNode, *(it))
1533 if (pnode->addr == addrNode)
1535 it = vservConnectAddresses.erase(it);
1540 BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
1542 CSemaphoreGrant grant(*semOutbound);
1543 OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
1550 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1551 Sleep(120000); // Retry every 2 minutes
1552 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1558 // if successful, this moves the passed grant to the constructed node
1559 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
1562 // Initiate outbound network connection
1567 if (IsLocal(addrConnect) ||
1568 FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1569 FindNode(addrConnect.ToStringIPPort().c_str()))
1571 if (strDest && FindNode(strDest))
1574 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1575 CNode* pnode = ConnectNode(addrConnect, strDest);
1576 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1582 grantOutbound->MoveTo(pnode->grantOutbound);
1583 pnode->fNetworkNode = true;
1585 pnode->fOneShot = true;
1590 // for now, use a very simple selection metric: the node from which we received
1592 double static NodeSyncScore(const CNode *pnode) {
1593 return -pnode->nLastRecv;
1596 void static StartSync(const vector<CNode*> &vNodes) {
1597 CNode *pnodeNewSync = NULL;
1598 double dBestScore = 0;
1600 // Iterate over all nodes
1601 BOOST_FOREACH(CNode* pnode, vNodes) {
1602 // check preconditions for allowing a sync
1603 if (!pnode->fClient && !pnode->fOneShot &&
1604 !pnode->fDisconnect && pnode->fSuccessfullyConnected &&
1605 (pnode->nStartingHeight > (nBestHeight - 144)) &&
1606 (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
1607 // if ok, compare node's score with the best so far
1608 double dScore = NodeSyncScore(pnode);
1609 if (pnodeNewSync == NULL || dScore > dBestScore) {
1610 pnodeNewSync = pnode;
1611 dBestScore = dScore;
1615 // if a new sync candidate was found, start sync!
1617 pnodeNewSync->fStartSync = true;
1618 pnodeSync = pnodeNewSync;
1622 void ThreadMessageHandler(void* parg)
1624 // Make this thread recognisable as the message handling thread
1625 RenameThread("novacoin-msghand");
1629 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1630 ThreadMessageHandler2(parg);
1631 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1633 catch (std::exception& e) {
1634 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1635 PrintException(&e, "ThreadMessageHandler()");
1637 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1638 PrintException(NULL, "ThreadMessageHandler()");
1640 printf("ThreadMessageHandler exited\n");
1643 void ThreadMessageHandler2(void* parg)
1645 printf("ThreadMessageHandler started\n");
1646 SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1649 bool fHaveSyncNode = false;
1650 vector<CNode*> vNodesCopy;
1653 vNodesCopy = vNodes;
1654 BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1656 if (pnode == pnodeSync)
1657 fHaveSyncNode = true;
1662 StartSync(vNodesCopy);
1664 // Poll the connected nodes for messages
1665 CNode* pnodeTrickle = NULL;
1666 if (!vNodesCopy.empty())
1667 pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1668 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1672 TRY_LOCK(pnode->cs_vRecv, lockRecv);
1674 ProcessMessages(pnode);
1681 TRY_LOCK(pnode->cs_vSend, lockSend);
1683 SendMessages(pnode, pnode == pnodeTrickle);
1691 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1695 // Wait and allow messages to bunch up.
1696 // Reduce vnThreadsRunning so StopNode has permission to exit while
1697 // we're sleeping, but we must always check fShutdown after doing this.
1698 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1700 if (fRequestShutdown)
1702 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1713 bool BindListenPort(const CService &addrBind, string& strError)
1719 // Initialize Windows Sockets
1721 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1722 if (ret != NO_ERROR)
1724 strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
1725 printf("%s\n", strError.c_str());
1730 // Create socket for listening for incoming connections
1732 struct sockaddr_storage sockaddr;
1734 struct sockaddr sockaddr;
1736 socklen_t len = sizeof(sockaddr);
1737 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1739 strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
1740 printf("%s\n", strError.c_str());
1744 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1745 if (hListenSocket == INVALID_SOCKET)
1747 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1748 printf("%s\n", strError.c_str());
1753 // Different way of disabling SIGPIPE on BSD
1754 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1758 // Allow binding if the port is still in TIME_WAIT state after
1759 // the program was closed and restarted. Not an issue on windows.
1760 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1765 // Set to non-blocking, incoming connections will also inherit this
1766 if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1768 if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1771 strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1772 printf("%s\n", strError.c_str());
1777 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1778 // and enable it by default or not. Try to enable it, if possible.
1779 if (addrBind.IsIPv6()) {
1782 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1784 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1788 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
1789 int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
1790 // this call is allowed to fail
1791 setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
1796 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1798 int nErr = WSAGetLastError();
1799 if (nErr == WSAEADDRINUSE)
1800 strError = strprintf(_("Unable to bind to %s on this computer. NovaCoin is probably already running."), addrBind.ToString().c_str());
1802 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
1803 printf("%s\n", strError.c_str());
1806 printf("Bound to %s\n", addrBind.ToString().c_str());
1808 // Listen for incoming connections
1809 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1811 strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1812 printf("%s\n", strError.c_str());
1816 vhListenSocket.push_back(hListenSocket);
1818 if (addrBind.IsRoutable() && fDiscover)
1819 AddLocal(addrBind, LOCAL_BIND);
1824 void static Discover()
1830 // Get local host IP
1831 char pszHostName[1000] = "";
1832 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1834 vector<CNetAddr> vaddr;
1835 if (LookupHost(pszHostName, vaddr))
1837 BOOST_FOREACH (const CNetAddr &addr, vaddr)
1839 AddLocal(addr, LOCAL_IF);
1844 // Get local host ip
1845 struct ifaddrs* myaddrs;
1846 if (getifaddrs(&myaddrs) == 0)
1848 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1850 if (ifa->ifa_addr == NULL) continue;
1851 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1852 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1853 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1854 if (ifa->ifa_addr->sa_family == AF_INET)
1856 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1857 CNetAddr addr(s4->sin_addr);
1858 if (AddLocal(addr, LOCAL_IF))
1859 printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1862 else if (ifa->ifa_addr->sa_family == AF_INET6)
1864 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1865 CNetAddr addr(s6->sin6_addr);
1866 if (AddLocal(addr, LOCAL_IF))
1867 printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1871 freeifaddrs(myaddrs);
1875 // Don't use external IPv4 discovery, when -onlynet="IPv6"
1876 if (!IsLimited(NET_IPV4))
1877 NewThread(ThreadGetMyExternalIP, NULL);
1880 void StartNode(void* parg)
1882 // Make this thread recognisable as the startup thread
1883 RenameThread("novacoin-start");
1885 if (semOutbound == NULL) {
1886 // initialize semaphore
1887 int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
1888 semOutbound = new CSemaphore(nMaxOutbound);
1891 if (pnodeLocalHost == NULL)
1892 pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1900 if (!GetBoolArg("-dnsseed", true))
1901 printf("DNS seeding disabled\n");
1903 if (!NewThread(ThreadDNSAddressSeed, NULL))
1904 printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
1906 // Map ports with UPnP
1910 // Get addresses from IRC and advertise ours
1911 if (!NewThread(ThreadIRCSeed, NULL))
1912 printf("Error: NewThread(ThreadIRCSeed) failed\n");
1914 // Send and receive from sockets, accept connections
1915 if (!NewThread(ThreadSocketHandler, NULL))
1916 printf("Error: NewThread(ThreadSocketHandler) failed\n");
1918 // Initiate outbound connections from -addnode
1919 if (!NewThread(ThreadOpenAddedConnections, NULL))
1920 printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
1922 // Initiate outbound connections
1923 if (!NewThread(ThreadOpenConnections, NULL))
1924 printf("Error: NewThread(ThreadOpenConnections) failed\n");
1927 if (!NewThread(ThreadMessageHandler, NULL))
1928 printf("Error: NewThread(ThreadMessageHandler) failed\n");
1930 // Dump network addresses
1931 if (!NewThread(ThreadDumpAddress, NULL))
1932 printf("Error; NewThread(ThreadDumpAddress) failed\n");
1934 // ppcoin: mint proof-of-stake blocks in the background
1935 if (!NewThread(ThreadStakeMinter, pwalletMain))
1936 printf("Error: NewThread(ThreadStakeMinter) failed\n");
1941 printf("StopNode()\n");
1943 nTransactionsUpdated++;
1944 int64 nStart = GetTime();
1947 ThreadScriptCheckQuit();
1950 for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1951 semOutbound->post();
1954 int nThreadsRunning = 0;
1955 for (int n = 0; n < THREAD_MAX; n++)
1956 nThreadsRunning += vnThreadsRunning[n];
1957 if (nThreadsRunning == 0)
1959 if (GetTime() - nStart > 20)
1963 if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
1964 if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
1965 if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
1966 if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
1967 if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
1969 if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
1971 if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
1972 if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
1973 if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
1974 if (vnThreadsRunning[THREAD_MINTER] > 0) printf("ThreadStakeMinter still running\n");
1975 if (vnThreadsRunning[THREAD_SCRIPTCHECK] > 0) printf("ThreadScriptCheck still running\n");
1976 while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0 || vnThreadsRunning[THREAD_SCRIPTCHECK] > 0)
1992 BOOST_FOREACH(CNode* pnode, vNodes)
1993 if (pnode->hSocket != INVALID_SOCKET)
1994 closesocket(pnode->hSocket);
1995 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
1996 if (hListenSocket != INVALID_SOCKET)
1997 if (closesocket(hListenSocket) == SOCKET_ERROR)
1998 printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
2001 // Shutdown Windows Sockets
2006 instance_of_cnetcleanup;
2008 void RelayTransaction(const CTransaction& tx, const uint256& hash)
2010 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
2013 RelayTransaction(tx, hash, ss);
2016 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
2018 CInv inv(MSG_TX, hash);
2021 // Expire old relay messages
2022 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
2024 mapRelay.erase(vRelayExpiration.front().second);
2025 vRelayExpiration.pop_front();
2028 // Save original serialized message so newer versions are preserved
2029 mapRelay.insert(std::make_pair(inv, ss));
2030 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
2033 RelayInventory(inv);