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)
651 void ThreadSocketHandler(void* parg)
653 // Make this thread recognisable as the networking thread
654 RenameThread("novacoin-net");
658 vnThreadsRunning[THREAD_SOCKETHANDLER]++;
659 ThreadSocketHandler2(parg);
660 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
662 catch (std::exception& e) {
663 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
664 PrintException(&e, "ThreadSocketHandler()");
666 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
667 throw; // support pthread_cancel()
669 printf("ThreadSocketHandler exited\n");
672 void ThreadSocketHandler2(void* parg)
674 printf("ThreadSocketHandler started\n");
675 list<CNode*> vNodesDisconnected;
676 unsigned int nPrevNodeCount = 0;
685 // Disconnect unused nodes
686 vector<CNode*> vNodesCopy = vNodes;
687 BOOST_FOREACH(CNode* pnode, vNodesCopy)
689 if (pnode->fDisconnect ||
690 (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
692 // remove from vNodes
693 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
695 // release outbound grant (if any)
696 pnode->grantOutbound.Release();
698 // close socket and cleanup
699 pnode->CloseSocketDisconnect();
702 // hold in disconnected pool until all refs are released
703 pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
704 if (pnode->fNetworkNode || pnode->fInbound)
706 vNodesDisconnected.push_back(pnode);
710 // Delete disconnected nodes
711 list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
712 BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
714 // wait until threads are done using it
715 if (pnode->GetRefCount() <= 0)
717 bool fDelete = false;
719 TRY_LOCK(pnode->cs_vSend, lockSend);
722 TRY_LOCK(pnode->cs_vRecv, lockRecv);
725 TRY_LOCK(pnode->cs_mapRequests, lockReq);
728 TRY_LOCK(pnode->cs_inventory, lockInv);
737 vNodesDisconnected.remove(pnode);
743 if (vNodes.size() != nPrevNodeCount)
745 nPrevNodeCount = vNodes.size();
746 uiInterface.NotifyNumConnectionsChanged(vNodes.size());
751 // Find which sockets have data to receive
753 struct timeval timeout;
755 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
762 FD_ZERO(&fdsetError);
763 SOCKET hSocketMax = 0;
764 bool have_fds = false;
766 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
767 FD_SET(hListenSocket, &fdsetRecv);
768 hSocketMax = max(hSocketMax, hListenSocket);
773 BOOST_FOREACH(CNode* pnode, vNodes)
775 if (pnode->hSocket == INVALID_SOCKET)
777 FD_SET(pnode->hSocket, &fdsetRecv);
778 FD_SET(pnode->hSocket, &fdsetError);
779 hSocketMax = max(hSocketMax, pnode->hSocket);
782 TRY_LOCK(pnode->cs_vSend, lockSend);
783 if (lockSend && !pnode->vSend.empty())
784 FD_SET(pnode->hSocket, &fdsetSend);
789 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
790 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
791 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
792 vnThreadsRunning[THREAD_SOCKETHANDLER]++;
795 if (nSelect == SOCKET_ERROR)
799 int nErr = WSAGetLastError();
800 printf("socket select error %d\n", nErr);
801 for (unsigned int i = 0; i <= hSocketMax; i++)
802 FD_SET(i, &fdsetRecv);
805 FD_ZERO(&fdsetError);
806 Sleep(timeout.tv_usec/1000);
811 // Accept new connections
813 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
814 if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
817 struct sockaddr_storage sockaddr;
819 struct sockaddr sockaddr;
821 socklen_t len = sizeof(sockaddr);
822 SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
826 if (hSocket != INVALID_SOCKET)
827 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
828 printf("Warning: Unknown socket family\n");
832 BOOST_FOREACH(CNode* pnode, vNodes)
837 if (hSocket == INVALID_SOCKET)
839 int nErr = WSAGetLastError();
840 if (nErr != WSAEWOULDBLOCK)
841 printf("socket error accept failed: %d\n", nErr);
843 else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
846 LOCK(cs_setservAddNodeAddresses);
847 if (!setservAddNodeAddresses.count(addr))
848 closesocket(hSocket);
851 else if (CNode::IsBanned(addr))
853 printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
854 closesocket(hSocket);
858 printf("accepted connection %s\n", addr.ToString().c_str());
859 CNode* pnode = new CNode(hSocket, addr, "", true);
863 vNodes.push_back(pnode);
870 // Service each socket
872 vector<CNode*> vNodesCopy;
876 BOOST_FOREACH(CNode* pnode, vNodesCopy)
879 BOOST_FOREACH(CNode* pnode, vNodesCopy)
887 if (pnode->hSocket == INVALID_SOCKET)
889 if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
891 TRY_LOCK(pnode->cs_vRecv, lockRecv);
894 CDataStream& vRecv = pnode->vRecv;
895 unsigned int nPos = vRecv.size();
897 if (nPos > ReceiveBufferSize()) {
898 if (!pnode->fDisconnect)
899 printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
900 pnode->CloseSocketDisconnect();
903 // typical socket buffer is 8K-64K
904 char pchBuf[0x10000];
905 int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
908 vRecv.resize(nPos + nBytes);
909 memcpy(&vRecv[nPos], pchBuf, nBytes);
910 pnode->nLastRecv = GetTime();
912 else if (nBytes == 0)
914 // socket closed gracefully
915 if (!pnode->fDisconnect)
916 printf("socket closed\n");
917 pnode->CloseSocketDisconnect();
922 int nErr = WSAGetLastError();
923 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
925 if (!pnode->fDisconnect)
926 printf("socket recv error %d\n", nErr);
927 pnode->CloseSocketDisconnect();
937 if (pnode->hSocket == INVALID_SOCKET)
939 if (FD_ISSET(pnode->hSocket, &fdsetSend))
941 TRY_LOCK(pnode->cs_vSend, lockSend);
944 CDataStream& vSend = pnode->vSend;
947 int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
950 vSend.erase(vSend.begin(), vSend.begin() + nBytes);
951 pnode->nLastSend = GetTime();
956 int nErr = WSAGetLastError();
957 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
959 printf("socket send error %d\n", nErr);
960 pnode->CloseSocketDisconnect();
968 // Inactivity checking
970 if (pnode->vSend.empty())
971 pnode->nLastSendEmpty = GetTime();
972 if (GetTime() - pnode->nTimeConnected > 60)
974 if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)
976 printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);
977 pnode->fDisconnect = true;
979 else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)
981 printf("socket not sending\n");
982 pnode->fDisconnect = true;
984 else if (GetTime() - pnode->nLastRecv > 90*60)
986 printf("socket inactivity timeout\n");
987 pnode->fDisconnect = true;
993 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1010 void ThreadMapPort(void* parg)
1012 // Make this thread recognisable as the UPnP thread
1013 RenameThread("novacoin-UPnP");
1017 vnThreadsRunning[THREAD_UPNP]++;
1018 ThreadMapPort2(parg);
1019 vnThreadsRunning[THREAD_UPNP]--;
1021 catch (std::exception& e) {
1022 vnThreadsRunning[THREAD_UPNP]--;
1023 PrintException(&e, "ThreadMapPort()");
1025 vnThreadsRunning[THREAD_UPNP]--;
1026 PrintException(NULL, "ThreadMapPort()");
1028 printf("ThreadMapPort exited\n");
1031 void ThreadMapPort2(void* parg)
1033 printf("ThreadMapPort started\n");
1035 std::string port = strprintf("%u", GetListenPort());
1036 const char * multicastif = 0;
1037 const char * minissdpdpath = 0;
1038 struct UPNPDev * devlist = 0;
1041 #ifndef UPNPDISCOVER_SUCCESS
1043 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
1047 devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
1050 struct UPNPUrls urls;
1051 struct IGDdatas data;
1054 r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
1058 char externalIPAddress[40];
1059 r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
1060 if(r != UPNPCOMMAND_SUCCESS)
1061 printf("UPnP: GetExternalIPAddress() returned %d\n", r);
1064 if(externalIPAddress[0])
1066 printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
1067 AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
1070 printf("UPnP: GetExternalIPAddress failed.\n");
1074 string strDesc = "NovaCoin " + FormatFullVersion();
1075 #ifndef UPNPDISCOVER_SUCCESS
1077 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1078 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1081 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1082 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1085 if(r!=UPNPCOMMAND_SUCCESS)
1086 printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1087 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1089 printf("UPnP Port Mapping successful.\n");
1093 if (fShutdown || !fUseUPnP)
1095 r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
1096 printf("UPNP_DeletePortMapping() returned : %d\n", r);
1097 freeUPNPDevlist(devlist); devlist = 0;
1098 FreeUPNPUrls(&urls);
1101 if (i % 600 == 0) // Refresh every 20 minutes
1103 #ifndef UPNPDISCOVER_SUCCESS
1105 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1106 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
1109 r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
1110 port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
1113 if(r!=UPNPCOMMAND_SUCCESS)
1114 printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
1115 port.c_str(), port.c_str(), lanaddr, r, strupnperror(r));
1117 printf("UPnP Port Mapping successful.\n");;
1123 printf("No valid UPnP IGDs found\n");
1124 freeUPNPDevlist(devlist); devlist = 0;
1126 FreeUPNPUrls(&urls);
1129 if (fShutdown || !fUseUPnP)
1138 if (fUseUPnP && vnThreadsRunning[THREAD_UPNP] < 1)
1140 if (!NewThread(ThreadMapPort, NULL))
1141 printf("Error: ThreadMapPort(ThreadMapPort) failed\n");
1147 // Intentionally left blank.
1160 // Each pair gives a source name and a seed name.
1161 // The first name is used as information source for addrman.
1162 // The second name should resolve to a list of seed addresses.
1163 static const char *strDNSSeed[][2] = {
1164 {"novacoin.su", "dnsseed.novacoin.su"},
1165 {"novacoin.ru", "dnsseed.novacoin.ru"},
1166 {"novaco.in", "dnsseed.novaco.in"},
1169 void ThreadDNSAddressSeed(void* parg)
1171 // Make this thread recognisable as the DNS seeding thread
1172 RenameThread("novacoin-dnsseed");
1176 vnThreadsRunning[THREAD_DNSSEED]++;
1177 ThreadDNSAddressSeed2(parg);
1178 vnThreadsRunning[THREAD_DNSSEED]--;
1180 catch (std::exception& e) {
1181 vnThreadsRunning[THREAD_DNSSEED]--;
1182 PrintException(&e, "ThreadDNSAddressSeed()");
1184 vnThreadsRunning[THREAD_DNSSEED]--;
1185 throw; // support pthread_cancel()
1187 printf("ThreadDNSAddressSeed exited\n");
1190 void ThreadDNSAddressSeed2(void* parg)
1192 printf("ThreadDNSAddressSeed started\n");
1197 printf("Loading addresses from DNS seeds (could take a while)\n");
1199 for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
1200 if (HaveNameProxy()) {
1201 AddOneShot(strDNSSeed[seed_idx][1]);
1203 vector<CNetAddr> vaddr;
1204 vector<CAddress> vAdd;
1205 if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
1207 BOOST_FOREACH(CNetAddr& ip, vaddr)
1209 int nOneDay = 24*3600;
1210 CAddress addr = CAddress(CService(ip, GetDefaultPort()));
1211 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1212 vAdd.push_back(addr);
1216 addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
1221 printf("%d addresses found from DNS seeds\n", found);
1235 unsigned int pnSeed[] =
1237 0x90EF78BC, 0x33F1C851, 0x36F1C851, 0xC6F5C851,
1240 void DumpAddresses()
1242 int64 nStart = GetTimeMillis();
1247 printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
1248 addrman.size(), GetTimeMillis() - nStart);
1251 void ThreadDumpAddress2(void* parg)
1253 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1257 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1259 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1261 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1264 void ThreadDumpAddress(void* parg)
1266 // Make this thread recognisable as the address dumping thread
1267 RenameThread("novacoin-adrdump");
1271 ThreadDumpAddress2(parg);
1273 catch (std::exception& e) {
1274 PrintException(&e, "ThreadDumpAddress()");
1276 printf("ThreadDumpAddress exited\n");
1279 void ThreadOpenConnections(void* parg)
1281 // Make this thread recognisable as the connection opening thread
1282 RenameThread("novacoin-opencon");
1286 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1287 ThreadOpenConnections2(parg);
1288 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1290 catch (std::exception& e) {
1291 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1292 PrintException(&e, "ThreadOpenConnections()");
1294 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1295 PrintException(NULL, "ThreadOpenConnections()");
1297 printf("ThreadOpenConnections exited\n");
1300 void static ProcessOneShot()
1305 if (vOneShots.empty())
1307 strDest = vOneShots.front();
1308 vOneShots.pop_front();
1311 CSemaphoreGrant grant(*semOutbound, true);
1313 if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1314 AddOneShot(strDest);
1318 // ppcoin: stake minter thread
1319 void static ThreadStakeMinter(void* parg)
1321 printf("ThreadStakeMinter started\n");
1322 CWallet* pwallet = (CWallet*)parg;
1325 vnThreadsRunning[THREAD_MINTER]++;
1326 StakeMiner(pwallet);
1327 vnThreadsRunning[THREAD_MINTER]--;
1329 catch (std::exception& e) {
1330 vnThreadsRunning[THREAD_MINTER]--;
1331 PrintException(&e, "ThreadStakeMinter()");
1333 vnThreadsRunning[THREAD_MINTER]--;
1334 PrintException(NULL, "ThreadStakeMinter()");
1336 printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
1339 void ThreadOpenConnections2(void* parg)
1341 printf("ThreadOpenConnections started\n");
1343 // Connect to specific addresses
1344 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1346 for (int64 nLoop = 0;; nLoop++)
1349 BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1352 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1353 for (int i = 0; i < 10 && i < nLoop; i++)
1364 // Initiate network connections
1365 int64 nStart = GetTime();
1370 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1372 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1377 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1378 CSemaphoreGrant grant(*semOutbound);
1379 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1383 // Add seed nodes if IRC isn't working
1384 if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
1386 std::vector<CAddress> vAdd;
1387 for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
1389 // It'll only connect to one or two seed nodes because once it connects,
1390 // it'll get a pile of addresses with newer timestamps.
1391 // Seed nodes are given a random 'last seen time' of between one and two
1393 const int64 nOneWeek = 7*24*60*60;
1395 memcpy(&ip, &pnSeed[i], sizeof(ip));
1396 CAddress addr(CService(ip, GetDefaultPort()));
1397 addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
1398 vAdd.push_back(addr);
1400 addrman.Add(vAdd, CNetAddr("127.0.0.1"));
1404 // Choose an address to connect to based on most recently seen
1406 CAddress addrConnect;
1408 // Only connect out to one peer per network group (/16 for IPv4).
1409 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1411 set<vector<unsigned char> > setConnected;
1414 BOOST_FOREACH(CNode* pnode, vNodes) {
1415 if (!pnode->fInbound) {
1416 setConnected.insert(pnode->addr.GetGroup());
1422 int64 nANow = GetAdjustedTime();
1427 // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
1428 CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
1430 // if we selected an invalid address, restart
1431 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1434 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1435 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1436 // already-connected network ranges, ...) before trying new addrman addresses.
1441 if (IsLimited(addr))
1444 // only consider very recently tried nodes after 30 failed attempts
1445 if (nANow - addr.nLastTry < 600 && nTries < 30)
1448 // do not allow non-default ports, unless after 50 invalid addresses selected already
1449 if (addr.GetPort() != GetDefaultPort() && nTries < 50)
1456 if (addrConnect.IsValid())
1457 OpenNetworkConnection(addrConnect, &grant);
1461 void ThreadOpenAddedConnections(void* parg)
1463 // Make this thread recognisable as the connection opening thread
1464 RenameThread("novacoin-opencon");
1468 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1469 ThreadOpenAddedConnections2(parg);
1470 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1472 catch (std::exception& e) {
1473 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1474 PrintException(&e, "ThreadOpenAddedConnections()");
1476 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1477 PrintException(NULL, "ThreadOpenAddedConnections()");
1479 printf("ThreadOpenAddedConnections exited\n");
1482 void ThreadOpenAddedConnections2(void* parg)
1484 printf("ThreadOpenAddedConnections started\n");
1486 if (mapArgs.count("-addnode") == 0)
1489 if (HaveNameProxy()) {
1491 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
1493 CSemaphoreGrant grant(*semOutbound);
1494 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1497 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1498 Sleep(120000); // Retry every 2 minutes
1499 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1504 vector<vector<CService> > vservAddressesToAdd(0);
1505 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
1507 vector<CService> vservNode(0);
1508 if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
1510 vservAddressesToAdd.push_back(vservNode);
1512 LOCK(cs_setservAddNodeAddresses);
1513 BOOST_FOREACH(CService& serv, vservNode)
1514 setservAddNodeAddresses.insert(serv);
1520 vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
1521 // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1522 // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1525 BOOST_FOREACH(CNode* pnode, vNodes)
1526 for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
1527 BOOST_FOREACH(CService& addrNode, *(it))
1528 if (pnode->addr == addrNode)
1530 it = vservConnectAddresses.erase(it);
1535 BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
1537 CSemaphoreGrant grant(*semOutbound);
1538 OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
1545 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1546 Sleep(120000); // Retry every 2 minutes
1547 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1553 // if successful, this moves the passed grant to the constructed node
1554 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
1557 // Initiate outbound network connection
1562 if (IsLocal(addrConnect) ||
1563 FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1564 FindNode(addrConnect.ToStringIPPort().c_str()))
1566 if (strDest && FindNode(strDest))
1569 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1570 CNode* pnode = ConnectNode(addrConnect, strDest);
1571 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1577 grantOutbound->MoveTo(pnode->grantOutbound);
1578 pnode->fNetworkNode = true;
1580 pnode->fOneShot = true;
1585 // for now, use a very simple selection metric: the node from which we received
1587 double static NodeSyncScore(const CNode *pnode) {
1588 return -pnode->nLastRecv;
1591 void static StartSync(const vector<CNode*> &vNodes) {
1592 CNode *pnodeNewSync = NULL;
1593 double dBestScore = 0;
1595 // Iterate over all nodes
1596 BOOST_FOREACH(CNode* pnode, vNodes) {
1597 // check preconditions for allowing a sync
1598 if (!pnode->fClient && !pnode->fOneShot &&
1599 !pnode->fDisconnect && pnode->fSuccessfullyConnected &&
1600 (pnode->nStartingHeight > (nBestHeight - 144)) &&
1601 (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
1602 // if ok, compare node's score with the best so far
1603 double dScore = NodeSyncScore(pnode);
1604 if (pnodeNewSync == NULL || dScore > dBestScore) {
1605 pnodeNewSync = pnode;
1606 dBestScore = dScore;
1610 // if a new sync candidate was found, start sync!
1612 pnodeNewSync->fStartSync = true;
1613 pnodeSync = pnodeNewSync;
1617 void ThreadMessageHandler(void* parg)
1619 // Make this thread recognisable as the message handling thread
1620 RenameThread("novacoin-msghand");
1624 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1625 ThreadMessageHandler2(parg);
1626 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1628 catch (std::exception& e) {
1629 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1630 PrintException(&e, "ThreadMessageHandler()");
1632 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1633 PrintException(NULL, "ThreadMessageHandler()");
1635 printf("ThreadMessageHandler exited\n");
1638 void ThreadMessageHandler2(void* parg)
1640 printf("ThreadMessageHandler started\n");
1641 SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1644 bool fHaveSyncNode = false;
1645 vector<CNode*> vNodesCopy;
1648 vNodesCopy = vNodes;
1649 BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1651 if (pnode == pnodeSync)
1652 fHaveSyncNode = true;
1657 StartSync(vNodesCopy);
1659 // Poll the connected nodes for messages
1660 CNode* pnodeTrickle = NULL;
1661 if (!vNodesCopy.empty())
1662 pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1663 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1667 TRY_LOCK(pnode->cs_vRecv, lockRecv);
1669 ProcessMessages(pnode);
1676 TRY_LOCK(pnode->cs_vSend, lockSend);
1678 SendMessages(pnode, pnode == pnodeTrickle);
1686 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1690 // Wait and allow messages to bunch up.
1691 // Reduce vnThreadsRunning so StopNode has permission to exit while
1692 // we're sleeping, but we must always check fShutdown after doing this.
1693 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1695 if (fRequestShutdown)
1697 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1708 bool BindListenPort(const CService &addrBind, string& strError)
1714 // Initialize Windows Sockets
1716 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1717 if (ret != NO_ERROR)
1719 strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
1720 printf("%s\n", strError.c_str());
1725 // Create socket for listening for incoming connections
1727 struct sockaddr_storage sockaddr;
1729 struct sockaddr sockaddr;
1731 socklen_t len = sizeof(sockaddr);
1732 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1734 strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
1735 printf("%s\n", strError.c_str());
1739 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1740 if (hListenSocket == INVALID_SOCKET)
1742 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1743 printf("%s\n", strError.c_str());
1748 // Different way of disabling SIGPIPE on BSD
1749 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1753 // Allow binding if the port is still in TIME_WAIT state after
1754 // the program was closed and restarted. Not an issue on windows.
1755 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1760 // Set to non-blocking, incoming connections will also inherit this
1761 if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1763 if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1766 strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1767 printf("%s\n", strError.c_str());
1772 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1773 // and enable it by default or not. Try to enable it, if possible.
1774 if (addrBind.IsIPv6()) {
1777 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1779 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1783 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
1784 int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
1785 // this call is allowed to fail
1786 setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
1791 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1793 int nErr = WSAGetLastError();
1794 if (nErr == WSAEADDRINUSE)
1795 strError = strprintf(_("Unable to bind to %s on this computer. NovaCoin is probably already running."), addrBind.ToString().c_str());
1797 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
1798 printf("%s\n", strError.c_str());
1801 printf("Bound to %s\n", addrBind.ToString().c_str());
1803 // Listen for incoming connections
1804 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1806 strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1807 printf("%s\n", strError.c_str());
1811 vhListenSocket.push_back(hListenSocket);
1813 if (addrBind.IsRoutable() && fDiscover)
1814 AddLocal(addrBind, LOCAL_BIND);
1819 void static Discover()
1825 // Get local host IP
1826 char pszHostName[1000] = "";
1827 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1829 vector<CNetAddr> vaddr;
1830 if (LookupHost(pszHostName, vaddr))
1832 BOOST_FOREACH (const CNetAddr &addr, vaddr)
1834 AddLocal(addr, LOCAL_IF);
1839 // Get local host ip
1840 struct ifaddrs* myaddrs;
1841 if (getifaddrs(&myaddrs) == 0)
1843 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1845 if (ifa->ifa_addr == NULL) continue;
1846 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1847 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1848 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1849 if (ifa->ifa_addr->sa_family == AF_INET)
1851 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1852 CNetAddr addr(s4->sin_addr);
1853 if (AddLocal(addr, LOCAL_IF))
1854 printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1857 else if (ifa->ifa_addr->sa_family == AF_INET6)
1859 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1860 CNetAddr addr(s6->sin6_addr);
1861 if (AddLocal(addr, LOCAL_IF))
1862 printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1866 freeifaddrs(myaddrs);
1870 // Don't use external IPv4 discovery, when -onlynet="IPv6"
1871 if (!IsLimited(NET_IPV4))
1872 NewThread(ThreadGetMyExternalIP, NULL);
1875 void StartNode(void* parg)
1877 // Make this thread recognisable as the startup thread
1878 RenameThread("novacoin-start");
1880 if (semOutbound == NULL) {
1881 // initialize semaphore
1882 int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
1883 semOutbound = new CSemaphore(nMaxOutbound);
1886 if (pnodeLocalHost == NULL)
1887 pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1895 if (!GetBoolArg("-dnsseed", true))
1896 printf("DNS seeding disabled\n");
1898 if (!NewThread(ThreadDNSAddressSeed, NULL))
1899 printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
1901 // Map ports with UPnP
1905 // Get addresses from IRC and advertise ours
1906 if (!NewThread(ThreadIRCSeed, NULL))
1907 printf("Error: NewThread(ThreadIRCSeed) failed\n");
1909 // Send and receive from sockets, accept connections
1910 if (!NewThread(ThreadSocketHandler, NULL))
1911 printf("Error: NewThread(ThreadSocketHandler) failed\n");
1913 // Initiate outbound connections from -addnode
1914 if (!NewThread(ThreadOpenAddedConnections, NULL))
1915 printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
1917 // Initiate outbound connections
1918 if (!NewThread(ThreadOpenConnections, NULL))
1919 printf("Error: NewThread(ThreadOpenConnections) failed\n");
1922 if (!NewThread(ThreadMessageHandler, NULL))
1923 printf("Error: NewThread(ThreadMessageHandler) failed\n");
1925 // Dump network addresses
1926 if (!NewThread(ThreadDumpAddress, NULL))
1927 printf("Error; NewThread(ThreadDumpAddress) failed\n");
1929 // ppcoin: mint proof-of-stake blocks in the background
1930 if (!NewThread(ThreadStakeMinter, pwalletMain))
1931 printf("Error: NewThread(ThreadStakeMinter) failed\n");
1936 printf("StopNode()\n");
1938 nTransactionsUpdated++;
1939 int64 nStart = GetTime();
1942 ThreadScriptCheckQuit();
1945 for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1946 semOutbound->post();
1949 int nThreadsRunning = 0;
1950 for (int n = 0; n < THREAD_MAX; n++)
1951 nThreadsRunning += vnThreadsRunning[n];
1952 if (nThreadsRunning == 0)
1954 if (GetTime() - nStart > 20)
1958 if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
1959 if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
1960 if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
1961 if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
1962 if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
1964 if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
1966 if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
1967 if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
1968 if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
1969 if (vnThreadsRunning[THREAD_MINTER] > 0) printf("ThreadStakeMinter still running\n");
1970 if (vnThreadsRunning[THREAD_SCRIPTCHECK] > 0) printf("ThreadScriptCheck still running\n");
1971 while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0 || vnThreadsRunning[THREAD_SCRIPTCHECK] > 0)
1987 BOOST_FOREACH(CNode* pnode, vNodes)
1988 if (pnode->hSocket != INVALID_SOCKET)
1989 closesocket(pnode->hSocket);
1990 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
1991 if (hListenSocket != INVALID_SOCKET)
1992 if (closesocket(hListenSocket) == SOCKET_ERROR)
1993 printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
1996 // Shutdown Windows Sockets
2001 instance_of_cnetcleanup;
2003 void RelayTransaction(const CTransaction& tx, const uint256& hash)
2005 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
2008 RelayTransaction(tx, hash, ss);
2011 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
2013 CInv inv(MSG_TX, hash);
2016 // Expire old relay messages
2017 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
2019 mapRelay.erase(vRelayExpiration.front().second);
2020 vRelayExpiration.pop_front();
2023 // Save original serialized message so newer versions are preserved
2024 mapRelay.insert(std::make_pair(inv, ss));
2025 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
2028 RelayInventory(inv);