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 r202 (last Satoshi commit) · 2010-12-15

net.cpp

1,427 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}165166// We now get our external IP from the IRC server first and only use this as a backup167bool 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        // We should be phasing out our use of sites like these.  If we need180        // replacements, we should ask for volunteers to put this simple181        // php file on their webserver that prints the client IP:182        //  <?php echo $_SERVER["REMOTE_ADDR"]; ?>183        if (nHost == 1)184        {185            addrConnect = CAddress("91.198.22.70:80"); // checkip.dyndns.org186187            if (nLookup == 1)188            {189                struct hostent* phostent = gethostbyname("checkip.dyndns.org");190                if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])191                    addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));192            }193194            pszGet = "GET / HTTP/1.1\r\n"195                     "Host: checkip.dyndns.org\r\n"196                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"197                     "Connection: close\r\n"198                     "\r\n";199200            pszKeyword = "Address:";201        }202        else if (nHost == 2)203        {204            addrConnect = CAddress("74.208.43.192:80"); // www.showmyip.com205206            if (nLookup == 1)207            {208                struct hostent* phostent = gethostbyname("www.showmyip.com");209                if (phostent && phostent->h_addr_list && phostent->h_addr_list[0])210                    addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));211            }212213            pszGet = "GET /simple/ HTTP/1.1\r\n"214                     "Host: www.showmyip.com\r\n"215                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"216                     "Connection: close\r\n"217                     "\r\n";218219            pszKeyword = NULL; // Returns just IP address220        }221222        if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))223            return true;224    }225226    return false;227}228229void ThreadGetMyExternalIP(void* parg)230{231    // Wait for IRC to get it first232    if (!GetBoolArg("-noirc"))233    {234        for (int i = 0; i < 2 * 60; i++)235        {236            Sleep(1000);237            if (fGotExternalIP || fShutdown)238                return;239        }240    }241242    // Fallback in case IRC fails to get it243    if (GetMyExternalIP(addrLocalHost.ip))244    {245        printf("GetMyExternalIP() returned %s\n", addrLocalHost.ToStringIP().c_str());246        if (addrLocalHost.IsRoutable())247        {248            // If we already connected to a few before we had our IP, go back and addr them.249            // setAddrKnown automatically filters any duplicate sends.250            CAddress addr(addrLocalHost);251            addr.nTime = GetAdjustedTime();252            CRITICAL_BLOCK(cs_vNodes)253                foreach(CNode* pnode, vNodes)254                    pnode->PushAddress(addr);255        }256    }257}258259260261262263bool AddAddress(CAddress addr, int64 nTimePenalty)264{265    if (!addr.IsRoutable())266        return false;267    if (addr.ip == addrLocalHost.ip)268        return false;269    addr.nTime = max((int64)0, (int64)addr.nTime - nTimePenalty);270    CRITICAL_BLOCK(cs_mapAddresses)271    {272        map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());273        if (it == mapAddresses.end())274        {275            // New address276            printf("AddAddress(%s)\n", addr.ToStringLog().c_str());277            mapAddresses.insert(make_pair(addr.GetKey(), addr));278            CAddrDB().WriteAddress(addr);279            return true;280        }281        else282        {283            bool fUpdated = false;284            CAddress& addrFound = (*it).second;285            if ((addrFound.nServices | addr.nServices) != addrFound.nServices)286            {287                // Services have been added288                addrFound.nServices |= addr.nServices;289                fUpdated = true;290            }291            bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);292            int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);293            if (addrFound.nTime < addr.nTime - nUpdateInterval)294            {295                // Periodically update most recently seen time296                addrFound.nTime = addr.nTime;297                fUpdated = true;298            }299            if (fUpdated)300                CAddrDB().WriteAddress(addrFound);301        }302    }303    return false;304}305306void AddressCurrentlyConnected(const CAddress& addr)307{308    CRITICAL_BLOCK(cs_mapAddresses)309    {310        // Only if it's been published already311        map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());312        if (it != mapAddresses.end())313        {314            CAddress& addrFound = (*it).second;315            int64 nUpdateInterval = 20 * 60;316            if (addrFound.nTime < GetAdjustedTime() - nUpdateInterval)317            {318                // Periodically update most recently seen time319                addrFound.nTime = GetAdjustedTime();320                CAddrDB addrdb;321                addrdb.WriteAddress(addrFound);322            }323        }324    }325}326327328329330331void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)332{333    // If the dialog might get closed before the reply comes back,334    // call this in the destructor so it doesn't get called after it's deleted.335    CRITICAL_BLOCK(cs_vNodes)336    {337        foreach(CNode* pnode, vNodes)338        {339            CRITICAL_BLOCK(pnode->cs_mapRequests)340            {341                for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)342                {343                    CRequestTracker& tracker = (*mi).second;344                    if (tracker.fn == fn && tracker.param1 == param1)345                        pnode->mapRequests.erase(mi++);346                    else347                        mi++;348                }349            }350        }351    }352}353354355356357358359360//361// Subscription methods for the broadcast and subscription system.362// Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.363//364// The subscription system uses a meet-in-the-middle strategy.365// With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers366// subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.367//368369bool AnySubscribed(unsigned int nChannel)370{371    if (pnodeLocalHost->IsSubscribed(nChannel))372        return true;373    CRITICAL_BLOCK(cs_vNodes)374        foreach(CNode* pnode, vNodes)375            if (pnode->IsSubscribed(nChannel))376                return true;377    return false;378}379380bool CNode::IsSubscribed(unsigned int nChannel)381{382    if (nChannel >= vfSubscribe.size())383        return false;384    return vfSubscribe[nChannel];385}386387void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)388{389    if (nChannel >= vfSubscribe.size())390        return;391392    if (!AnySubscribed(nChannel))393    {394        // Relay subscribe395        CRITICAL_BLOCK(cs_vNodes)396            foreach(CNode* pnode, vNodes)397                if (pnode != this)398                    pnode->PushMessage("subscribe", nChannel, nHops);399    }400401    vfSubscribe[nChannel] = true;402}403404void CNode::CancelSubscribe(unsigned int nChannel)405{406    if (nChannel >= vfSubscribe.size())407        return;408409    // Prevent from relaying cancel if wasn't subscribed410    if (!vfSubscribe[nChannel])411        return;412    vfSubscribe[nChannel] = false;413414    if (!AnySubscribed(nChannel))415    {416        // Relay subscription cancel417        CRITICAL_BLOCK(cs_vNodes)418            foreach(CNode* pnode, vNodes)419                if (pnode != this)420                    pnode->PushMessage("sub-cancel", nChannel);421    }422}423424425426427428429430431432CNode* FindNode(unsigned int ip)433{434    CRITICAL_BLOCK(cs_vNodes)435    {436        foreach(CNode* pnode, vNodes)437            if (pnode->addr.ip == ip)438                return (pnode);439    }440    return NULL;441}442443CNode* FindNode(CAddress addr)444{445    CRITICAL_BLOCK(cs_vNodes)446    {447        foreach(CNode* pnode, vNodes)448            if (pnode->addr == addr)449                return (pnode);450    }451    return NULL;452}453454CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)455{456    if (addrConnect.ip == addrLocalHost.ip)457        return NULL;458459    // Look for an existing connection460    CNode* pnode = FindNode(addrConnect.ip);461    if (pnode)462    {463        if (nTimeout != 0)464            pnode->AddRef(nTimeout);465        else466            pnode->AddRef();467        return pnode;468    }469470    /// debug print471    printf("trying connection %s lastseen=%.1fhrs lasttry=%.1fhrs\n",472        addrConnect.ToStringLog().c_str(),473        (double)(addrConnect.nTime - GetAdjustedTime())/3600.0,474        (double)(addrConnect.nLastTry - GetAdjustedTime())/3600.0);475476    CRITICAL_BLOCK(cs_mapAddresses)477        mapAddresses[addrConnect.GetKey()].nLastTry = GetAdjustedTime();478479    // Connect480    SOCKET hSocket;481    if (ConnectSocket(addrConnect, hSocket))482    {483        /// debug print484        printf("connected %s\n", addrConnect.ToStringLog().c_str());485486        // Set to nonblocking487#ifdef __WXMSW__488        u_long nOne = 1;489        if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)490            printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());491#else492        if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)493            printf("ConnectSocket() : fcntl nonblocking setting failed, error %d\n", errno);494#endif495496        // Add node497        CNode* pnode = new CNode(hSocket, addrConnect, false);498        if (nTimeout != 0)499            pnode->AddRef(nTimeout);500        else501            pnode->AddRef();502        CRITICAL_BLOCK(cs_vNodes)503            vNodes.push_back(pnode);504505        pnode->nTimeConnected = GetTime();506        return pnode;507    }508    else509    {510        return NULL;511    }512}513514void CNode::CloseSocketDisconnect()515{516    fDisconnect = true;517    if (hSocket != INVALID_SOCKET)518    {519        if (fDebug)520            printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());521        printf("disconnecting node %s\n", addr.ToStringLog().c_str());522        closesocket(hSocket);523        hSocket = INVALID_SOCKET;524    }525}526527void CNode::Cleanup()528{529    // All of a nodes broadcasts and subscriptions are automatically torn down530    // when it goes down, so a node has to stay up to keep its broadcast going.531532    // Cancel subscriptions533    for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)534        if (vfSubscribe[nChannel])535            CancelSubscribe(nChannel);536}537538539540541542543544545546547548549550void ThreadSocketHandler(void* parg)551{552    IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));553    try554    {555        vnThreadsRunning[0]++;556        ThreadSocketHandler2(parg);557        vnThreadsRunning[0]--;558    }559    catch (std::exception& e) {560        vnThreadsRunning[0]--;561        PrintException(&e, "ThreadSocketHandler()");562    } catch (...) {563        vnThreadsRunning[0]--;564        throw; // support pthread_cancel()565    }566    printf("ThreadSocketHandler exiting\n");567}568569void ThreadSocketHandler2(void* parg)570{571    printf("ThreadSocketHandler started\n");572    list<CNode*> vNodesDisconnected;573    int nPrevNodeCount = 0;574575    loop576    {577        //578        // Disconnect nodes579        //580        CRITICAL_BLOCK(cs_vNodes)581        {582            // Disconnect unused nodes583            vector<CNode*> vNodesCopy = vNodes;584            foreach(CNode* pnode, vNodesCopy)585            {586                if (pnode->fDisconnect ||587                    (pnode->GetRefCount() <= 0 && pnode->vRecv.empty() && pnode->vSend.empty()))588                {589                    // remove from vNodes590                    vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());591592                    // close socket and cleanup593                    pnode->CloseSocketDisconnect();594                    pnode->Cleanup();595596                    // hold in disconnected pool until all refs are released597                    pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 15 * 60);598                    if (pnode->fNetworkNode || pnode->fInbound)599                        pnode->Release();600                    vNodesDisconnected.push_back(pnode);601                }602            }603604            // Delete disconnected nodes605            list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;606            foreach(CNode* pnode, vNodesDisconnectedCopy)607            {608                // wait until threads are done using it609                if (pnode->GetRefCount() <= 0)610                {611                    bool fDelete = false;612                    TRY_CRITICAL_BLOCK(pnode->cs_vSend)613                     TRY_CRITICAL_BLOCK(pnode->cs_vRecv)614                      TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)615                       TRY_CRITICAL_BLOCK(pnode->cs_inventory)616                        fDelete = true;617                    if (fDelete)618                    {619                        vNodesDisconnected.remove(pnode);620                        delete pnode;621                    }622                }623            }624        }625        if (vNodes.size() != nPrevNodeCount)626        {627            nPrevNodeCount = vNodes.size();628            MainFrameRepaint();629        }630631632        //633        // Find which sockets have data to receive634        //635        struct timeval timeout;636        timeout.tv_sec  = 0;637        timeout.tv_usec = 50000; // frequency to poll pnode->vSend638639        fd_set fdsetRecv;640        fd_set fdsetSend;641        fd_set fdsetError;642        FD_ZERO(&fdsetRecv);643        FD_ZERO(&fdsetSend);644        FD_ZERO(&fdsetError);645        SOCKET hSocketMax = 0;646        FD_SET(hListenSocket, &fdsetRecv);647        hSocketMax = max(hSocketMax, hListenSocket);648        CRITICAL_BLOCK(cs_vNodes)649        {650            foreach(CNode* pnode, vNodes)651            {652                if (pnode->hSocket == INVALID_SOCKET || pnode->hSocket < 0)653                    continue;654                FD_SET(pnode->hSocket, &fdsetRecv);655                FD_SET(pnode->hSocket, &fdsetError);656                hSocketMax = max(hSocketMax, pnode->hSocket);657                TRY_CRITICAL_BLOCK(pnode->cs_vSend)658                    if (!pnode->vSend.empty())659                        FD_SET(pnode->hSocket, &fdsetSend);660            }661        }662663        vnThreadsRunning[0]--;664        int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, &fdsetError, &timeout);665        vnThreadsRunning[0]++;666        if (fShutdown)667            return;668        if (nSelect == SOCKET_ERROR)669        {670            int nErr = WSAGetLastError();671            printf("socket select error %d\n", nErr);672            for (int i = 0; i <= hSocketMax; i++)673                FD_SET(i, &fdsetRecv);674            FD_ZERO(&fdsetSend);675            FD_ZERO(&fdsetError);676            Sleep(timeout.tv_usec/1000);677        }678679680        //681        // Accept new connections682        //683        if (FD_ISSET(hListenSocket, &fdsetRecv))684        {685            struct sockaddr_in sockaddr;686            socklen_t len = sizeof(sockaddr);687            SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);688            CAddress addr(sockaddr);689            if (hSocket == INVALID_SOCKET)690            {691                if (WSAGetLastError() != WSAEWOULDBLOCK)692                    printf("socket error accept failed: %d\n", WSAGetLastError());693            }694            else if (mapArgs.count("-maxconnections") && (int)vNodes.size() >= atoi(mapArgs["-maxconnections"]) - MAX_OUTBOUND_CONNECTIONS)695            {696                closesocket(hSocket);697            }698            else699            {700                printf("accepted connection %s\n", addr.ToStringLog().c_str());701                CNode* pnode = new CNode(hSocket, addr, true);702                pnode->AddRef();703                CRITICAL_BLOCK(cs_vNodes)704                    vNodes.push_back(pnode);705            }706        }707708709        //710        // Service each socket711        //712        vector<CNode*> vNodesCopy;713        CRITICAL_BLOCK(cs_vNodes)714        {715            vNodesCopy = vNodes;716            foreach(CNode* pnode, vNodesCopy)717                pnode->AddRef();718        }719        foreach(CNode* pnode, vNodesCopy)720        {721            if (fShutdown)722                return;723724            //725            // Receive726            //727            if (pnode->hSocket == INVALID_SOCKET)728                continue;729            if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError))730            {731                TRY_CRITICAL_BLOCK(pnode->cs_vRecv)732                {733                    CDataStream& vRecv = pnode->vRecv;734                    unsigned int nPos = vRecv.size();735736                    // typical socket buffer is 8K-64K737                    char pchBuf[0x10000];738                    int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);739                    if (nBytes > 0)740                    {741                        vRecv.resize(nPos + nBytes);742                        memcpy(&vRecv[nPos], pchBuf, nBytes);743                        pnode->nLastRecv = GetTime();744                    }745                    else if (nBytes == 0)746                    {747                        // socket closed gracefully748                        if (!pnode->fDisconnect)749                            printf("socket closed\n");750                        pnode->CloseSocketDisconnect();751                    }752                    else if (nBytes < 0)753                    {754                        // error755                        int nErr = WSAGetLastError();756                        if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)757                        {758                            if (!pnode->fDisconnect)759                                printf("socket recv error %d\n", nErr);760                            pnode->CloseSocketDisconnect();761                        }762                    }763                }764            }765766            //767            // Send768            //769            if (pnode->hSocket == INVALID_SOCKET)770                continue;771            if (FD_ISSET(pnode->hSocket, &fdsetSend))772            {773                TRY_CRITICAL_BLOCK(pnode->cs_vSend)774                {775                    CDataStream& vSend = pnode->vSend;776                    if (!vSend.empty())777                    {778                        int nBytes = send(pnode->hSocket, &vSend[0], vSend.size(), MSG_NOSIGNAL | MSG_DONTWAIT);779                        if (nBytes > 0)780                        {781                            vSend.erase(vSend.begin(), vSend.begin() + nBytes);782                            pnode->nLastSend = GetTime();783                        }784                        else if (nBytes < 0)785                        {786                            // error787                            int nErr = WSAGetLastError();788                            if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)789                            {790                                printf("socket send error %d\n", nErr);791                                pnode->CloseSocketDisconnect();792                            }793                        }794                    }795                }796            }797798            //799            // Inactivity checking800            //801            if (pnode->vSend.empty())802                pnode->nLastSendEmpty = GetTime();803            if (GetTime() - pnode->nTimeConnected > 60)804            {805                if (pnode->nLastRecv == 0 || pnode->nLastSend == 0)806                {807                    printf("socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0);808                    pnode->fDisconnect = true;809                }810                else if (GetTime() - pnode->nLastSend > 90*60 && GetTime() - pnode->nLastSendEmpty > 90*60)811                {812                    printf("socket not sending\n");813                    pnode->fDisconnect = true;814                }815                else if (GetTime() - pnode->nLastRecv > 90*60)816                {817                    printf("socket inactivity timeout\n");818                    pnode->fDisconnect = true;819                }820            }821        }822        CRITICAL_BLOCK(cs_vNodes)823        {824            foreach(CNode* pnode, vNodesCopy)825                pnode->Release();826        }827828        Sleep(10);829    }830}831832833834835836837838839840841842843844unsigned int pnSeed[] =845{846    // 2010/06847    0x35218252, 0x9c9c9618, 0xda6bacad, 0xb9aca862, 0x97c235c6,848    0x146f9562, 0xb67b9e4b, 0x87cf4bc0, 0xb83945d0, 0x984333ad,849    0xbbeec555, 0x6f0eb440, 0xe0005318, 0x7797e460, 0xddc60fcc,850    0xb3bbd24a, 0x1ac85746, 0x641846a6, 0x85ee1155, 0xbb2e7a4c,851    0x9cb8514b, 0xfc342648, 0x62958fae, 0xd0a8c87a, 0xa800795b,852    0xda8c814e, 0x256a0c80, 0x3f23ec63, 0xd565df43, 0x997d9044,853    0xaa121448, 0xbed8688e, 0x59d09a5e, 0xb2931243, 0x3730ba18,854    0xdd3462d0, 0x4e4d1448, 0x171df645, 0x84ee1155,855    0x248ac445, 0x0e634444, 0x0ded1b63, 0x30c01e60,856    0xa2b9a094, 0x29e4fd43, 0x9ce61b4c, 0xdae09744,857858    // 2010/08859    0x5ae6bf43, 0x460be257, 0x7245c0cf, 0x4e0f028d, 0x26501760, 0x38643255, 0x67094f4f, 0x480449b8,860    0x16545143, 0x1f082e5a, 0xaa428018, 0xe411e793, 0x14c1f862, 0x2726105b, 0x9b33ea50, 0xeeef86ca,861    0xe3210d44, 0x0dca8b63, 0x3f9dfb18, 0x860340ad, 0xf33ba17a, 0x9018375c, 0x1de4e353, 0x0fa52dcb,862    0x89c4555b, 0x109cf37b, 0x28c55b40, 0x04c801ae, 0x275c1e80, 0x6f7f745d, 0x7a2a5653, 0xa28e26d8,863    0xa4e65db2, 0x99a06580, 0xf253ba44, 0x82cf6ab8, 0x859c2e8e, 0xf71a815d, 0xc18f1454, 0x71c8a943,864    0x90d24e18, 0x311789b2, 0x74aba645, 0xde0bbfc3, 0xad724fad, 0xbf1ae15e, 0xbaa6fb54, 0x06e4d145,865    0x51528645, 0x72120cd4, 0xd4cfd145, 0x0a7afed8, 0x9b9a5fad, 0x9e9ff45e, 0x10128355, 0xd44e8646,866    0x04a07b47, 0x5fc9d547, 0xe0491e45, 0xbac21b41, 0x7aa31bae, 0x10483c5f, 0x94a23055, 0x73d9dc47,867    0x1a99c247, 0x822fe847, 0x7e57ba48, 0xb19ea843, 0xa60621b2, 0x778cf163, 0x125c6556, 0xf94ba44f,868    0xa61a0948, 0x6c839e4b, 0x29af5348, 0x68d84845, 0x752b95c3, 0xcf0d4663, 0x08e11e56, 0x75109550,869    0x5f24b94c, 0x42426d4d, 0xfbbc0a4c, 0x70a9a246, 0xda7837cb, 0xae2a986d, 0xe283c358, 0x0c7ca954,870    0x8e9bde59, 0x61521760, 0x6884444c, 0xa194e548, 0x9b8809cc, 0x16e96a8f, 0x956ff859, 0xfad5e555,871    0x0ea70c80, 0x5b4ce26d, 0x7984444c, 0x1080d24a, 0x22a686cf, 0x6bf8c2ad, 0xb0f7485f, 0x06b66e56,872    0x668373bc, 0x75506279, 0x3868694e, 0x12a5954b, 0x3a8b62d1, 0xb74fcbad, 0xa7dc3360, 0xc070b359,873    0xa2b87242, 0xc45cab7c, 0x69882050, 0x14a5464b, 0x386acad5, 0x80b85db2, 0x1f78a062, 0xc608c55b,874    0x4257d543, 0x7636ad80, 0x4432d655, 0xb2114d4b, 0x32639bd9, 0xadd75db2, 0x9be5a362, 0x6831bc5e,875    0xf7f77046, 0x8f35ba81, 0x09bb4e59, 0xd0fb6b4e, 0xc5daa445, 0x9c611618, 0x355dcc62, 0xf2cf435e,876    0x31e72c46, 0xdd8a43ad, 0x171f9c5b, 0xb4c2e355, 0xbe8af945, 0x613d3942, 0xe6f9e863, 0x7a3d855f,877    0xa66adc47, 0x261089b2, 0x5a27105b, 0x6c28105b, 0xdd247946, 0xe6c3a445, 0x43a1ec63, 0x99b4dd5f,878    0xb6834347, 0x5e9649bc, 0xf9dd545d, 0x6ae4c15b, 0xa5318a47, 0x7984ec47, 0x93a73b63, 0x0c60195f,879    0xa5c85e4b, 0xa0a36dc2, 0x0739a95e, 0x3d44c15b, 0xfb940f4b, 0xd67c9148, 0x614f9876, 0x0a241c5f,880    0xad9da74c, 0x4459abc8, 0x12e71b5f, 0x1c534a5d, 0x8ff5fc50, 0x2ca8864b, 0xd894fd80, 0x82ab3160,881    0x390d804e, 0x2cf310cc, 0x680dad80, 0x691be15e, 0x5a8f4652, 0xaad0784d, 0x0d2431ad,882};883884885886void ThreadOpenConnections(void* parg)887{888    IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));889    try890    {891        vnThreadsRunning[1]++;892        ThreadOpenConnections2(parg);893        vnThreadsRunning[1]--;894    }895    catch (std::exception& e) {896        vnThreadsRunning[1]--;897        PrintException(&e, "ThreadOpenConnections()");898    } catch (...) {899        vnThreadsRunning[1]--;900        PrintException(NULL, "ThreadOpenConnections()");901    }902    printf("ThreadOpenConnections exiting\n");903}904905void ThreadOpenConnections2(void* parg)906{907    printf("ThreadOpenConnections started\n");908909    // Connect to specific addresses910    if (mapArgs.count("-connect"))911    {912        for (int64 nLoop = 0;; nLoop++)913        {914            foreach(string strAddr, mapMultiArgs["-connect"])915            {916                CAddress addr(strAddr, NODE_NETWORK);917                if (addr.IsValid())918                    OpenNetworkConnection(addr);919                for (int i = 0; i < 10 && i < nLoop; i++)920                {921                    Sleep(500);922                    if (fShutdown)923                        return;924                }925            }926        }927    }928929    // Connect to manually added nodes first930    if (mapArgs.count("-addnode"))931    {932        foreach(string strAddr, mapMultiArgs["-addnode"])933        {934            CAddress addr(strAddr, NODE_NETWORK);935            if (addr.IsValid())936            {937                OpenNetworkConnection(addr);938                Sleep(500);939                if (fShutdown)940                    return;941            }942        }943    }944945    // Initiate network connections946    int64 nStart = GetTime();947    loop948    {949        // Limit outbound connections950        vnThreadsRunning[1]--;951        Sleep(500);952        loop953        {954            int nOutbound = 0;955            CRITICAL_BLOCK(cs_vNodes)956                foreach(CNode* pnode, vNodes)957                    if (!pnode->fInbound)958                        nOutbound++;959            int nMaxOutboundConnections = MAX_OUTBOUND_CONNECTIONS;960            if (mapArgs.count("-maxconnections"))961                nMaxOutboundConnections = min(nMaxOutboundConnections, atoi(mapArgs["-maxconnections"]));962            if (nOutbound < nMaxOutboundConnections)963                break;964            Sleep(2000);965            if (fShutdown)966                return;967        }968        vnThreadsRunning[1]++;969        if (fShutdown)970            return;971972        CRITICAL_BLOCK(cs_mapAddresses)973        {974            // Add seed nodes if IRC isn't working975            static bool fSeedUsed;976            bool fTOR = (fUseProxy && addrProxy.port == htons(9050));977            if (mapAddresses.empty() && (GetTime() - nStart > 60 || fTOR) && !fTestNet)978            {979                for (int i = 0; i < ARRAYLEN(pnSeed); i++)980                {981                    // It'll only connect to one or two seed nodes because once it connects,982                    // it'll get a pile of addresses with newer timestamps.983                    CAddress addr;984                    addr.ip = pnSeed[i];985                    addr.nTime = 0;986                    AddAddress(addr);987                }988                fSeedUsed = true;989            }990991            if (fSeedUsed && mapAddresses.size() > ARRAYLEN(pnSeed) + 100)992            {993                // Disconnect seed nodes994                set<unsigned int> setSeed(pnSeed, pnSeed + ARRAYLEN(pnSeed));995                static int64 nSeedDisconnected;996                if (nSeedDisconnected == 0)997                {998                    nSeedDisconnected = GetTime();999                    CRITICAL_BLOCK(cs_vNodes)1000                        foreach(CNode* pnode, vNodes)1001                            if (setSeed.count(pnode->addr.ip))1002                                pnode->fDisconnect = true;1003                }10041005                // Keep setting timestamps to 0 so they won't reconnect1006                if (GetTime() - nSeedDisconnected < 60 * 60)1007                {1008                    foreach(PAIRTYPE(const vector<unsigned char>, CAddress)& item, mapAddresses)1009                    {1010                        if (setSeed.count(item.second.ip))1011                        {1012                            item.second.nTime = 0;1013                            CAddrDB().WriteAddress(item.second);1014                        }1015                    }1016                }1017            }1018        }101910201021        //1022        // Choose an address to connect to based on most recently seen1023        //1024        CAddress addrConnect;1025        int64 nBest = INT64_MIN;10261027        // Only connect to one address per a.b.?.? range.1028        // Do this here so we don't have to critsect vNodes inside mapAddresses critsect.1029        set<unsigned int> setConnected;1030        CRITICAL_BLOCK(cs_vNodes)1031            foreach(CNode* pnode, vNodes)1032                setConnected.insert(pnode->addr.ip & 0x0000ffff);10331034        CRITICAL_BLOCK(cs_mapAddresses)1035        {1036            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)1037            {1038                const CAddress& addr = item.second;1039                if (!addr.IsIPv4() || !addr.IsValid() || setConnected.count(addr.ip & 0x0000ffff))1040                    continue;1041                int64 nSinceLastSeen = GetAdjustedTime() - addr.nTime;1042                int64 nSinceLastTry = GetAdjustedTime() - addr.nLastTry;10431044                // Randomize the order in a deterministic way, putting the standard port first1045                int64 nRandomizer = (uint64)(nStart * 4951 + addr.nLastTry * 9567851 + addr.ip * 7789) % (2 * 60 * 60);1046                if (addr.port != GetDefaultPort())1047                    nRandomizer += 2 * 60 * 60;10481049                // Last seen  Base retry frequency1050                //   <1 hour   10 min1051                //    1 hour    1 hour1052                //    4 hours   2 hours1053                //   24 hours   5 hours1054                //   48 hours   7 hours1055                //    7 days   13 hours1056                //   30 days   27 hours1057                //   90 days   46 hours1058                //  365 days   93 hours1059                int64 nDelay = (int64)(3600.0 * sqrt(fabs((double)nSinceLastSeen) / 3600.0) + nRandomizer);10601061                // Fast reconnect for one hour after last seen1062                if (nSinceLastSeen < 60 * 60)1063                    nDelay = 10 * 60;10641065                // Limit retry frequency1066                if (nSinceLastTry < nDelay)1067                    continue;10681069                // If we have IRC, we'll be notified when they first come online,1070                // and again every 24 hours by the refresh broadcast.1071                if (nGotIRCAddresses > 0 && vNodes.size() >= 2 && nSinceLastSeen > 24 * 60 * 60)1072                    continue;10731074                // Only try the old stuff if we don't have enough connections1075                if (vNodes.size() >= 8 && nSinceLastSeen > 24 * 60 * 60)1076                    continue;10771078                // If multiple addresses are ready, prioritize by time since1079                // last seen and time since last tried.1080                int64 nScore = min(nSinceLastTry, (int64)24 * 60 * 60) - nSinceLastSeen - nRandomizer;1081                if (nScore > nBest)1082                {1083                    nBest = nScore;1084                    addrConnect = addr;1085                }1086            }1087        }10881089        if (addrConnect.IsValid())1090            OpenNetworkConnection(addrConnect);1091    }1092}10931094bool OpenNetworkConnection(const CAddress& addrConnect)1095{1096    //1097    // Initiate outbound network connection1098    //1099    if (fShutdown)1100        return false;1101    if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() || FindNode(addrConnect.ip))1102        return false;11031104    vnThreadsRunning[1]--;1105    CNode* pnode = ConnectNode(addrConnect);1106    vnThreadsRunning[1]++;1107    if (fShutdown)1108        return false;1109    if (!pnode)1110        return false;1111    pnode->fNetworkNode = true;11121113    return true;1114}111511161117111811191120112111221123void ThreadMessageHandler(void* parg)1124{1125    IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));1126    try1127    {1128        vnThreadsRunning[2]++;1129        ThreadMessageHandler2(parg);1130        vnThreadsRunning[2]--;1131    }1132    catch (std::exception& e) {1133        vnThreadsRunning[2]--;1134        PrintException(&e, "ThreadMessageHandler()");1135    } catch (...) {1136        vnThreadsRunning[2]--;1137        PrintException(NULL, "ThreadMessageHandler()");1138    }1139    printf("ThreadMessageHandler exiting\n");1140}11411142void ThreadMessageHandler2(void* parg)1143{1144    printf("ThreadMessageHandler started\n");1145    SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);1146    while (!fShutdown)1147    {1148        vector<CNode*> vNodesCopy;1149        CRITICAL_BLOCK(cs_vNodes)1150        {1151            vNodesCopy = vNodes;1152            foreach(CNode* pnode, vNodesCopy)1153                pnode->AddRef();1154        }11551156        // Poll the connected nodes for messages1157        CNode* pnodeTrickle = NULL;1158        if (!vNodesCopy.empty())1159            pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];1160        foreach(CNode* pnode, vNodesCopy)1161        {1162            // Receive messages1163            TRY_CRITICAL_BLOCK(pnode->cs_vRecv)1164                ProcessMessages(pnode);1165            if (fShutdown)1166                return;11671168            // Send messages1169            TRY_CRITICAL_BLOCK(pnode->cs_vSend)1170                SendMessages(pnode, pnode == pnodeTrickle);1171            if (fShutdown)1172                return;1173        }11741175        CRITICAL_BLOCK(cs_vNodes)1176        {1177            foreach(CNode* pnode, vNodesCopy)1178                pnode->Release();1179        }11801181        // Wait and allow messages to bunch up.1182        // Reduce vnThreadsRunning so StopNode has permission to exit while1183        // we're sleeping, but we must always check fShutdown after doing this.1184        vnThreadsRunning[2]--;1185        Sleep(100);1186        if (fRequestShutdown)1187            Shutdown(NULL);1188        vnThreadsRunning[2]++;1189        if (fShutdown)1190            return;1191    }1192}1193119411951196119711981199120012011202bool BindListenPort(string& strError)1203{1204    strError = "";1205    int nOne = 1;1206    addrLocalHost.port = GetDefaultPort();12071208#ifdef __WXMSW__1209    // Initialize Windows Sockets1210    WSADATA wsadata;1211    int ret = WSAStartup(MAKEWORD(2,2), &wsadata);1212    if (ret != NO_ERROR)1213    {1214        strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);1215        printf("%s\n", strError.c_str());1216        return false;1217    }1218#endif12191220    // Create socket for listening for incoming connections1221    hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);1222    if (hListenSocket == INVALID_SOCKET)1223    {1224        strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());1225        printf("%s\n", strError.c_str());1226        return false;1227    }12281229#ifdef BSD1230    // Different way of disabling SIGPIPE on BSD1231    setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));1232#endif12331234#ifndef __WXMSW__1235    // Allow binding if the port is still in TIME_WAIT state after1236    // the program was closed and restarted.  Not an issue on windows.1237    setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));1238#endif12391240#ifdef __WXMSW__1241    // Set to nonblocking, incoming connections will also inherit this1242    if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR)1243#else1244    if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR)1245#endif1246    {1247        strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError());1248        printf("%s\n", strError.c_str());1249        return false;1250    }12511252    // The sockaddr_in structure specifies the address family,1253    // IP address, and port for the socket that is being bound1254    struct sockaddr_in sockaddr;1255    memset(&sockaddr, 0, sizeof(sockaddr));1256    sockaddr.sin_family = AF_INET;1257    sockaddr.sin_addr.s_addr = INADDR_ANY; // bind to all IPs on this computer1258    sockaddr.sin_port = GetDefaultPort();1259    if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)1260    {1261        int nErr = WSAGetLastError();1262        if (nErr == WSAEADDRINUSE)1263            strError = strprintf(_("Unable to bind to port %d on this computer.  Bitcoin is probably already running."), ntohs(sockaddr.sin_port));1264        else1265            strError = strprintf("Error: Unable to bind to port %d on this computer (bind returned error %d)", ntohs(sockaddr.sin_port), nErr);1266        printf("%s\n", strError.c_str());1267        return false;1268    }1269    printf("Bound to port %d\n", ntohs(sockaddr.sin_port));12701271    // Listen for incoming connections1272    if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)1273    {1274        strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());1275        printf("%s\n", strError.c_str());1276        return false;1277    }12781279    return true;1280}12811282void StartNode(void* parg)1283{1284    if (pnodeLocalHost == NULL)1285        pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress("127.0.0.1", nLocalServices));12861287#ifdef __WXMSW__1288    // Get local host ip1289    char pszHostName[1000] = "";1290    if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR)1291    {1292        struct hostent* phostent = gethostbyname(pszHostName);1293        if (phostent)1294        {1295            // Take the first IP that isn't loopback 127.x.x.x1296            for (int i = 0; phostent->h_addr_list[i] != NULL; i++)1297                printf("host ip %d: %s\n", i, CAddress(*(unsigned int*)phostent->h_addr_list[i]).ToStringIP().c_str());1298            for (int i = 0; phostent->h_addr_list[i] != NULL; i++)1299            {1300                CAddress addr(*(unsigned int*)phostent->h_addr_list[i], GetDefaultPort(), nLocalServices);1301                if (addr.IsValid() && addr.GetByte(3) != 127)1302                {1303                    addrLocalHost = addr;1304                    break;1305                }1306            }1307        }1308    }1309#else1310    // Get local host ip1311    struct ifaddrs* myaddrs;1312    if (getifaddrs(&myaddrs) == 0)1313    {1314        for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next)1315        {1316            if (ifa->ifa_addr == NULL) continue;1317            if ((ifa->ifa_flags & IFF_UP) == 0) continue;1318            if (strcmp(ifa->ifa_name, "lo") == 0) continue;1319            if (strcmp(ifa->ifa_name, "lo0") == 0) continue;1320            char pszIP[100];1321            if (ifa->ifa_addr->sa_family == AF_INET)1322            {1323                struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);1324                if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s4->sin_addr), pszIP, sizeof(pszIP)) != NULL)1325                    printf("ipv4 %s: %s\n", ifa->ifa_name, pszIP);13261327                // Take the first IP that isn't loopback 127.x.x.x1328                CAddress addr(*(unsigned int*)&s4->sin_addr, GetDefaultPort(), nLocalServices);1329                if (addr.IsValid() && addr.GetByte(3) != 127)1330                {1331                    addrLocalHost = addr;1332                    break;1333                }1334            }1335            else if (ifa->ifa_addr->sa_family == AF_INET6)1336            {1337                struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);1338                if (inet_ntop(ifa->ifa_addr->sa_family, (void*)&(s6->sin6_addr), pszIP, sizeof(pszIP)) != NULL)1339                    printf("ipv6 %s: %s\n", ifa->ifa_name, pszIP);1340            }1341        }1342        freeifaddrs(myaddrs);1343    }1344#endif1345    printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());13461347    if (fUseProxy || mapArgs.count("-connect"))1348    {1349        // Proxies can't take incoming connections1350        addrLocalHost.ip = CAddress("0.0.0.0").ip;1351        printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());1352    }1353    else1354    {1355        CreateThread(ThreadGetMyExternalIP, NULL);1356    }13571358    //1359    // Start threads1360    //13611362    // Get addresses from IRC and advertise ours1363    if (!CreateThread(ThreadIRCSeed, NULL))1364        printf("Error: CreateThread(ThreadIRCSeed) failed\n");13651366    // Send and receive from sockets, accept connections1367    pthread_t hThreadSocketHandler = CreateThread(ThreadSocketHandler, NULL, true);13681369    // Initiate outbound connections1370    if (!CreateThread(ThreadOpenConnections, NULL))1371        printf("Error: CreateThread(ThreadOpenConnections) failed\n");13721373    // Process messages1374    if (!CreateThread(ThreadMessageHandler, NULL))1375        printf("Error: CreateThread(ThreadMessageHandler) failed\n");13761377    // Generate coins in the background1378    GenerateBitcoins(fGenerateBitcoins);1379}13801381bool StopNode()1382{1383    printf("StopNode()\n");1384    fShutdown = true;1385    nTransactionsUpdated++;1386    int64 nStart = GetTime();1387    while (vnThreadsRunning[0] > 0 || vnThreadsRunning[2] > 0 || vnThreadsRunning[3] > 0 || vnThreadsRunning[4] > 0)1388    {1389        if (GetTime() - nStart > 20)1390            break;1391        Sleep(20);1392    }1393    if (vnThreadsRunning[0] > 0) printf("ThreadSocketHandler still running\n");1394    if (vnThreadsRunning[1] > 0) printf("ThreadOpenConnections still running\n");1395    if (vnThreadsRunning[2] > 0) printf("ThreadMessageHandler still running\n");1396    if (vnThreadsRunning[3] > 0) printf("ThreadBitcoinMiner still running\n");1397    if (vnThreadsRunning[4] > 0) printf("ThreadRPCServer still running\n");1398    while (vnThreadsRunning[2] > 0 || vnThreadsRunning[4] > 0)1399        Sleep(20);1400    Sleep(50);14011402    return true;1403}14041405class CNetCleanup1406{1407public:1408    CNetCleanup()1409    {1410    }1411    ~CNetCleanup()1412    {1413        // Close sockets1414        foreach(CNode* pnode, vNodes)1415            if (pnode->hSocket != INVALID_SOCKET)1416                closesocket(pnode->hSocket);1417        if (hListenSocket != INVALID_SOCKET)1418            if (closesocket(hListenSocket) == SOCKET_ERROR)1419                printf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError());14201421#ifdef __WXMSW__1422        // Shutdown Windows Sockets1423        WSACleanup();1424#endif1425    }1426}1427instance_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