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 boost::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);
435 uint64_t CNode::nTotalBytesRecv = 0;
436 uint64_t CNode::nTotalBytesSent = 0;
437 CCriticalSection CNode::cs_totalBytesRecv;
438 CCriticalSection CNode::cs_totalBytesSent;
440 CNode* FindNode(const CNetAddr& ip)
443 BOOST_FOREACH(CNode* pnode, vNodes)
444 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)
461 BOOST_FOREACH(CNode* pnode, vNodes)
462 if ((CService)pnode->addr == addr)
467 CNode* ConnectNode(CAddress addrConnect, const char *pszDest, int64 nTimeout)
469 if (pszDest == NULL) {
470 if (IsLocal(addrConnect))
473 // Look for an existing connection
474 CNode* pnode = FindNode((CService)addrConnect);
478 pnode->AddRef(nTimeout);
487 printf("trying connection %s lastseen=%.1fhrs\n",
488 pszDest ? pszDest : addrConnect.ToString().c_str(),
489 pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0);
493 if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, GetDefaultPort()) : ConnectSocket(addrConnect, hSocket))
495 addrman.Attempt(addrConnect);
498 printf("connected %s\n", pszDest ? pszDest : addrConnect.ToString().c_str());
500 // Set to non-blocking
503 if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)
504 printf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError());
506 if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
507 printf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno);
511 CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
513 pnode->AddRef(nTimeout);
519 vNodes.push_back(pnode);
522 pnode->nTimeConnected = GetTime();
531 void CNode::CloseSocketDisconnect()
534 if (hSocket != INVALID_SOCKET)
536 printf("disconnecting node %s\n", addrName.c_str());
537 closesocket(hSocket);
538 hSocket = INVALID_SOCKET;
542 // in case this fails, we'll empty the recv buffer when the CNode is deleted
543 TRY_LOCK(cs_vRecv, lockRecv);
547 // if this was the sync node, we'll need a new one
548 if (this == pnodeSync)
552 void CNode::Cleanup()
557 void CNode::PushVersion()
559 /// when NTP implemented, change to just nTime = GetAdjustedTime()
560 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
561 CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0)));
562 CAddress addrMe = GetLocalAddress(&addr);
563 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
564 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());
565 PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
566 nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight);
573 std::map<CNetAddr, int64> CNode::setBanned;
574 CCriticalSection CNode::cs_setBanned;
576 void CNode::ClearBanned()
581 bool CNode::IsBanned(CNetAddr ip)
583 bool fResult = false;
586 std::map<CNetAddr, int64>::iterator i = setBanned.find(ip);
587 if (i != setBanned.end())
589 int64 t = (*i).second;
597 bool CNode::Misbehaving(int howmuch)
601 printf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName.c_str(), howmuch);
605 nMisbehavior += howmuch;
606 if (nMisbehavior >= GetArg("-banscore", 100))
608 int64 banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban
609 printf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
612 if (setBanned[addr] < banTime)
613 setBanned[addr] = banTime;
615 CloseSocketDisconnect();
618 printf("Misbehaving: %s (%d -> %d)\n", addr.ToString().c_str(), nMisbehavior-howmuch, nMisbehavior);
623 #define X(name) stats.name = name
624 void CNode::copyStats(CNodeStats &stats)
639 stats.fSyncNode = (this == pnodeSync);
652 void ThreadSocketHandler(void* parg)
654 // Make this thread recognisable as the networking thread
655 RenameThread("novacoin-net");
659 vnThreadsRunning[THREAD_SOCKETHANDLER]++;
660 ThreadSocketHandler2(parg);
661 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
663 catch (std::exception& e) {
664 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
665 PrintException(&e, "ThreadSocketHandler()");
667 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
668 throw; // support pthread_cancel()
670 printf("ThreadSocketHandler exited\n");
673 void ThreadSocketHandler2(void* parg)
675 printf("ThreadSocketHandler started\n");
676 list<CNode*> vNodesDisconnected;
677 unsigned int nPrevNodeCount = 0;
686 // Disconnect unused nodes
687 vector<CNode*> vNodesCopy = vNodes;
688 BOOST_FOREACH(CNode* pnode, vNodesCopy)
690 if (pnode->fDisconnect ||
691 (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))
693 // remove from vNodes
694 vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
696 // release outbound grant (if any)
697 pnode->grantOutbound.Release();
699 // close socket and cleanup
700 pnode->CloseSocketDisconnect();
703 // hold in disconnected pool until all refs are released
704 pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);
705 if (pnode->fNetworkNode || pnode->fInbound)
707 vNodesDisconnected.push_back(pnode);
711 // Delete disconnected nodes
712 list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
713 BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy)
715 // wait until threads are done using it
716 if (pnode->GetRefCount() <= 0)
718 bool fDelete = false;
720 TRY_LOCK(pnode->cs_vSend, lockSend);
723 TRY_LOCK(pnode->cs_vRecv, lockRecv);
726 TRY_LOCK(pnode->cs_mapRequests, lockReq);
729 TRY_LOCK(pnode->cs_inventory, lockInv);
738 vNodesDisconnected.remove(pnode);
744 if (vNodes.size() != nPrevNodeCount)
746 nPrevNodeCount = vNodes.size();
747 uiInterface.NotifyNumConnectionsChanged(vNodes.size());
752 // Find which sockets have data to receive
754 struct timeval timeout;
756 timeout.tv_usec = 50000; // frequency to poll pnode->vSend
763 FD_ZERO(&fdsetError);
764 SOCKET hSocketMax = 0;
765 bool have_fds = false;
767 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) {
768 FD_SET(hListenSocket, &fdsetRecv);
769 hSocketMax = max(hSocketMax, hListenSocket);
774 BOOST_FOREACH(CNode* pnode, vNodes)
776 if (pnode->hSocket == INVALID_SOCKET)
778 FD_SET(pnode->hSocket, &fdsetRecv);
779 FD_SET(pnode->hSocket, &fdsetError);
780 hSocketMax = max(hSocketMax, pnode->hSocket);
783 TRY_LOCK(pnode->cs_vSend, lockSend);
784 if (lockSend && !pnode->vSend.empty())
785 FD_SET(pnode->hSocket, &fdsetSend);
790 vnThreadsRunning[THREAD_SOCKETHANDLER]--;
791 int nSelect = select(have_fds ? hSocketMax + 1 : 0,
792 &fdsetRecv, &fdsetSend, &fdsetError, &timeout);
793 vnThreadsRunning[THREAD_SOCKETHANDLER]++;
796 if (nSelect == SOCKET_ERROR)
800 int nErr = WSAGetLastError();
801 printf("socket select error %d\n", nErr);
802 for (unsigned int i = 0; i <= hSocketMax; i++)
803 FD_SET(i, &fdsetRecv);
806 FD_ZERO(&fdsetError);
807 Sleep(timeout.tv_usec/1000);
812 // Accept new connections
814 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
815 if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv))
818 struct sockaddr_storage sockaddr;
820 struct sockaddr sockaddr;
822 socklen_t len = sizeof(sockaddr);
823 SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);
827 if (hSocket != INVALID_SOCKET)
828 if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
829 printf("Warning: Unknown socket family\n");
833 BOOST_FOREACH(CNode* pnode, vNodes)
838 if (hSocket == INVALID_SOCKET)
840 int nErr = WSAGetLastError();
841 if (nErr != WSAEWOULDBLOCK)
842 printf("socket error accept failed: %d\n", nErr);
844 else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS)
847 LOCK(cs_setservAddNodeAddresses);
848 if (!setservAddNodeAddresses.count(addr))
849 closesocket(hSocket);
852 else if (CNode::IsBanned(addr))
854 printf("connection from %s dropped (banned)\n", addr.ToString().c_str());
855 closesocket(hSocket);
859 printf("accepted connection %s\n", addr.ToString().c_str());
860 CNode* pnode = new CNode(hSocket, addr, "", true);
864 vNodes.push_back(pnode);
871 // Service each socket
873 vector<CNode*> vNodesCopy;
877 BOOST_FOREACH(CNode* pnode, vNodesCopy)
880 BOOST_FOREACH(CNode* pnode, vNodesCopy)
888 if (pnode->hSocket == INVALID_SOCKET)
890 if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))
892 TRY_LOCK(pnode->cs_vRecv, lockRecv);
895 CDataStream& vRecv = pnode->vRecv;
896 unsigned int nPos = vRecv.size();
898 if (nPos > ReceiveBufferSize()) {
899 if (!pnode->fDisconnect)
900 printf("socket recv flood control disconnect (%"PRIszu" bytes)\n", vRecv.size());
901 pnode->CloseSocketDisconnect();
904 // typical socket buffer is 8K-64K
905 char pchBuf[0x10000];
906 int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
909 vRecv.resize(nPos + nBytes);
910 memcpy(&vRecv[nPos], pchBuf, nBytes);
911 pnode->nLastRecv = GetTime();
912 pnode->nRecvBytes += nBytes;
913 pnode->RecordBytesRecv(nBytes);
915 else if (nBytes == 0)
917 // socket closed gracefully
918 if (!pnode->fDisconnect)
919 printf("socket closed\n");
920 pnode->CloseSocketDisconnect();
925 int nErr = WSAGetLastError();
926 if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)
928 if (!pnode->fDisconnect)
929 printf("socket recv error %d\n", nErr);
930 pnode->CloseSocketDisconnect();
940 if (pnode->hSocket == INVALID_SOCKET)
942 if (FD_ISSET(pnode->hSocket, &fdsetSend))
944 TRY_LOCK(pnode->cs_vSend, lockSend);
947 CDataStream& vSend = pnode->vSend;
950 int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);
953 vSend.erase(vSend.begin(), vSend.begin() + nBytes);
954 pnode->nLastSend = GetTime();
955 pnode->nSendBytes += nBytes;
956 pnode->RecordBytesSent(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.karelia.pro", "dnsseed.novacoin.karelia.pro"},
1170 {"novacoin.su", "dnsseed.novacoin.su"},
1171 {"novacoin.ru", "dnsseed.novacoin.ru"},
1172 {"novaco.in", "dnsseed.novaco.in"},
1175 void ThreadDNSAddressSeed(void* parg)
1177 // Make this thread recognisable as the DNS seeding thread
1178 RenameThread("novacoin-dnsseed");
1182 vnThreadsRunning[THREAD_DNSSEED]++;
1183 ThreadDNSAddressSeed2(parg);
1184 vnThreadsRunning[THREAD_DNSSEED]--;
1186 catch (std::exception& e) {
1187 vnThreadsRunning[THREAD_DNSSEED]--;
1188 PrintException(&e, "ThreadDNSAddressSeed()");
1190 vnThreadsRunning[THREAD_DNSSEED]--;
1191 throw; // support pthread_cancel()
1193 printf("ThreadDNSAddressSeed exited\n");
1196 void ThreadDNSAddressSeed2(void* parg)
1198 printf("ThreadDNSAddressSeed started\n");
1203 printf("Loading addresses from DNS seeds (could take a while)\n");
1205 for (unsigned int seed_idx = 0; seed_idx < ARRAYLEN(strDNSSeed); seed_idx++) {
1206 if (HaveNameProxy()) {
1207 AddOneShot(strDNSSeed[seed_idx][1]);
1209 vector<CNetAddr> vaddr;
1210 vector<CAddress> vAdd;
1211 if (LookupHost(strDNSSeed[seed_idx][1], vaddr))
1213 BOOST_FOREACH(CNetAddr& ip, vaddr)
1215 int nOneDay = 24*3600;
1216 CAddress addr = CAddress(CService(ip, GetDefaultPort()));
1217 addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old
1218 vAdd.push_back(addr);
1222 addrman.Add(vAdd, CNetAddr(strDNSSeed[seed_idx][0], true));
1227 printf("%d addresses found from DNS seeds\n", found);
1241 unsigned int pnSeed[] =
1243 0x90EF78BC, 0x33F1C851, 0x36F1C851, 0xC6F5C851,
1246 void DumpAddresses()
1248 int64 nStart = GetTimeMillis();
1253 printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
1254 addrman.size(), GetTimeMillis() - nStart);
1257 void ThreadDumpAddress2(void* parg)
1259 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1263 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1265 vnThreadsRunning[THREAD_DUMPADDRESS]++;
1267 vnThreadsRunning[THREAD_DUMPADDRESS]--;
1270 void ThreadDumpAddress(void* parg)
1272 // Make this thread recognisable as the address dumping thread
1273 RenameThread("novacoin-adrdump");
1277 ThreadDumpAddress2(parg);
1279 catch (std::exception& e) {
1280 PrintException(&e, "ThreadDumpAddress()");
1282 printf("ThreadDumpAddress exited\n");
1285 void ThreadOpenConnections(void* parg)
1287 // Make this thread recognisable as the connection opening thread
1288 RenameThread("novacoin-opencon");
1292 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1293 ThreadOpenConnections2(parg);
1294 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1296 catch (std::exception& e) {
1297 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1298 PrintException(&e, "ThreadOpenConnections()");
1300 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1301 PrintException(NULL, "ThreadOpenConnections()");
1303 printf("ThreadOpenConnections exited\n");
1306 void static ProcessOneShot()
1311 if (vOneShots.empty())
1313 strDest = vOneShots.front();
1314 vOneShots.pop_front();
1317 CSemaphoreGrant grant(*semOutbound, true);
1319 if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
1320 AddOneShot(strDest);
1324 // ppcoin: stake minter thread
1325 void static ThreadStakeMinter(void* parg)
1327 printf("ThreadStakeMinter started\n");
1328 CWallet* pwallet = (CWallet*)parg;
1331 vnThreadsRunning[THREAD_MINTER]++;
1332 StakeMiner(pwallet);
1333 vnThreadsRunning[THREAD_MINTER]--;
1335 catch (std::exception& e) {
1336 vnThreadsRunning[THREAD_MINTER]--;
1337 PrintException(&e, "ThreadStakeMinter()");
1339 vnThreadsRunning[THREAD_MINTER]--;
1340 PrintException(NULL, "ThreadStakeMinter()");
1342 printf("ThreadStakeMinter exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINTER]);
1345 void ThreadOpenConnections2(void* parg)
1347 printf("ThreadOpenConnections started\n");
1349 // Connect to specific addresses
1350 if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0)
1352 for (int64 nLoop = 0;; nLoop++)
1355 BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"])
1358 OpenNetworkConnection(addr, NULL, strAddr.c_str());
1359 for (int i = 0; i < 10 && i < nLoop; i++)
1370 // Initiate network connections
1371 int64 nStart = GetTime();
1376 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1378 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1383 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1384 CSemaphoreGrant grant(*semOutbound);
1385 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1389 // Add seed nodes if IRC isn't working
1390 if (addrman.size()==0 && (GetTime() - nStart > 60) && !fTestNet)
1392 std::vector<CAddress> vAdd;
1393 for (unsigned int i = 0; i < ARRAYLEN(pnSeed); i++)
1395 // It'll only connect to one or two seed nodes because once it connects,
1396 // it'll get a pile of addresses with newer timestamps.
1397 // Seed nodes are given a random 'last seen time' of between one and two
1399 const int64 nOneWeek = 7*24*60*60;
1401 memcpy(&ip, &pnSeed[i], sizeof(ip));
1402 CAddress addr(CService(ip, GetDefaultPort()));
1403 addr.nTime = GetTime()-GetRand(nOneWeek)-nOneWeek;
1404 vAdd.push_back(addr);
1406 addrman.Add(vAdd, CNetAddr("127.0.0.1"));
1410 // Choose an address to connect to based on most recently seen
1412 CAddress addrConnect;
1414 // Only connect out to one peer per network group (/16 for IPv4).
1415 // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
1417 set<vector<unsigned char> > setConnected;
1420 BOOST_FOREACH(CNode* pnode, vNodes) {
1421 if (!pnode->fInbound) {
1422 setConnected.insert(pnode->addr.GetGroup());
1428 int64 nANow = GetAdjustedTime();
1433 // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections)
1434 CAddress addr = addrman.Select(10 + min(nOutbound,8)*10);
1436 // if we selected an invalid address, restart
1437 if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
1440 // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
1441 // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
1442 // already-connected network ranges, ...) before trying new addrman addresses.
1447 if (IsLimited(addr))
1450 // only consider very recently tried nodes after 30 failed attempts
1451 if (nANow - addr.nLastTry < 600 && nTries < 30)
1454 // do not allow non-default ports, unless after 50 invalid addresses selected already
1455 if (addr.GetPort() != GetDefaultPort() && nTries < 50)
1462 if (addrConnect.IsValid())
1463 OpenNetworkConnection(addrConnect, &grant);
1467 void ThreadOpenAddedConnections(void* parg)
1469 // Make this thread recognisable as the connection opening thread
1470 RenameThread("novacoin-opencon");
1474 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1475 ThreadOpenAddedConnections2(parg);
1476 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1478 catch (std::exception& e) {
1479 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1480 PrintException(&e, "ThreadOpenAddedConnections()");
1482 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1483 PrintException(NULL, "ThreadOpenAddedConnections()");
1485 printf("ThreadOpenAddedConnections exited\n");
1488 void ThreadOpenAddedConnections2(void* parg)
1490 printf("ThreadOpenAddedConnections started\n");
1492 if (mapArgs.count("-addnode") == 0)
1495 if (HaveNameProxy()) {
1497 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"]) {
1499 CSemaphoreGrant grant(*semOutbound);
1500 OpenNetworkConnection(addr, &grant, strAddNode.c_str());
1503 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1504 Sleep(120000); // Retry every 2 minutes
1505 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1510 vector<vector<CService> > vservAddressesToAdd(0);
1511 BOOST_FOREACH(string& strAddNode, mapMultiArgs["-addnode"])
1513 vector<CService> vservNode(0);
1514 if(Lookup(strAddNode.c_str(), vservNode, GetDefaultPort(), fNameLookup, 0))
1516 vservAddressesToAdd.push_back(vservNode);
1518 LOCK(cs_setservAddNodeAddresses);
1519 BOOST_FOREACH(CService& serv, vservNode)
1520 setservAddNodeAddresses.insert(serv);
1526 vector<vector<CService> > vservConnectAddresses = vservAddressesToAdd;
1527 // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
1528 // (keeping in mind that addnode entries can have many IPs if fNameLookup)
1531 BOOST_FOREACH(CNode* pnode, vNodes)
1532 for (vector<vector<CService> >::iterator it = vservConnectAddresses.begin(); it != vservConnectAddresses.end(); it++)
1533 BOOST_FOREACH(CService& addrNode, *(it))
1534 if (pnode->addr == addrNode)
1536 it = vservConnectAddresses.erase(it);
1541 BOOST_FOREACH(vector<CService>& vserv, vservConnectAddresses)
1543 CSemaphoreGrant grant(*semOutbound);
1544 OpenNetworkConnection(CAddress(*(vserv.begin())), &grant);
1551 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]--;
1552 Sleep(120000); // Retry every 2 minutes
1553 vnThreadsRunning[THREAD_ADDEDCONNECTIONS]++;
1559 // if successful, this moves the passed grant to the constructed node
1560 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot)
1563 // Initiate outbound network connection
1568 if (IsLocal(addrConnect) ||
1569 FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
1570 FindNode(addrConnect.ToStringIPPort().c_str()))
1572 if (strDest && FindNode(strDest))
1575 vnThreadsRunning[THREAD_OPENCONNECTIONS]--;
1576 CNode* pnode = ConnectNode(addrConnect, strDest);
1577 vnThreadsRunning[THREAD_OPENCONNECTIONS]++;
1583 grantOutbound->MoveTo(pnode->grantOutbound);
1584 pnode->fNetworkNode = true;
1586 pnode->fOneShot = true;
1591 // for now, use a very simple selection metric: the node from which we received
1593 double static NodeSyncScore(const CNode *pnode) {
1594 return -pnode->nLastRecv;
1597 void static StartSync(const vector<CNode*> &vNodes) {
1598 CNode *pnodeNewSync = NULL;
1599 double dBestScore = 0;
1601 // Iterate over all nodes
1602 BOOST_FOREACH(CNode* pnode, vNodes) {
1603 // check preconditions for allowing a sync
1604 if (!pnode->fClient && !pnode->fOneShot &&
1605 !pnode->fDisconnect && pnode->fSuccessfullyConnected &&
1606 (pnode->nStartingHeight > (nBestHeight - 144)) &&
1607 (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) {
1608 // if ok, compare node's score with the best so far
1609 double dScore = NodeSyncScore(pnode);
1610 if (pnodeNewSync == NULL || dScore > dBestScore) {
1611 pnodeNewSync = pnode;
1612 dBestScore = dScore;
1616 // if a new sync candidate was found, start sync!
1618 pnodeNewSync->fStartSync = true;
1619 pnodeSync = pnodeNewSync;
1623 void ThreadMessageHandler(void* parg)
1625 // Make this thread recognisable as the message handling thread
1626 RenameThread("novacoin-msghand");
1630 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1631 ThreadMessageHandler2(parg);
1632 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1634 catch (std::exception& e) {
1635 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1636 PrintException(&e, "ThreadMessageHandler()");
1638 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1639 PrintException(NULL, "ThreadMessageHandler()");
1641 printf("ThreadMessageHandler exited\n");
1644 void ThreadMessageHandler2(void* parg)
1646 printf("ThreadMessageHandler started\n");
1647 SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
1650 bool fHaveSyncNode = false;
1651 vector<CNode*> vNodesCopy;
1654 vNodesCopy = vNodes;
1655 BOOST_FOREACH(CNode* pnode, vNodesCopy) {
1657 if (pnode == pnodeSync)
1658 fHaveSyncNode = true;
1663 StartSync(vNodesCopy);
1665 // Poll the connected nodes for messages
1666 CNode* pnodeTrickle = NULL;
1667 if (!vNodesCopy.empty())
1668 pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
1669 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1673 TRY_LOCK(pnode->cs_vRecv, lockRecv);
1675 ProcessMessages(pnode);
1682 TRY_LOCK(pnode->cs_vSend, lockSend);
1684 SendMessages(pnode, pnode == pnodeTrickle);
1692 BOOST_FOREACH(CNode* pnode, vNodesCopy)
1696 // Wait and allow messages to bunch up.
1697 // Reduce vnThreadsRunning so StopNode has permission to exit while
1698 // we're sleeping, but we must always check fShutdown after doing this.
1699 vnThreadsRunning[THREAD_MESSAGEHANDLER]--;
1701 if (fRequestShutdown)
1703 vnThreadsRunning[THREAD_MESSAGEHANDLER]++;
1714 bool BindListenPort(const CService &addrBind, string& strError)
1720 // Initialize Windows Sockets
1722 int ret = WSAStartup(MAKEWORD(2,2), &wsadata);
1723 if (ret != NO_ERROR)
1725 strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);
1726 printf("%s\n", strError.c_str());
1731 // Create socket for listening for incoming connections
1733 struct sockaddr_storage sockaddr;
1735 struct sockaddr sockaddr;
1737 socklen_t len = sizeof(sockaddr);
1738 if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len))
1740 strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString().c_str());
1741 printf("%s\n", strError.c_str());
1745 SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
1746 if (hListenSocket == INVALID_SOCKET)
1748 strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());
1749 printf("%s\n", strError.c_str());
1754 // Different way of disabling SIGPIPE on BSD
1755 setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
1759 // Allow binding if the port is still in TIME_WAIT state after
1760 // the program was closed and restarted. Not an issue on windows.
1761 setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
1766 // Set to non-blocking, incoming connections will also inherit this
1767 if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)
1769 if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)
1772 strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());
1773 printf("%s\n", strError.c_str());
1778 // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
1779 // and enable it by default or not. Try to enable it, if possible.
1780 if (addrBind.IsIPv6()) {
1783 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
1785 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
1789 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */;
1790 int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */;
1791 // this call is allowed to fail
1792 setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int));
1797 if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR)
1799 int nErr = WSAGetLastError();
1800 if (nErr == WSAEADDRINUSE)
1801 strError = strprintf(_("Unable to bind to %s on this computer. NovaCoin is probably already running."), addrBind.ToString().c_str());
1803 strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString().c_str(), nErr, strerror(nErr));
1804 printf("%s\n", strError.c_str());
1807 printf("Bound to %s\n", addrBind.ToString().c_str());
1809 // Listen for incoming connections
1810 if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)
1812 strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());
1813 printf("%s\n", strError.c_str());
1817 vhListenSocket.push_back(hListenSocket);
1819 if (addrBind.IsRoutable() && fDiscover)
1820 AddLocal(addrBind, LOCAL_BIND);
1825 void static Discover()
1831 // Get local host IP
1832 char pszHostName[1000] = "";
1833 if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)
1835 vector<CNetAddr> vaddr;
1836 if (LookupHost(pszHostName, vaddr))
1838 BOOST_FOREACH (const CNetAddr &addr, vaddr)
1840 AddLocal(addr, LOCAL_IF);
1845 // Get local host ip
1846 struct ifaddrs* myaddrs;
1847 if (getifaddrs(&myaddrs) == 0)
1849 for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)
1851 if (ifa->ifa_addr == NULL) continue;
1852 if ((ifa->ifa_flags & IFF_UP) == 0) continue;
1853 if (strcmp(ifa->ifa_name, "lo") == 0) continue;
1854 if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
1855 if (ifa->ifa_addr->sa_family == AF_INET)
1857 struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
1858 CNetAddr addr(s4->sin_addr);
1859 if (AddLocal(addr, LOCAL_IF))
1860 printf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1863 else if (ifa->ifa_addr->sa_family == AF_INET6)
1865 struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
1866 CNetAddr addr(s6->sin6_addr);
1867 if (AddLocal(addr, LOCAL_IF))
1868 printf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString().c_str());
1872 freeifaddrs(myaddrs);
1876 // Don't use external IPv4 discovery, when -onlynet="IPv6"
1877 if (!IsLimited(NET_IPV4))
1878 NewThread(ThreadGetMyExternalIP, NULL);
1881 void StartNode(void* parg)
1883 // Make this thread recognisable as the startup thread
1884 RenameThread("novacoin-start");
1886 if (semOutbound == NULL) {
1887 // initialize semaphore
1888 int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125));
1889 semOutbound = new CSemaphore(nMaxOutbound);
1892 if (pnodeLocalHost == NULL)
1893 pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
1901 if (!GetBoolArg("-dnsseed", true))
1902 printf("DNS seeding disabled\n");
1904 if (!NewThread(ThreadDNSAddressSeed, NULL))
1905 printf("Error: NewThread(ThreadDNSAddressSeed) failed\n");
1907 // Map ports with UPnP
1911 // Get addresses from IRC and advertise ours
1912 if (!NewThread(ThreadIRCSeed, NULL))
1913 printf("Error: NewThread(ThreadIRCSeed) failed\n");
1915 // Send and receive from sockets, accept connections
1916 if (!NewThread(ThreadSocketHandler, NULL))
1917 printf("Error: NewThread(ThreadSocketHandler) failed\n");
1919 // Initiate outbound connections from -addnode
1920 if (!NewThread(ThreadOpenAddedConnections, NULL))
1921 printf("Error: NewThread(ThreadOpenAddedConnections) failed\n");
1923 // Initiate outbound connections
1924 if (!NewThread(ThreadOpenConnections, NULL))
1925 printf("Error: NewThread(ThreadOpenConnections) failed\n");
1928 if (!NewThread(ThreadMessageHandler, NULL))
1929 printf("Error: NewThread(ThreadMessageHandler) failed\n");
1931 // Dump network addresses
1932 if (!NewThread(ThreadDumpAddress, NULL))
1933 printf("Error; NewThread(ThreadDumpAddress) failed\n");
1935 // ppcoin: mint proof-of-stake blocks in the background
1936 if (!NewThread(ThreadStakeMinter, pwalletMain))
1937 printf("Error: NewThread(ThreadStakeMinter) failed\n");
1942 printf("StopNode()\n");
1944 nTransactionsUpdated++;
1945 int64 nStart = GetTime();
1948 ThreadScriptCheckQuit();
1951 for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++)
1952 semOutbound->post();
1955 int nThreadsRunning = 0;
1956 for (int n = 0; n < THREAD_MAX; n++)
1957 nThreadsRunning += vnThreadsRunning[n];
1958 if (nThreadsRunning == 0)
1960 if (GetTime() - nStart > 20)
1964 if (vnThreadsRunning[THREAD_SOCKETHANDLER] > 0) printf("ThreadSocketHandler still running\n");
1965 if (vnThreadsRunning[THREAD_OPENCONNECTIONS] > 0) printf("ThreadOpenConnections still running\n");
1966 if (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0) printf("ThreadMessageHandler still running\n");
1967 if (vnThreadsRunning[THREAD_RPCLISTENER] > 0) printf("ThreadRPCListener still running\n");
1968 if (vnThreadsRunning[THREAD_RPCHANDLER] > 0) printf("ThreadsRPCServer still running\n");
1970 if (vnThreadsRunning[THREAD_UPNP] > 0) printf("ThreadMapPort still running\n");
1972 if (vnThreadsRunning[THREAD_DNSSEED] > 0) printf("ThreadDNSAddressSeed still running\n");
1973 if (vnThreadsRunning[THREAD_ADDEDCONNECTIONS] > 0) printf("ThreadOpenAddedConnections still running\n");
1974 if (vnThreadsRunning[THREAD_DUMPADDRESS] > 0) printf("ThreadDumpAddresses still running\n");
1975 if (vnThreadsRunning[THREAD_MINTER] > 0) printf("ThreadStakeMinter still running\n");
1976 if (vnThreadsRunning[THREAD_SCRIPTCHECK] > 0) printf("ThreadScriptCheck still running\n");
1977 while (vnThreadsRunning[THREAD_MESSAGEHANDLER] > 0 || vnThreadsRunning[THREAD_RPCHANDLER] > 0 || vnThreadsRunning[THREAD_SCRIPTCHECK] > 0)
1993 BOOST_FOREACH(CNode* pnode, vNodes)
1994 if (pnode->hSocket != INVALID_SOCKET)
1995 closesocket(pnode->hSocket);
1996 BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket)
1997 if (hListenSocket != INVALID_SOCKET)
1998 if (closesocket(hListenSocket) == SOCKET_ERROR)
1999 printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());
2002 // Shutdown Windows Sockets
2007 instance_of_cnetcleanup;
2009 void RelayTransaction(const CTransaction& tx, const uint256& hash)
2011 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
2014 RelayTransaction(tx, hash, ss);
2017 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss)
2019 CInv inv(MSG_TX, hash);
2022 // Expire old relay messages
2023 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
2025 mapRelay.erase(vRelayExpiration.front().second);
2026 vRelayExpiration.pop_front();
2029 // Save original serialized message so newer versions are preserved
2030 mapRelay.insert(std::make_pair(inv, ss));
2031 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
2034 RelayInventory(inv);
2037 void CNode::RecordBytesRecv(uint64_t bytes)
2039 LOCK(cs_totalBytesRecv);
2040 nTotalBytesRecv += bytes;
2043 void CNode::RecordBytesSent(uint64_t bytes)
2045 LOCK(cs_totalBytesSent);
2046 nTotalBytesSent += bytes;
2049 uint64_t CNode::GetTotalBytesRecv()
2051 LOCK(cs_totalBytesRecv);
2052 return nTotalBytesRecv;
2055 uint64_t CNode::GetTotalBytesSent()
2057 LOCK(cs_totalBytesSent);
2058 return nTotalBytesSent;