Research
Timechain
Search Donate
Sponsors
Cake Wallet, private Bitcoin and Monero walletSideShift.ai, no-signup crypto exchangeOrangeRock, non-custodial bitcoin spot and perps tradingBraiins Hashpower, buy and sell Bitcoin hashrateeCash.com
Bitcoin v0.3.19 · 2010-12-13

net.cpp

1,402 lines · plain text · GitHub · MIT license (license.txt)
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include "headers.h"67static const int MAX_OUTBOUND_CONNECTIONS = 8;89void ThreadMessageHandler2(void* parg);10void ThreadSocketHandler2(void* parg);11void ThreadOpenConnections2(void* parg);12bool OpenNetworkConnection(const CAddress& addrConnect);131415161718//19// Global state variables20//21bool fClient = false;22uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);23CAddress addrLocalHost(0, 0, nLocalServices);24CNode* pnodeLocalHost = NULL;25uint64 nLocalHostNonce = 0;26array<int, 10> vnThreadsRunning;27SOCKET hListenSocket = INVALID_SOCKET;2829vector<CNode*> vNodes;30CCriticalSection cs_vNodes;31map<vector<unsigned char>, CAddress> mapAddresses;32CCriticalSection cs_mapAddresses;33map<CInv, CDataStream> mapRelay;34deque<pair<int64, CInv> > vRelayExpiration;35CCriticalSection cs_mapRelay;36map<CInv, int64> mapAlreadyAskedFor;3738// Settings39int fUseProxy = false;40CAddress addrProxy("127.0.0.1:9050");414243444546void CNode::PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd)47{48    // Filter out duplicate requests49    if (pindexBegin == pindexLastGetBlocksBegin && hashEnd == hashLastGetBlocksEnd)50        return;51    pindexLastGetBlocksBegin = pindexBegin;52    hashLastGetBlocksEnd = hashEnd;5354    PushMessage("getblocks", CBlockLocator(pindexBegin), hashEnd);55}565758596061bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet)62{63    hSocketRet = INVALID_SOCKET;6465    SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);66    if (hSocket == INVALID_SOCKET)67        return false;68#ifdef BSD69    int set = 1;70    setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));71#endif7273    bool fRoutable = !(addrConnect.GetByte(3) == 10 || (addrConnect.GetByte(3) == 192 && addrConnect.GetByte(2) == 168));74    bool fProxy = (fUseProxy && fRoutable);75    struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr());7677    if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)78    {79        closesocket(hSocket);80        return false;81    }8283    if (fProxy)84    {85        printf("proxy connecting %s\n", addrConnect.ToStringLog().c_str());86        char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";87        memcpy(pszSocks4IP + 2, &addrConnect.port, 2);88        memcpy(pszSocks4IP + 4, &addrConnect.ip, 4);89        char* pszSocks4 = pszSocks4IP;90        int nSize = sizeof(pszSocks4IP);9192        int ret = send(hSocket, pszSocks4, nSize, MSG_NOSIGNAL);93        if (ret != nSize)94        {95            closesocket(hSocket);96            return error("Error sending to proxy");97        }98        char pchRet[8];99        if (recv(hSocket, pchRet, 8, 0) != 8)100        {101            closesocket(hSocket);102            return error("Error reading proxy response");103        }104        if (pchRet[1] != 0x5a)105        {106            closesocket(hSocket);107            if (pchRet[1] != 0x5b)108                printf("ERROR: Proxy returned error %d\n", pchRet[1]);109            return false;110        }111        printf("proxy connected %s\n", addrConnect.ToStringLog().c_str());112    }113114    hSocketRet = hSocket;115    return true;116}117118119120bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const char* pszKeyword, unsigned int& ipRet)121{122    SOCKET hSocket;123    if (!ConnectSocket(addrConnect, hSocket))124        return error("GetMyExternalIP() : connection to %s failed", addrConnect.ToString().c_str());125126    send(hSocket, pszGet, strlen(pszGet), MSG_NOSIGNAL);127128    string strLine;129    while (RecvLine(hSocket, strLine))130    {131        if (strLine.empty()) // HTTP response is separated from headers by blank line132        {133            loop134            {135                if (!RecvLine(hSocket, strLine))136                {137                    closesocket(hSocket);138                    return false;139                }140                if (pszKeyword == NULL)141                    break;142                if (strLine.find(pszKeyword) != -1)143                {144                    strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));145                    break;146                }147            }148            closesocket(hSocket);149            if (strLine.find("<") != -1)150                strLine = strLine.substr(0, strLine.find("<"));151            strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));152            while (strLine.size() > 0 && isspace(strLine[strLine.size()-1]))153                strLine.resize(strLine.size()-1);154            CAddress addr(strLine.c_str());155            printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());156            if (addr.ip == 0 || addr.ip == INADDR_NONE || !addr.IsRoutable())157                return false;158            ipRet = addr.ip;159            return true;160        }161    }162    closesocket(hSocket);163    return error("GetMyExternalIP() : connection closed");164}165166167bool GetMyExternalIP(unsigned int& ipRet)168{169    CAddress addrConnect;170    const char* pszGet;171    const char* pszKeyword;172173    if (fUseProxy)174        return false;175176    for (int nLookup = 0; nLookup <= 1; nLookup++)177    for (int nHost = 1; nHost <= 2; nHost++)178    {179        if (nHost == 1)180        {181            addrConnect = CAddress("91.198.22.70:80"); // checkip.dyndns.org182183            if (nLookup == 1)184            {185                struct hostent* phostent = gethostbyname("checkip.dyndns.org");186                if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])187                    addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));188            }189190            pszGet = "GET / HTTP/1.1\r\n"191                     "Host: checkip.dyndns.org\r\n"192                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"193                     "Connection: close\r\n"194                     "\r\n";195196            pszKeyword = "Address:";197        }198        else if (nHost == 2)199        {200            addrConnect = CAddress("74.208.43.192:80"); // www.showmyip.com201202            if (nLookup == 1)203            {204                struct hostent* phostent = gethostbyname("www.showmyip.com");205                if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])206                    addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));207            }208209            pszGet = "GET /simple/ HTTP/1.1\r\n"210                     "Host: www.showmyip.com\r\n"211                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"212                     "Connection: close\r\n"213                     "\r\n";214215            pszKeyword = NULL; // Returns just IP address216        }217218        if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))219            return true;220    }221222    return false;223}224225226227228229bool AddAddress(CAddress addr, int64 nTimePenalty)230{231    if (!addr.IsRoutable())232        return false;233    if (addr.ip == addrLocalHost.ip)234        return false;235    addr.nTime = max((int64)0, (int64)addr.nTime - nTimePenalty);236    CRITICAL_BLOCK(cs_mapAddresses)237    {238        map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());239        if (it == mapAddresses.end())240        {241            // New address242            printf("AddAddress(%s)\n", addr.ToStringLog().c_str());243            mapAddresses.insert(make_pair(addr.GetKey(), addr));244            CAddrDB().WriteAddress(addr);245            return true;246        }247        else248        {249            bool fUpdated = false;250            CAddress& addrFound = (*it).second;251            if ((addrFound.nServices | addr.nServices) != addrFound.nServices)252            {253                // Services have been added254                addrFound.nServices |= addr.nServices;255                fUpdated = true;256            }257            bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);258            int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);259            if (addrFound.nTime < addr.nTime - nUpdateInterval)260            {261                // Periodically update most recently seen time262                addrFound.nTime = addr.nTime;263                fUpdated = true;264            }265            if (fUpdated)266                CAddrDB().WriteAddress(addrFound);267        }268    }269    return false;270}271272void AddressCurrentlyConnected(const CAddress& addr)273{274    CRITICAL_BLOCK(cs_mapAddresses)275    {276        // Only if it's been published already277        map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());278        if (it != mapAddresses.end())279        {280            CAddress& addrFound = (*it).second;281            int64 nUpdateInterval = 20 * 60;282            if (addrFound.nTime < GetAdjustedTime() - nUpdateInterval)283            {284                // Periodically update most recently seen time285                addrFound.nTime = GetAdjustedTime();286                CAddrDB addrdb;287                addrdb.WriteAddress(addrFound);288            }289        }290    }291}292293294295296297void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)298{299    // If the dialog might get closed before the reply comes back,300    // call this in the destructor so it doesn't get called after it's deleted.301    CRITICAL_BLOCK(cs_vNodes)302    {303        foreach(CNode* pnode, vNodes)304        {305            CRITICAL_BLOCK(pnode->cs_mapRequests)306            {307                for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)308                {309                    CRequestTracker& tracker = (*mi).second;310                    if (tracker.fn == fn && tracker.param1 == param1)311                        pnode->mapRequests.erase(mi++);312                    else313                        mi++;314                }315            }316        }317    }318}319320321322323324325326//327// Subscription methods for the broadcast and subscription system.328// Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.329//330// The subscription system uses a meet-in-the-middle strategy.331// With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers332// subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.333//334335bool AnySubscribed(unsigned int nChannel)336{337    if (pnodeLocalHost->IsSubscribed(nChannel))338        return true;339    CRITICAL_BLOCK(cs_vNodes)340        foreach(CNode* pnode, vNodes)341            if (pnode->IsSubscribed(nChannel))342                return true;343    return false;344}345346bool CNode::IsSubscribed(unsigned int nChannel)347{348    if (nChannel >= vfSubscribe.size())349        return false;350    return vfSubscribe[nChannel];351}352353void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)354{355    if (nChannel >= vfSubscribe.size())356        return;357358    if (!AnySubscribed(nChannel))359    {360        // Relay subscribe361        CRITICAL_BLOCK(cs_vNodes)362            foreach(CNode* pnode, vNodes)363                if (pnode != this)364                    pnode->PushMessage("subscribe", nChannel, nHops);365    }366367    vfSubscribe[nChannel] = true;368}369370void CNode::CancelSubscribe(unsigned int nChannel)371{372    if (nChannel >= vfSubscribe.size())373        return;374375    // Prevent from relaying cancel if wasn't subscribed376    if (!vfSubscribe[nChannel])377        return;378    vfSubscribe[nChannel] = false;379380    if (!AnySubscribed(nChannel))381    {382        // Relay subscription cancel383        CRITICAL_BLOCK(cs_vNodes)384            foreach(CNode* pnode, vNodes)385                if (pnode != this)386                    pnode->PushMessage("sub-cancel", nChannel);387    }388}389390391392393394395396397398CNode* FindNode(unsigned int ip)399{400    CRITICAL_BLOCK(cs_vNodes)401    {402        foreach(CNode* pnode, vNodes)403            if (pnode->addr.ip == ip)404                return (pnode);405    }406    return NULL;407}408409CNode* FindNode(CAddress addr)410{411    CRITICAL_BLOCK(cs_vNodes)412    {413        foreach(CNode* pnode, vNodes)414            if (pnode->addr == addr)415                return (pnode);416    }417    return NULL;418}419420CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)421{422    if (addrConnect.ip == addrLocalHost.ip)423        return NULL;424425    // Look for an existing connection426    CNode* pnode = FindNode(addrConnect.ip);427    if (pnode)428    {429        if (nTimeout != 0)430            pnode->AddRef(nTimeout);431        else432            pnode->AddRef();433        return pnode;434    }435436    /// debug print437    printf("trying connection %s lastseen=%.1fhrs lasttry=%.1fhrs\n",438        addrConnect.ToStringLog().c_str(),439        (double)(addrConnect.nTime - GetAdjustedTime())/3600.0,440        (double)(addrConnect.nLastTry - GetAdjustedTime())/3600.0);441442    CRITICAL_BLOCK(cs_mapAddresses)443        mapAddresses[addrConnect.GetKey()].nLastTry = GetAdjustedTime();444445    // Connect446    SOCKET hSocket;447    if (ConnectSocket(addrConnect, hSocket))448    {449        /// debug print450        printf("connected %s\n", addrConnect.ToStringLog().c_str());451452        // Set to nonblocking453#ifdef __WXMSW__454        u_long nOne = 1;455        if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)456            printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());457#else458        if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)459            printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);460#endif461462        // Add node463        CNode* pnode = new CNode(hSocket, addrConnect, false);464        if (nTimeout != 0)465            pnode->AddRef(nTimeout);466        else467            pnode->AddRef();468        CRITICAL_BLOCK(cs_vNodes)469            vNodes.push_back(pnode);470471        pnode->nTimeConnected = GetTime();472        return pnode;473    }474    else475    {476        return NULL;477    }478}479480void CNode::CloseSocketDisconnect()481{482    fDisconnect = true;483    if (hSocket != INVALID_SOCKET)484    {485        if (fDebug)486            printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());487        printf("disconnecting node %s\n", addr.ToStringLog().c_str());488        closesocket(hSocket);489        hSocket = INVALID_SOCKET;490    }491}492493void CNode::Cleanup()494{495    // All of a nodes broadcasts and subscriptions are automatically torn down496    // when it goes down, so a node has to stay up to keep its broadcast going.497498    // Cancel subscriptions499    for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)500        if (vfSubscribe[nChannel])501            CancelSubscribe(nChannel);502}503504505506507508509510511512513514515516void ThreadSocketHandler(void* parg)517{518    IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));519    try520    {521        vnThreadsRunning[0]++;522        ThreadSocketHandler2(parg);523        vnThreadsRunning[0]--;524    }525    catch (std::exception& e) {526        vnThreadsRunning[0]--;527        PrintException(&e, "ThreadSocketHandler()");528    } catch (...) {529        vnThreadsRunning[0]--;530        throw; // support pthread_cancel()531    }532    printf("ThreadSocketHandler exiting\n");533}534535void ThreadSocketHandler2(void* parg)536{537    printf("ThreadSocketHandler started\n");538    list<CNode*> vNodesDisconnected;539    int nPrevNodeCount = 0;540541    loop542    {543        //544        // Disconnect nodes545        //546        CRITICAL_BLOCK(cs_vNodes)547        {548            // Disconnect unused nodes549            vector<CNode*> vNodesCopy = vNodes;550            foreach(CNode* pnode, vNodesCopy)551            {552                if (pnode->fDisconnect ||553                    (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))554                {555                    // remove from vNodes556                    vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());557558                    // close socket and cleanup559                    pnode->CloseSocketDisconnect();560                    pnode->Cleanup();561562                    // hold in disconnected pool until all refs are released563                    pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);564                    if (pnode->fNetworkNode || pnode->fInbound)565                        pnode->Release();566                    vNodesDisconnected.push_back(pnode);567                }568            }569570            // Delete disconnected nodes571            list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;572            foreach(CNode* pnode, vNodesDisconnectedCopy)573            {574                // wait until threads are done using it575                if (pnode->GetRefCount() <= 0)576                {577                    bool fDelete = false;578                    TRY_CRITICAL_BLOCK(pnode->cs_vSend)579                     TRY_CRITICAL_BLOCK(pnode->cs_vRecv)580                      TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)581                       TRY_CRITICAL_BLOCK(pnode->cs_inventory)582                        fDelete = true;583                    if (fDelete)584                    {585                        vNodesDisconnected.remove(pnode);586                        delete pnode;587                    }588                }589            }590        }591        if (vNodes.size() != nPrevNodeCount)592        {593            nPrevNodeCount = vNodes.size();594            MainFrameRepaint();595        }596597598        //599        // Find which sockets have data to receive600        //601        struct timeval timeout;602        timeout.tv_sec  = 0;603        timeout.tv_usec = 50000; // frequency to poll pnode->vSend604605        fd_set fdsetRecv;606        fd_set fdsetSend;607        fd_set fdsetError;608        FD_ZERO(&fdsetRecv);609        FD_ZERO(&fdsetSend);610        FD_ZERO(&fdsetError);611        SOCKET hSocketMax = 0;612        FD_SET(hListenSocket, &fdsetRecv);613        hSocketMax = max(hSocketMax, hListenSocket);614        CRITICAL_BLOCK(cs_vNodes)615        {616            foreach(CNode* pnode, vNodes)617            {618                if (pnode->hSocket == INVALID_SOCKET || pnode->hSocket < 0)619                    continue;620                FD_SET(pnode->hSocket, &fdsetRecv);621                FD_SET(pnode->hSocket, &fdsetError);622                hSocketMax = max(hSocketMax, pnode->hSocket);623                TRY_CRITICAL_BLOCK(pnode->cs_vSend)624                    if (!pnode->vSend.empty())625                        FD_SET(pnode->hSocket, &fdsetSend);626            }627        }628629        vnThreadsRunning[0]--;630        int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);631        vnThreadsRunning[0]++;632        if (fShutdown)633            return;634        if (nSelect == SOCKET_ERROR)635        {636            int nErr = WSAGetLastError();637            printf("socket select error %d\n", nErr);638            for (int i = 0; i <= hSocketMax; i++)639                FD_SET(i, &fdsetRecv);640            FD_ZERO(&fdsetSend);641            FD_ZERO(&fdsetError);642            Sleep(timeout.tv_usec/1000);643        }644645646        //647        // Accept new connections648        //649        if (FD_ISSET(hListenSocket, &fdsetRecv))650        {651            struct sockaddr_in sockaddr;652            socklen_t len = sizeof(sockaddr);653            SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);654            CAddress addr(sockaddr);655            if (hSocket == INVALID_SOCKET)656            {657                if (WSAGetLastError() != WSAEWOULDBLOCK)658                    printf("socket error accept failed: %d\n", WSAGetLastError());659            }660            else if (mapArgs.count("-maxconnections") && (int)vNodes.size() >= atoi(mapArgs["-maxconnections"]) - MAX_OUTBOUND_CONNECTIONS)661            {662                closesocket(hSocket);663            }664            else665            {666                printf("accepted connection %s\n", addr.ToStringLog().c_str());667                CNode* pnode = new CNode(hSocket, addr, true);668                pnode->AddRef();669                CRITICAL_BLOCK(cs_vNodes)670                    vNodes.push_back(pnode);671            }672        }673674675        //676        // Service each socket677        //678        vector<CNode*> vNodesCopy;679        CRITICAL_BLOCK(cs_vNodes)680        {681            vNodesCopy = vNodes;682            foreach(CNode* pnode, vNodesCopy)683                pnode->AddRef();684        }685        foreach(CNode* pnode, vNodesCopy)686        {687            if (fShutdown)688                return;689690            //691            // Receive692            //693            if (pnode->hSocket == INVALID_SOCKET)694                continue;695            if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))696            {697                TRY_CRITICAL_BLOCK(pnode->cs_vRecv)698                {699                    CDataStream& vRecv = pnode->vRecv;700                    unsigned int nPos = vRecv.size();701702                    // typical socket buffer is 8K-64K703                    char pchBuf[0x10000];704                    int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);705                    if (nBytes > 0)706                    {707                        vRecv.resize(nPos + nBytes);708                        memcpy(&vRecv[nPos], pchBuf, nBytes);709                        pnode->nLastRecv = GetTime();710                    }711                    else if (nBytes == 0)712                    {713                        // socket closed gracefully714                        if (!pnode->fDisconnect)715                            printf("socket closed\n");716                        pnode->CloseSocketDisconnect();717                    }718                    else if (nBytes < 0)719                    {720                        // error721                        int nErr = WSAGetLastError();722                        if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)723                        {724                            if (!pnode->fDisconnect)725                                printf("socket recv error %d\n", nErr);726                            pnode->CloseSocketDisconnect();727                        }728                    }729                }730            }731732            //733            // Send734            //735            if (pnode->hSocket == INVALID_SOCKET)736                continue;737            if (FD_ISSET(pnode->hSocket, &fdsetSend))738            {739                TRY_CRITICAL_BLOCK(pnode->cs_vSend)740                {741                    CDataStream& vSend = pnode->vSend;742                    if (!vSend.empty())743                    {744                        int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);745                        if (nBytes > 0)746                        {747                            vSend.erase(vSend.begin(), vSend.begin() + nBytes);748                            pnode->nLastSend = GetTime();749                        }750                        else if (nBytes < 0)751                        {752                            // error753                            int nErr = WSAGetLastError();754                            if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)755                            {756                                printf("socket send error %d\n", nErr);757                                pnode->CloseSocketDisconnect();758                            }759                        }760                    }761                }762            }763764            //765            // Inactivity checking766            //767            if (pnode->vSend.empty())768                pnode->nLastSendEmpty = GetTime();769            if (GetTime() - pnode->nTimeConnected > 60)770            {771                if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)772                {773                    printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);774                    pnode->fDisconnect = true;775                }776                else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)777                {778                    printf("socket not sending\n");779                    pnode->fDisconnect = true;780                }781                else if (GetTime() - pnode->nLastRecv > 90*60)782                {783                    printf("socket inactivity timeout\n");784                    pnode->fDisconnect = true;785                }786            }787        }788        CRITICAL_BLOCK(cs_vNodes)789        {790            foreach(CNode* pnode, vNodesCopy)791                pnode->Release();792        }793794        Sleep(10);795    }796}797798799800801802803804805806807808809810unsigned int pnSeed[] =811{812    // 2010/06813    0x35218252, 0x9c9c9618, 0xda6bacad, 0xb9aca862, 0x97c235c6,814    0x146f9562, 0xb67b9e4b, 0x87cf4bc0, 0xb83945d0, 0x984333ad,815    0xbbeec555, 0x6f0eb440, 0xe0005318, 0x7797e460, 0xddc60fcc,816    0xb3bbd24a, 0x1ac85746, 0x641846a6, 0x85ee1155, 0xbb2e7a4c,817    0x9cb8514b, 0xfc342648, 0x62958fae, 0xd0a8c87a, 0xa800795b,818    0xda8c814e, 0x256a0c80, 0x3f23ec63, 0xd565df43, 0x997d9044,819    0xaa121448, 0xbed8688e, 0x59d09a5e, 0xb2931243, 0x3730ba18,820    0xdd3462d0, 0x4e4d1448, 0x171df645, 0x84ee1155,821    0x248ac445, 0x0e634444, 0x0ded1b63, 0x30c01e60,822    0xa2b9a094, 0x29e4fd43, 0x9ce61b4c, 0xdae09744,823824    // 2010/08825    0x5ae6bf43, 0x460be257, 0x7245c0cf, 0x4e0f028d, 0x26501760, 0x38643255, 0x67094f4f, 0x480449b8,826    0x16545143, 0x1f082e5a, 0xaa428018, 0xe411e793, 0x14c1f862, 0x2726105b, 0x9b33ea50, 0xeeef86ca,827    0xe3210d44, 0x0dca8b63, 0x3f9dfb18, 0x860340ad, 0xf33ba17a, 0x9018375c, 0x1de4e353, 0x0fa52dcb,828    0x89c4555b, 0x109cf37b, 0x28c55b40, 0x04c801ae, 0x275c1e80, 0x6f7f745d, 0x7a2a5653, 0xa28e26d8,829    0xa4e65db2, 0x99a06580, 0xf253ba44, 0x82cf6ab8, 0x859c2e8e, 0xf71a815d, 0xc18f1454, 0x71c8a943,830    0x90d24e18, 0x311789b2, 0x74aba645, 0xde0bbfc3, 0xad724fad, 0xbf1ae15e, 0xbaa6fb54, 0x06e4d145,831    0x51528645, 0x72120cd4, 0xd4cfd145, 0x0a7afed8, 0x9b9a5fad, 0x9e9ff45e, 0x10128355, 0xd44e8646,832    0x04a07b47, 0x5fc9d547, 0xe0491e45, 0xbac21b41, 0x7aa31bae, 0x10483c5f, 0x94a23055, 0x73d9dc47,833    0x1a99c247, 0x822fe847, 0x7e57ba48, 0xb19ea843, 0xa60621b2, 0x778cf163, 0x125c6556, 0xf94ba44f,834    0xa61a0948, 0x6c839e4b, 0x29af5348, 0x68d84845, 0x752b95c3, 0xcf0d4663, 0x08e11e56, 0x75109550,835    0x5f24b94c, 0x42426d4d, 0xfbbc0a4c, 0x70a9a246, 0xda7837cb, 0xae2a986d, 0xe283c358, 0x0c7ca954,836    0x8e9bde59, 0x61521760, 0x6884444c, 0xa194e548, 0x9b8809cc, 0x16e96a8f, 0x956ff859, 0xfad5e555,837    0x0ea70c80, 0x5b4ce26d, 0x7984444c, 0x1080d24a, 0x22a686cf, 0x6bf8c2ad, 0xb0f7485f, 0x06b66e56,838    0x668373bc, 0x75506279, 0x3868694e, 0x12a5954b, 0x3a8b62d1, 0xb74fcbad, 0xa7dc3360, 0xc070b359,839    0xa2b87242, 0xc45cab7c, 0x69882050, 0x14a5464b, 0x386acad5, 0x80b85db2, 0x1f78a062, 0xc608c55b,840    0x4257d543, 0x7636ad80, 0x4432d655, 0xb2114d4b, 0x32639bd9, 0xadd75db2, 0x9be5a362, 0x6831bc5e,841    0xf7f77046, 0x8f35ba81, 0x09bb4e59, 0xd0fb6b4e, 0xc5daa445, 0x9c611618, 0x355dcc62, 0xf2cf435e,842    0x31e72c46, 0xdd8a43ad, 0x171f9c5b, 0xb4c2e355, 0xbe8af945, 0x613d3942, 0xe6f9e863, 0x7a3d855f,843    0xa66adc47, 0x261089b2, 0x5a27105b, 0x6c28105b, 0xdd247946, 0xe6c3a445, 0x43a1ec63, 0x99b4dd5f,844    0xb6834347, 0x5e9649bc, 0xf9dd545d, 0x6ae4c15b, 0xa5318a47, 0x7984ec47, 0x93a73b63, 0x0c60195f,845    0xa5c85e4b, 0xa0a36dc2, 0x0739a95e, 0x3d44c15b, 0xfb940f4b, 0xd67c9148, 0x614f9876, 0x0a241c5f,846    0xad9da74c, 0x4459abc8, 0x12e71b5f, 0x1c534a5d, 0x8ff5fc50, 0x2ca8864b, 0xd894fd80, 0x82ab3160,847    0x390d804e, 0x2cf310cc, 0x680dad80, 0x691be15e, 0x5a8f4652, 0xaad0784d, 0x0d2431ad,848};849850851852void ThreadOpenConnections(void* parg)853{854    IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));855    try856    {857        vnThreadsRunning[1]++;858        ThreadOpenConnections2(parg);859        vnThreadsRunning[1]--;860    }861    catch (std::exception& e) {862        vnThreadsRunning[1]--;863        PrintException(&e, "ThreadOpenConnections()");864    } catch (...) {865        vnThreadsRunning[1]--;866        PrintException(NULL, "ThreadOpenConnections()");867    }868    printf("ThreadOpenConnections exiting\n");869}870871void ThreadOpenConnections2(void* parg)872{873    printf("ThreadOpenConnections started\n");874875    // Connect to specific addresses876    if (mapArgs.count("-connect"))877    {878        for (int64 nLoop = 0;; nLoop++)879        {880            foreach(string strAddr, mapMultiArgs["-connect"])881            {882                CAddress addr(strAddr, NODE_NETWORK);883                if (addr.IsValid())884                    OpenNetworkConnection(addr);885                for (int i = 0; i < 10 && i < nLoop; i++)886                {887                    Sleep(500);888                    if (fShutdown)889                        return;890                }891            }892        }893    }894895    // Connect to manually added nodes first896    if (mapArgs.count("-addnode"))897    {898        foreach(string strAddr, mapMultiArgs["-addnode"])899        {900            CAddress addr(strAddr, NODE_NETWORK);901            if (addr.IsValid())902            {903                OpenNetworkConnection(addr);904                Sleep(500);905                if (fShutdown)906                    return;907            }908        }909    }910911    // Initiate network connections912    int64 nStart = GetTime();913    loop914    {915        // Limit outbound connections916        vnThreadsRunning[1]--;917        Sleep(500);918        loop919        {920            int nOutbound = 0;921            CRITICAL_BLOCK(cs_vNodes)922                foreach(CNode* pnode, vNodes)923                    if (!pnode->fInbound)924                        nOutbound++;925            int nMaxOutboundConnections = MAX_OUTBOUND_CONNECTIONS;926            if (mapArgs.count("-maxconnections"))927                nMaxOutboundConnections = min(nMaxOutboundConnections, atoi(mapArgs["-maxconnections"]));928            if (nOutbound < nMaxOutboundConnections)929                break;930            Sleep(2000);931            if (fShutdown)932                return;933        }934        vnThreadsRunning[1]++;935        if (fShutdown)936            return;937938        CRITICAL_BLOCK(cs_mapAddresses)939        {940            // Add seed nodes if IRC isn't working941            static bool fSeedUsed;942            bool fTOR = (fUseProxy && addrProxy.port == htons(9050));943            if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR) && !fTestNet)944            {945                for (int i = 0; i < ARRAYLEN(pnSeed); i++)946                {947                    // It'll only connect to one or two seed nodes because once it connects,948                    // it'll get a pile of addresses with newer timestamps.949                    CAddress addr;950                    addr.ip = pnSeed[i];951                    addr.nTime = 0;952                    AddAddress(addr);953                }954                fSeedUsed = true;955            }956957            if (fSeedUsed && mapAddresses.size() > ARRAYLEN(pnSeed) + 100)958            {959                // Disconnect seed nodes960                set<unsigned int> setSeed(pnSeed, pnSeed + ARRAYLEN(pnSeed));961                static int64 nSeedDisconnected;962                if (nSeedDisconnected == 0)963                {964                    nSeedDisconnected = GetTime();965                    CRITICAL_BLOCK(cs_vNodes)966                        foreach(CNode* pnode, vNodes)967                            if (setSeed.count(pnode->addr.ip))968                                pnode->fDisconnect = true;969                }970971                // Keep setting timestamps to 0 so they won't reconnect972                if (GetTime() - nSeedDisconnected < 60 * 60)973                {974                    foreach(PAIRTYPE(const vector<unsigned char>, CAddress)& item, mapAddresses)975                    {976                        if (setSeed.count(item.second.ip))977                        {978                            item.second.nTime = 0;979                            CAddrDB().WriteAddress(item.second);980                        }981                    }982                }983            }984        }985986987        //988        // Choose an address to connect to based on most recently seen989        //990        CAddress addrConnect;991        int64 nBest = INT64_MIN;992993        // Only connect to one address per a.b.?.? range.994        // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.995        set<unsigned int> setConnected;996        CRITICAL_BLOCK(cs_vNodes)997            foreach(CNode* pnode, vNodes)998                setConnected.insert(pnode->addr.ip & 0x0000ffff);9991000        CRITICAL_BLOCK(cs_mapAddresses)1001        {1002            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)1003            {1004                const CAddress& addr = item.second;1005                if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff))1006                    continue;1007                int64 nSinceLastSeen = GetAdjustedTime() - addr.nTime;1008                int64 nSinceLastTry = GetAdjustedTime() - addr.nLastTry;10091010                // Randomize the order in a deterministic way, putting the standard port first1011                int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.ip * 7789) % (2 * 60 * 60);1012                if (addr.port != GetDefaultPort())1013                    nRandomizer += 2 * 60 * 60;10141015                // Last seen  Base retry frequency1016                //   <1 hour   10 min1017                //    1 hour    1 hour1018                //    4 hours   2 hours1019                //   24 hours   5 hours1020                //   48 hours   7 hours1021                //    7 days   13 hours1022                //   30 days   27 hours1023                //   90 days   46 hours1024                //  365 days   93 hours1025                int64 nDelay = (int64)(3600.0 * sqrt(fabs((double)nSinceLastSeen) / 3600.0) + nRandomizer);10261027                // Fast reconnect for one hour after last seen1028                if (nSinceLastSeen < 60 * 60)1029                    nDelay = 10 * 60;10301031                // Limit retry frequency1032                if (nSinceLastTry < nDelay)1033                    continue;10341035                // If we have IRC, we'll be notified when they first come online,1036                // and again every 24 hours by the refresh broadcast.1037                if (nGotIRCAddresses > 0 && vNodes.size() >= 2 && nSinceLastSeen > 24 * 60 * 60)1038                    continue;10391040                // Only try the old stuff if we don't have enough connections1041                if (vNodes.size() >= 8 && nSinceLastSeen > 24 * 60 * 60)1042                    continue;10431044                // If multiple addresses are ready, prioritize by time since1045                // last seen and time since last tried.1046                int64 nScore = min(nSinceLastTry, (int64)24 * 60 * 60) - nSinceLastSeen - nRandomizer;1047                if (nScore > nBest)1048                {1049                    nBest = nScore;1050                    addrConnect = addr;1051                }1052            }1053        }10541055        if (addrConnect.IsValid())1056            OpenNetworkConnection(addrConnect);1057    }1058}10591060bool OpenNetworkConnection(const CAddress& addrConnect)1061{1062    //1063    // Initiate outbound network connection1064    //1065    if (fShutdown)1066        return false;1067    if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() || FindNode(addrConnect.ip))1068        return false;10691070    vnThreadsRunning[1]--;1071    CNode* pnode = ConnectNode(addrConnect);1072    vnThreadsRunning[1]++;1073    if (fShutdown)1074        return false;1075    if (!pnode)1076        return false;1077    pnode->fNetworkNode = true;10781079    return true;1080}108110821083108410851086108710881089void ThreadMessageHandler(void* parg)1090{1091    IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));1092    try1093    {1094        vnThreadsRunning[2]++;1095        ThreadMessageHandler2(parg);1096        vnThreadsRunning[2]--;1097    }1098    catch (std::exception& e) {1099        vnThreadsRunning[2]--;1100        PrintException(&e, "ThreadMessageHandler()");1101    } catch (...) {1102        vnThreadsRunning[2]--;1103        PrintException(NULL, "ThreadMessageHandler()");1104    }1105    printf("ThreadMessageHandler exiting\n");1106}11071108void ThreadMessageHandler2(void* parg)1109{1110    printf("ThreadMessageHandler started\n");1111    SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);1112    while (!fShutdown)1113    {1114        vector<CNode*> vNodesCopy;1115        CRITICAL_BLOCK(cs_vNodes)1116        {1117            vNodesCopy = vNodes;1118            foreach(CNode* pnode, vNodesCopy)1119                pnode->AddRef();1120        }11211122        // Poll the connected nodes for messages1123        CNode* pnodeTrickle = NULL;1124        if (!vNodesCopy.empty())1125            pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];1126        foreach(CNode* pnode, vNodesCopy)1127        {1128            // Receive messages1129            TRY_CRITICAL_BLOCK(pnode->cs_vRecv)1130                ProcessMessages(pnode);1131            if (fShutdown)1132                return;11331134            // Send messages1135            TRY_CRITICAL_BLOCK(pnode->cs_vSend)1136                SendMessages(pnode, pnode == pnodeTrickle);1137            if (fShutdown)1138                return;1139        }11401141        CRITICAL_BLOCK(cs_vNodes)1142        {1143            foreach(CNode* pnode, vNodesCopy)1144                pnode->Release();1145        }11461147        // Wait and allow messages to bunch up.1148        // Reduce vnThreadsRunning so StopNode has permission to exit while1149        // we're sleeping, but we must always check fShutdown after doing this.1150        vnThreadsRunning[2]--;1151        Sleep(100);1152        if (fRequestShutdown)1153            Shutdown(NULL);1154        vnThreadsRunning[2]++;1155        if (fShutdown)1156            return;1157    }1158}1159116011611162116311641165116611671168bool BindListenPort(string& strError)1169{1170    strError = "";1171    int nOne = 1;1172    addrLocalHost.port = GetDefaultPort();11731174#ifdef __WXMSW__1175    // Initialize Windows Sockets1176    WSADATA wsadata;1177    int ret = WSAStartup(MAKEWORD(2,2), &wsadata);1178    if (ret != NO_ERROR)1179    {1180        strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);1181        printf("%s\n", strError.c_str());1182        return false;1183    }1184#endif11851186    // Create socket for listening for incoming connections1187    hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);1188    if (hListenSocket == INVALID_SOCKET)1189    {1190        strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());1191        printf("%s\n", strError.c_str());1192        return false;1193    }11941195#ifdef BSD1196    // Different way of disabling SIGPIPE on BSD1197    setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));1198#endif11991200#ifndef __WXMSW__1201    // Allow binding if the port is still in TIME_WAIT state after1202    // the program was closed and restarted.  Not an issue on windows.1203    setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));1204#endif12051206#ifdef __WXMSW__1207    // Set to nonblocking, incoming connections will also inherit this1208    if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)1209#else1210    if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)1211#endif1212    {1213        strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());1214        printf("%s\n", strError.c_str());1215        return false;1216    }12171218    // The sockaddr_in structure specifies the address family,1219    // IP address, and port for the socket that is being bound1220    struct sockaddr_in sockaddr;1221    memset(&sockaddr, 0, sizeof(sockaddr));1222    sockaddr.sin_family = AF_INET;1223    sockaddr.sin_addr.s_addr = INADDR_ANY; // bind to all IPs on this computer1224    sockaddr.sin_port = GetDefaultPort();1225    if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)1226    {1227        int nErr = WSAGetLastError();1228        if (nErr == WSAEADDRINUSE)1229            strError = strprintf(_("Unable to bind to port %d on this computer.  Bitcoin is probably already running."), ntohs(sockaddr.sin_port));1230        else1231            strError = strprintf("Error: Unable to bind to port %d on this computer (bind returned error %d)", ntohs(sockaddr.sin_port), nErr);1232        printf("%s\n", strError.c_str());1233        return false;1234    }1235    printf("Bound to port %d\n", ntohs(sockaddr.sin_port));12361237    // Listen for incoming connections1238    if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)1239    {1240        strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());1241        printf("%s\n", strError.c_str());1242        return false;1243    }12441245    return true;1246}12471248void StartNode(void* parg)1249{1250    if (pnodeLocalHost == NULL)1251        pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress("127.0.0.1", nLocalServices));12521253#ifdef __WXMSW__1254    // Get local host ip1255    char pszHostName[1000] = "";1256    if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)1257    {1258        struct hostent* phostent = gethostbyname(pszHostName);1259        if (phostent)1260        {1261            // Take the first IP that isn't loopback 127.x.x.x1262            for (int i = 0; phostent->h_addr_list[i] != NULL; i++)1263                printf("host ip %d: %s\n", i, CAddress(*(unsigned int*)phostent->h_addr_list[i]).ToStringIP().c_str());1264            for (int i = 0; phostent->h_addr_list[i] != NULL; i++)1265            {1266                CAddress addr(*(unsigned int*)phostent->h_addr_list[i], GetDefaultPort(), nLocalServices);1267                if (addr.IsValid() && addr.GetByte(3) != 127)1268                {1269                    addrLocalHost = addr;1270                    break;1271                }1272            }1273        }1274    }1275#else1276    // Get local host ip1277    struct ifaddrs* myaddrs;1278    if (getifaddrs(&myaddrs) == 0)1279    {1280        for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)1281        {1282            if (ifa->ifa_addr == NULL) continue;1283            if ((ifa->ifa_flags & IFF_UP) == 0) continue;1284            if (strcmp(ifa->ifa_name, "lo") == 0) continue;1285            if (strcmp(ifa->ifa_name, "lo0") == 0) continue;1286            char pszIP[100];1287            if (ifa->ifa_addr->sa_family == AF_INET)1288            {1289                struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);1290                if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s4->sin_addr), pszIP, sizeof(pszIP)) != NULL)1291                    printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP);12921293                // Take the first IP that isn't loopback 127.x.x.x1294                CAddress addr(*(unsigned int*)&s4->sin_addr, GetDefaultPort(), nLocalServices);1295                if (addr.IsValid() && addr.GetByte(3) != 127)1296                {1297                    addrLocalHost = addr;1298                    break;1299                }1300            }1301            else if (ifa->ifa_addr->sa_family == AF_INET6)1302            {1303                struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);1304                if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s6->sin6_addr), pszIP, sizeof(pszIP)) != NULL)1305                    printf("ipv6 %s: %s\n", ifa->ifa_name, pszIP);1306            }1307        }1308        freeifaddrs(myaddrs);1309    }1310#endif1311    printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());13121313    // Get our external IP address for incoming connections1314    if (fUseProxy)1315    {1316        // Proxies can't take incoming connections1317        addrLocalHost.ip = CAddress("0.0.0.0").ip;1318        printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());1319    }1320    else1321    {1322        if (addrIncoming.IsValid())1323            addrLocalHost.ip = addrIncoming.ip;13241325        if (GetMyExternalIP(addrLocalHost.ip))1326        {1327            addrIncoming = addrLocalHost;1328            CWalletDB().WriteSetting("addrIncoming", addrIncoming);1329            printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());1330        }1331    }13321333    //1334    // Start threads1335    //13361337    // Get addresses from IRC and advertise ours1338    if (!CreateThread(ThreadIRCSeed, NULL))1339        printf("Error: CreateThread(ThreadIRCSeed) failed\n");13401341    // Send and receive from sockets, accept connections1342    pthread_t hThreadSocketHandler = CreateThread(ThreadSocketHandler, NULL, true);13431344    // Initiate outbound connections1345    if (!CreateThread(ThreadOpenConnections, NULL))1346        printf("Error: CreateThread(ThreadOpenConnections) failed\n");13471348    // Process messages1349    if (!CreateThread(ThreadMessageHandler, NULL))1350        printf("Error: CreateThread(ThreadMessageHandler) failed\n");13511352    // Generate coins in the background1353    GenerateBitcoins(fGenerateBitcoins);1354}13551356bool StopNode()1357{1358    printf("StopNode()\n");1359    fShutdown = true;1360    nTransactionsUpdated++;1361    int64 nStart = GetTime();1362    while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0)1363    {1364        if (GetTime() - nStart > 20)1365            break;1366        Sleep(20);1367    }1368    if (vnThreadsRunning[0] > 0) printf("ThreadSocketHandler still running\n");1369    if (vnThreadsRunning[1] > 0) printf("ThreadOpenConnections still running\n");1370    if (vnThreadsRunning[2] > 0) printf("ThreadMessageHandler still running\n");1371    if (vnThreadsRunning[3] > 0) printf("ThreadBitcoinMiner still running\n");1372    if (vnThreadsRunning[4] > 0) printf("ThreadRPCServer still running\n");1373    while (vnThreadsRunning[2] > 0 || vnThreadsRunning[4] > 0)1374        Sleep(20);1375    Sleep(50);13761377    return true;1378}13791380class CNetCleanup1381{1382public:1383    CNetCleanup()1384    {1385    }1386    ~CNetCleanup()1387    {1388        // Close sockets1389        foreach(CNode* pnode, vNodes)1390            if (pnode->hSocket != INVALID_SOCKET)1391                closesocket(pnode->hSocket);1392        if (hListenSocket != INVALID_SOCKET)1393            if (closesocket(hListenSocket) == SOCKET_ERROR)1394                printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());13951396#ifdef __WXMSW__1397        // Shutdown Windows Sockets1398        WSACleanup();1399#endif1400    }1401}1402instance_of_cnetcleanup;

Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.

0:000:00