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.1.3 · 2009-01-12

net.cpp

1,067 lines · plain text · MIT license (license.txt)
1// Copyright (c) 2009 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"6#include <winsock2.h>78void ThreadMessageHandler2(void* parg);9void ThreadSocketHandler2(void* parg);10void ThreadOpenConnections2(void* parg);11121314151617//18// Global state variables19//20bool fClient = false;21uint64 nLocalServices = (fClient ? 0 : NODE_NETWORK);22CAddress addrLocalHost(0, DEFAULT_PORT, nLocalServices);23CNode nodeLocalHost(INVALID_SOCKET, CAddress("127.0.0.1", nLocalServices));24CNode* pnodeLocalHost = &nodeLocalHost;25bool fShutdown = false;26array<bool, 10> vfThreadRunning;27vector<CNode*> vNodes;28CCriticalSection cs_vNodes;29map<vector<unsigned char>, CAddress> mapAddresses;30CCriticalSection cs_mapAddresses;31map<CInv, CDataStream> mapRelay;32deque<pair<int64, CInv> > vRelayExpiration;33CCriticalSection cs_mapRelay;34map<CInv, int64> mapAlreadyAskedFor;35363738CAddress addrProxy;3940bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet)41{42    hSocketRet = INVALID_SOCKET;4344    SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);45    if (hSocket == INVALID_SOCKET)46        return false;4748    bool fRoutable = !(addrConnect.GetByte(3) == 10 || (addrConnect.GetByte(3) == 192 && addrConnect.GetByte(2) == 168));49    bool fProxy = (addrProxy.ip && fRoutable);50    struct sockaddr_in sockaddr = (fProxy ? addrProxy.GetSockAddr() : addrConnect.GetSockAddr());5152    if (connect(hSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)53    {54        closesocket(hSocket);55        return false;56    }5758    if (fProxy)59    {60        printf("Proxy connecting to %s\n", addrConnect.ToString().c_str());61        char pszSocks4IP[] = "\4\1\0\0\0\0\0\0user";62        memcpy(pszSocks4IP + 2, &addrConnect.port, 2);63        memcpy(pszSocks4IP + 4, &addrConnect.ip, 4);64        char* pszSocks4 = pszSocks4IP;65        int nSize = sizeof(pszSocks4IP);6667        int ret = send(hSocket, pszSocks4, nSize, 0);68        if (ret != nSize)69        {70            closesocket(hSocket);71            return error("Error sending to proxy\n");72        }73        char pchRet[8];74        if (recv(hSocket, pchRet, 8, 0) != 8)75        {76            closesocket(hSocket);77            return error("Error reading proxy response\n");78        }79        if (pchRet[1] != 0x5a)80        {81            closesocket(hSocket);82            return error("Proxy returned error %d\n", pchRet[1]);83        }84        printf("Proxy connection established %s\n", addrConnect.ToString().c_str());85    }8687    hSocketRet = hSocket;88    return true;89}90919293bool GetMyExternalIP2(const CAddress& addrConnect, const char* pszGet, const char* pszKeyword, unsigned int& ipRet)94{95    SOCKET hSocket;96    if (!ConnectSocket(addrConnect, hSocket))97        return error("GetMyExternalIP() : connection to %s failed\n", addrConnect.ToString().c_str());9899    send(hSocket, pszGet, strlen(pszGet), 0);100101    string strLine;102    while (RecvLine(hSocket, strLine))103    {104        if (strLine.empty())105        {106            loop107            {108                if (!RecvLine(hSocket, strLine))109                {110                    closesocket(hSocket);111                    return false;112                }113                if (strLine.find(pszKeyword) != -1)114                {115                    strLine = strLine.substr(strLine.find(pszKeyword) + strlen(pszKeyword));116                    break;117                }118            }119            closesocket(hSocket);120            if (strLine.find("<"))121                strLine = strLine.substr(0, strLine.find("<"));122            strLine = strLine.substr(strspn(strLine.c_str(), " \t\n\r"));123            strLine = wxString(strLine).Trim();124            CAddress addr(strLine.c_str());125            printf("GetMyExternalIP() received [%s] %s\n", strLine.c_str(), addr.ToString().c_str());126            if (addr.ip == 0 || !addr.IsRoutable())127                return false;128            ipRet = addr.ip;129            return true;130        }131    }132    closesocket(hSocket);133    return error("GetMyExternalIP() : connection closed\n");134}135136137bool GetMyExternalIP(unsigned int& ipRet)138{139    CAddress addrConnect;140    char* pszGet;141    char* pszKeyword;142143    for (int nLookup = 0; nLookup <= 1; nLookup++)144    for (int nHost = 1; nHost <= 2; nHost++)145    {146        if (nHost == 1)147        {148            addrConnect = CAddress("70.86.96.218:80"); // www.ipaddressworld.com149150            if (nLookup == 1)151            {152                struct hostent* phostent = gethostbyname("www.ipaddressworld.com");153                addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));154            }155156            pszGet = "GET /ip.php HTTP/1.1\r\n"157                     "Host: www.ipaddressworld.com\r\n"158                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"159                     "Connection: close\r\n"160                     "\r\n";161162            pszKeyword = "IP:";163        }164        else if (nHost == 2)165        {166            addrConnect = CAddress("208.78.68.70:80"); // checkip.dyndns.org167168            if (nLookup == 1)169            {170                struct hostent* phostent = gethostbyname("checkip.dyndns.org");171                addrConnect = CAddress(*(u_long*)phostent->h_addr_list[0], htons(80));172            }173174            pszGet = "GET / HTTP/1.1\r\n"175                     "Host: checkip.dyndns.org\r\n"176                     "User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)\r\n"177                     "Connection: close\r\n"178                     "\r\n";179180            pszKeyword = "Address:";181        }182183        if (GetMyExternalIP2(addrConnect, pszGet, pszKeyword, ipRet))184            return true;185    }186187    return false;188}189190191192193194bool AddAddress(CAddrDB& addrdb, const CAddress& addr)195{196    if (!addr.IsRoutable())197        return false;198    if (addr.ip == addrLocalHost.ip)199        return false;200    CRITICAL_BLOCK(cs_mapAddresses)201    {202        map<vector<unsigned char>, CAddress>::iterator it = mapAddresses.find(addr.GetKey());203        if (it == mapAddresses.end())204        {205            // New address206            mapAddresses.insert(make_pair(addr.GetKey(), addr));207            addrdb.WriteAddress(addr);208            return true;209        }210        else211        {212            CAddress& addrFound = (*it).second;213            if ((addrFound.nServices | addr.nServices) != addrFound.nServices)214            {215                // Services have been added216                addrFound.nServices |= addr.nServices;217                addrdb.WriteAddress(addrFound);218                return true;219            }220        }221    }222    return false;223}224225226227228229void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1)230{231    // If the dialog might get closed before the reply comes back,232    // call this in the destructor so it doesn't get called after it's deleted.233    CRITICAL_BLOCK(cs_vNodes)234    {235        foreach(CNode* pnode, vNodes)236        {237            CRITICAL_BLOCK(pnode->cs_mapRequests)238            {239                for (map<uint256, CRequestTracker>::iterator mi = pnode->mapRequests.begin(); mi != pnode->mapRequests.end();)240                {241                    CRequestTracker& tracker = (*mi).second;242                    if (tracker.fn == fn && tracker.param1 == param1)243                        pnode->mapRequests.erase(mi++);244                    else245                        mi++;246                }247            }248        }249    }250}251252253254255256257258//259// Subscription methods for the broadcast and subscription system.260// Channel numbers are message numbers, i.e. MSG_TABLE and MSG_PRODUCT.261//262// The subscription system uses a meet-in-the-middle strategy.263// With 100,000 nodes, if senders broadcast to 1000 random nodes and receivers264// subscribe to 1000 random nodes, 99.995% (1 - 0.99^1000) of messages will get through.265//266267bool AnySubscribed(unsigned int nChannel)268{269    if (pnodeLocalHost->IsSubscribed(nChannel))270        return true;271    CRITICAL_BLOCK(cs_vNodes)272        foreach(CNode* pnode, vNodes)273            if (pnode->IsSubscribed(nChannel))274                return true;275    return false;276}277278bool CNode::IsSubscribed(unsigned int nChannel)279{280    if (nChannel >= vfSubscribe.size())281        return false;282    return vfSubscribe[nChannel];283}284285void CNode::Subscribe(unsigned int nChannel, unsigned int nHops)286{287    if (nChannel >= vfSubscribe.size())288        return;289290    if (!AnySubscribed(nChannel))291    {292        // Relay subscribe293        CRITICAL_BLOCK(cs_vNodes)294            foreach(CNode* pnode, vNodes)295                if (pnode != this)296                    pnode->PushMessage("subscribe", nChannel, nHops);297    }298299    vfSubscribe[nChannel] = true;300}301302void CNode::CancelSubscribe(unsigned int nChannel)303{304    if (nChannel >= vfSubscribe.size())305        return;306307    // Prevent from relaying cancel if wasn't subscribed308    if (!vfSubscribe[nChannel])309        return;310    vfSubscribe[nChannel] = false;311312    if (!AnySubscribed(nChannel))313    {314        // Relay subscription cancel315        CRITICAL_BLOCK(cs_vNodes)316            foreach(CNode* pnode, vNodes)317                if (pnode != this)318                    pnode->PushMessage("sub-cancel", nChannel);319320        // Clear memory, no longer subscribed321        if (nChannel == MSG_PRODUCT)322            CRITICAL_BLOCK(cs_mapProducts)323                mapProducts.clear();324    }325}326327328329330331332333334335CNode* FindNode(unsigned int ip)336{337    CRITICAL_BLOCK(cs_vNodes)338    {339        foreach(CNode* pnode, vNodes)340            if (pnode->addr.ip == ip)341                return (pnode);342    }343    return NULL;344}345346CNode* FindNode(CAddress addr)347{348    CRITICAL_BLOCK(cs_vNodes)349    {350        foreach(CNode* pnode, vNodes)351            if (pnode->addr == addr)352                return (pnode);353    }354    return NULL;355}356357CNode* ConnectNode(CAddress addrConnect, int64 nTimeout)358{359    if (addrConnect.ip == addrLocalHost.ip)360        return NULL;361362    // Look for an existing connection363    CNode* pnode = FindNode(addrConnect.ip);364    if (pnode)365    {366        if (nTimeout != 0)367            pnode->AddRef(nTimeout);368        else369            pnode->AddRef();370        return pnode;371    }372373    /// debug print374    printf("trying %s\n", addrConnect.ToString().c_str());375376    // Connect377    SOCKET hSocket;378    if (ConnectSocket(addrConnect, hSocket))379    {380        /// debug print381        printf("connected %s\n", addrConnect.ToString().c_str());382383        // Set to nonblocking384        u_long nOne = 1;385        if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR)386            printf("ConnectSocket() : ioctlsocket nonblocking setting failed, error %d\n", WSAGetLastError());387388        // Add node389        CNode* pnode = new CNode(hSocket, addrConnect, false);390        if (nTimeout != 0)391            pnode->AddRef(nTimeout);392        else393            pnode->AddRef();394        CRITICAL_BLOCK(cs_vNodes)395            vNodes.push_back(pnode);396397        CRITICAL_BLOCK(cs_mapAddresses)398            mapAddresses[addrConnect.GetKey()].nLastFailed = 0;399        return pnode;400    }401    else402    {403        CRITICAL_BLOCK(cs_mapAddresses)404            mapAddresses[addrConnect.GetKey()].nLastFailed = GetTime();405        return NULL;406    }407}408409void CNode::Disconnect()410{411    printf("disconnecting node %s\n", addr.ToString().c_str());412413    closesocket(hSocket);414415    // All of a nodes broadcasts and subscriptions are automatically torn down416    // when it goes down, so a node has to stay up to keep its broadcast going.417418    CRITICAL_BLOCK(cs_mapProducts)419        for (map<uint256, CProduct>::iterator mi = mapProducts.begin(); mi != mapProducts.end();)420            AdvertRemoveSource(this, MSG_PRODUCT, 0, (*(mi++)).second);421422    // Cancel subscriptions423    for (unsigned int nChannel = 0; nChannel < vfSubscribe.size(); nChannel++)424        if (vfSubscribe[nChannel])425            CancelSubscribe(nChannel);426}427428429430431432433434435436437438439440void ThreadSocketHandler(void* parg)441{442    IMPLEMENT_RANDOMIZE_STACK(ThreadSocketHandler(parg));443444    loop445    {446        vfThreadRunning[0] = true;447        CheckForShutdown(0);448        try449        {450            ThreadSocketHandler2(parg);451        }452        CATCH_PRINT_EXCEPTION("ThreadSocketHandler()")453        vfThreadRunning[0] = false;454        Sleep(5000);455    }456}457458void ThreadSocketHandler2(void* parg)459{460    printf("ThreadSocketHandler started\n");461    SOCKET hListenSocket = *(SOCKET*)parg;462    list<CNode*> vNodesDisconnected;463    int nPrevNodeCount = 0;464465    loop466    {467        //468        // Disconnect nodes469        //470        CRITICAL_BLOCK(cs_vNodes)471        {472            // Disconnect unused nodes473            vector<CNode*> vNodesCopy = vNodes;474            foreach(CNode* pnode, vNodesCopy)475            {476                if (pnode->ReadyToDisconnect() && pnode->vRecv.empty() && pnode->vSend.empty())477                {478                    // remove from vNodes479                    vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());480                    pnode->Disconnect();481482                    // hold in disconnected pool until all refs are released483                    pnode->nReleaseTime = max(pnode->nReleaseTime, GetTime() + 5 * 60);484                    if (pnode->fNetworkNode)485                        pnode->Release();486                    vNodesDisconnected.push_back(pnode);487                }488            }489490            // Delete disconnected nodes491            list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;492            foreach(CNode* pnode, vNodesDisconnectedCopy)493            {494                // wait until threads are done using it495                if (pnode->GetRefCount() <= 0)496                {497                    bool fDelete = false;498                    TRY_CRITICAL_BLOCK(pnode->cs_vSend)499                     TRY_CRITICAL_BLOCK(pnode->cs_vRecv)500                      TRY_CRITICAL_BLOCK(pnode->cs_mapRequests)501                       TRY_CRITICAL_BLOCK(pnode->cs_inventory)502                        fDelete = true;503                    if (fDelete)504                    {505                        vNodesDisconnected.remove(pnode);506                        delete pnode;507                    }508                }509            }510        }511        if (vNodes.size() != nPrevNodeCount)512        {513            nPrevNodeCount = vNodes.size();514            MainFrameRepaint();515        }516517518        //519        // Find which sockets have data to receive520        //521        struct timeval timeout;522        timeout.tv_sec  = 0;523        timeout.tv_usec = 50000; // frequency to poll pnode->vSend524525        struct fd_set fdsetRecv;526        struct fd_set fdsetSend;527        FD_ZERO(&fdsetRecv);528        FD_ZERO(&fdsetSend);529        SOCKET hSocketMax = 0;530        FD_SET(hListenSocket, &fdsetRecv);531        hSocketMax = max(hSocketMax, hListenSocket);532        CRITICAL_BLOCK(cs_vNodes)533        {534            foreach(CNode* pnode, vNodes)535            {536                FD_SET(pnode->hSocket, &fdsetRecv);537                hSocketMax = max(hSocketMax, pnode->hSocket);538                TRY_CRITICAL_BLOCK(pnode->cs_vSend)539                    if (!pnode->vSend.empty())540                        FD_SET(pnode->hSocket, &fdsetSend);541            }542        }543544        vfThreadRunning[0] = false;545        int nSelect = select(hSocketMax + 1, &fdsetRecv, &fdsetSend, NULL, &timeout);546        vfThreadRunning[0] = true;547        CheckForShutdown(0);548        if (nSelect == SOCKET_ERROR)549        {550            int nErr = WSAGetLastError();551            printf("select failed: %d\n", nErr);552            for (int i = 0; i <= hSocketMax; i++)553            {554                FD_SET(i, &fdsetRecv);555                FD_SET(i, &fdsetSend);556            }557            Sleep(timeout.tv_usec/1000);558        }559        RandAddSeed();560561        //// debug print562        //foreach(CNode* pnode, vNodes)563        //{564        //    printf("vRecv = %-5d ", pnode->vRecv.size());565        //    printf("vSend = %-5d    ", pnode->vSend.size());566        //}567        //printf("\n");568569570        //571        // Accept new connections572        //573        if (FD_ISSET(hListenSocket, &fdsetRecv))574        {575            struct sockaddr_in sockaddr;576            int len = sizeof(sockaddr);577            SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len);578            CAddress addr(sockaddr);579            if (hSocket == INVALID_SOCKET)580            {581                if (WSAGetLastError() != WSAEWOULDBLOCK)582                    printf("ERROR ThreadSocketHandler accept failed: %d\n", WSAGetLastError());583            }584            else585            {586                printf("accepted connection from %s\n", addr.ToString().c_str());587                CNode* pnode = new CNode(hSocket, addr, true);588                pnode->AddRef();589                CRITICAL_BLOCK(cs_vNodes)590                    vNodes.push_back(pnode);591            }592        }593594595        //596        // Service each socket597        //598        vector<CNode*> vNodesCopy;599        CRITICAL_BLOCK(cs_vNodes)600            vNodesCopy = vNodes;601        foreach(CNode* pnode, vNodesCopy)602        {603            CheckForShutdown(0);604            SOCKET hSocket = pnode->hSocket;605606            //607            // Receive608            //609            if (FD_ISSET(hSocket, &fdsetRecv))610            {611                TRY_CRITICAL_BLOCK(pnode->cs_vRecv)612                {613                    CDataStream& vRecv = pnode->vRecv;614                    unsigned int nPos = vRecv.size();615616                    // typical socket buffer is 8K-64K617                    const unsigned int nBufSize = 0x10000;618                    vRecv.resize(nPos + nBufSize);619                    int nBytes = recv(hSocket, &vRecv[nPos], nBufSize, 0);620                    vRecv.resize(nPos + max(nBytes, 0));621                    if (nBytes == 0)622                    {623                        // socket closed gracefully624                        if (!pnode->fDisconnect)625                            printf("recv: socket closed\n");626                        pnode->fDisconnect = true;627                    }628                    else if (nBytes < 0)629                    {630                        // socket error631                        int nErr = WSAGetLastError();632                        if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS)633                        {634                            if (!pnode->fDisconnect)635                                printf("recv failed: %d\n", nErr);636                            pnode->fDisconnect = true;637                        }638                    }639                }640            }641642            //643            // Send644            //645            if (FD_ISSET(hSocket, &fdsetSend))646            {647                TRY_CRITICAL_BLOCK(pnode->cs_vSend)648                {649                    CDataStream& vSend = pnode->vSend;650                    if (!vSend.empty())651                    {652                        int nBytes = send(hSocket, &vSend[0], vSend.size(), 0);653                        if (nBytes > 0)654                        {655                            vSend.erase(vSend.begin(), vSend.begin() + nBytes);656                        }657                        else if (nBytes == 0)658                        {659                            if (pnode->ReadyToDisconnect())660                                pnode->vSend.clear();661                        }662                        else663                        {664                            printf("send error %d\n", nBytes);665                            if (pnode->ReadyToDisconnect())666                                pnode->vSend.clear();667                        }668                    }669                }670            }671        }672673674        Sleep(10);675    }676}677678679680681682683684685686687void ThreadOpenConnections(void* parg)688{689    IMPLEMENT_RANDOMIZE_STACK(ThreadOpenConnections(parg));690691    loop692    {693        vfThreadRunning[1] = true;694        CheckForShutdown(1);695        try696        {697            ThreadOpenConnections2(parg);698        }699        CATCH_PRINT_EXCEPTION("ThreadOpenConnections()")700        vfThreadRunning[1] = false;701        Sleep(5000);702    }703}704705void ThreadOpenConnections2(void* parg)706{707    printf("ThreadOpenConnections started\n");708709    // Initiate network connections710    const int nMaxConnections = 15;711    loop712    {713        // Wait714        vfThreadRunning[1] = false;715        Sleep(500);716        while (vNodes.size() >= nMaxConnections || vNodes.size() >= mapAddresses.size())717        {718            CheckForShutdown(1);719            Sleep(2000);720        }721        vfThreadRunning[1] = true;722        CheckForShutdown(1);723724725        // Make a list of unique class C's726        unsigned char pchIPCMask[4] = { 0xff, 0xff, 0xff, 0x00 };727        unsigned int nIPCMask = *(unsigned int*)pchIPCMask;728        vector<unsigned int> vIPC;729        CRITICAL_BLOCK(cs_mapAddresses)730        {731            vIPC.reserve(mapAddresses.size());732            unsigned int nPrev = 0;733            foreach(const PAIRTYPE(vector<unsigned char>, CAddress)& item, mapAddresses)734            {735                const CAddress& addr = item.second;736                if (!addr.IsIPv4())737                    continue;738739                // Taking advantage of mapAddresses being in sorted order,740                // with IPs of the same class C grouped together.741                unsigned int ipC = addr.ip & nIPCMask;742                if (ipC != nPrev)743                    vIPC.push_back(nPrev = ipC);744            }745        }746747        //748        // The IP selection process is designed to limit vulnerability to address flooding.749        // Any class C (a.b.c.?) has an equal chance of being chosen, then an IP is750        // chosen within the class C.  An attacker may be able to allocate many IPs, but751        // they would normally be concentrated in blocks of class C's.  They can hog the752        // attention within their class C, but not the whole IP address space overall.753        // A lone node in a class C will get as much attention as someone holding all 255754        // IPs in another class C.755        //756        bool fSuccess = false;757        int nLimit = vIPC.size();758        while (!fSuccess && nLimit-- > 0)759        {760            // Choose a random class C761            unsigned int ipC = vIPC[GetRand(vIPC.size())];762763            // Organize all addresses in the class C by IP764            map<unsigned int, vector<CAddress> > mapIP;765            CRITICAL_BLOCK(cs_mapAddresses)766            {767                unsigned int nDelay = ((30 * 60) << vNodes.size());768                if (nDelay > 8 * 60 * 60)769                    nDelay = 8 * 60 * 60;770                for (map<vector<unsigned char>, CAddress>::iterator mi = mapAddresses.lower_bound(CAddress(ipC, 0).GetKey());771                     mi != mapAddresses.upper_bound(CAddress(ipC | ~nIPCMask, 0xffff).GetKey());772                     ++mi)773                {774                    const CAddress& addr = (*mi).second;775                    unsigned int nRandomizer = (addr.nLastFailed * addr.ip * 7777U) % 20000;776                    if (GetTime() - addr.nLastFailed > nDelay * nRandomizer / 10000)777                        mapIP[addr.ip].push_back(addr);778                }779            }780            if (mapIP.empty())781                break;782783            // Choose a random IP in the class C784            map<unsigned int, vector<CAddress> >::iterator mi = mapIP.begin();785            advance(mi, GetRand(mapIP.size()));786787            // Once we've chosen an IP, we'll try every given port before moving on788            foreach(const CAddress& addrConnect, (*mi).second)789            {790                CheckForShutdown(1);791                if (addrConnect.ip == addrLocalHost.ip || !addrConnect.IsIPv4() || FindNode(addrConnect.ip))792                    continue;793794                vfThreadRunning[1] = false;795                CNode* pnode = ConnectNode(addrConnect);796                vfThreadRunning[1] = true;797                CheckForShutdown(1);798                if (!pnode)799                    continue;800                pnode->fNetworkNode = true;801802                if (addrLocalHost.IsRoutable())803                {804                    // Advertise our address805                    vector<CAddress> vAddrToSend;806                    vAddrToSend.push_back(addrLocalHost);807                    pnode->PushMessage("addr", vAddrToSend);808                }809810                // Get as many addresses as we can811                pnode->PushMessage("getaddr");812813                ////// should the one on the receiving end do this too?814                // Subscribe our local subscription list815                const unsigned int nHops = 0;816                for (unsigned int nChannel = 0; nChannel < pnodeLocalHost->vfSubscribe.size(); nChannel++)817                    if (pnodeLocalHost->vfSubscribe[nChannel])818                        pnode->PushMessage("subscribe", nChannel, nHops);819820                fSuccess = true;821                break;822            }823        }824    }825}826827828829830831832833834void ThreadMessageHandler(void* parg)835{836    IMPLEMENT_RANDOMIZE_STACK(ThreadMessageHandler(parg));837838    loop839    {840        vfThreadRunning[2] = true;841        CheckForShutdown(2);842        try843        {844            ThreadMessageHandler2(parg);845        }846        CATCH_PRINT_EXCEPTION("ThreadMessageHandler()")847        vfThreadRunning[2] = false;848        Sleep(5000);849    }850}851852void ThreadMessageHandler2(void* parg)853{854    printf("ThreadMessageHandler started\n");855    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);856    loop857    {858        // Poll the connected nodes for messages859        vector<CNode*> vNodesCopy;860        CRITICAL_BLOCK(cs_vNodes)861            vNodesCopy = vNodes;862        foreach(CNode* pnode, vNodesCopy)863        {864            pnode->AddRef();865866            // Receive messages867            TRY_CRITICAL_BLOCK(pnode->cs_vRecv)868                ProcessMessages(pnode);869870            // Send messages871            TRY_CRITICAL_BLOCK(pnode->cs_vSend)872                SendMessages(pnode);873874            pnode->Release();875        }876877        // Wait and allow messages to bunch up878        vfThreadRunning[2] = false;879        Sleep(100);880        vfThreadRunning[2] = true;881        CheckForShutdown(2);882    }883}884885886887888889890891892893//// todo: start one thread per processor, use getenv("NUMBER_OF_PROCESSORS")894void ThreadBitcoinMiner(void* parg)895{896    vfThreadRunning[3] = true;897    CheckForShutdown(3);898    try899    {900        bool fRet = BitcoinMiner();901        printf("BitcoinMiner returned %s\n\n\n", fRet ? "true" : "false");902    }903    CATCH_PRINT_EXCEPTION("BitcoinMiner()")904    vfThreadRunning[3] = false;905}906907908909910911912913914915916917bool StartNode(string& strError)918{919    strError = "";920921    // Sockets startup922    WSADATA wsadata;923    int ret = WSAStartup(MAKEWORD(2,2), &wsadata);924    if (ret != NO_ERROR)925    {926        strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret);927        printf("%s\n", strError.c_str());928        return false;929    }930931    // Get local host ip932    char pszHostName[255];933    if (gethostname(pszHostName, 255) == SOCKET_ERROR)934    {935        strError = strprintf("Error: Unable to get IP address of this computer (gethostname returned error %d)", WSAGetLastError());936        printf("%s\n", strError.c_str());937        return false;938    }939    struct hostent* pHostEnt = gethostbyname(pszHostName);940    if (!pHostEnt)941    {942        strError = strprintf("Error: Unable to get IP address of this computer (gethostbyname returned error %d)", WSAGetLastError());943        printf("%s\n", strError.c_str());944        return false;945    }946    addrLocalHost = CAddress(*(long*)(pHostEnt->h_addr_list[0]),947                             DEFAULT_PORT,948                             nLocalServices);949    printf("addrLocalHost = %s\n", addrLocalHost.ToString().c_str());950951    // Create socket for listening for incoming connections952    SOCKET hListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);953    if (hListenSocket == INVALID_SOCKET)954    {955        strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError());956        printf("%s\n", strError.c_str());957        return false;958    }959960    // Set to nonblocking, incoming connections will also inherit this961    u_long nOne = 1;962    if (ioctlsocket(hListenSocket, FIONBIO, &nOne) == SOCKET_ERROR)963    {964        strError = strprintf("Error: Couldn't set properties on socket for incoming connections (ioctlsocket returned error %d)", WSAGetLastError());965        printf("%s\n", strError.c_str());966        return false;967    }968969    // The sockaddr_in structure specifies the address family,970    // IP address, and port for the socket that is being bound971    int nRetryLimit = 15;972    struct sockaddr_in sockaddr = addrLocalHost.GetSockAddr();973    if (bind(hListenSocket, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == SOCKET_ERROR)974    {975        int nErr = WSAGetLastError();976        if (nErr == WSAEADDRINUSE)977            strError = strprintf("Error: Unable to bind to port %s on this computer. The program is probably already running.", addrLocalHost.ToString().c_str());978        else979            strError = strprintf("Error: Unable to bind to port %s on this computer (bind returned error %d)", addrLocalHost.ToString().c_str(), nErr);980        printf("%s\n", strError.c_str());981        return false;982    }983    printf("bound to addrLocalHost = %s\n\n", addrLocalHost.ToString().c_str());984985    // Listen for incoming connections986    if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR)987    {988        strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError());989        printf("%s\n", strError.c_str());990        return false;991    }992993    // Get our external IP address for incoming connections994    if (addrIncoming.ip)995        addrLocalHost.ip = addrIncoming.ip;996997    if (GetMyExternalIP(addrLocalHost.ip))998    {999        addrIncoming = addrLocalHost;1000        CWalletDB().WriteSetting("addrIncoming", addrIncoming);1001    }10021003    // Get addresses from IRC and advertise ours1004    if (_beginthread(ThreadIRCSeed, 0, NULL) == -1)1005        printf("Error: _beginthread(ThreadIRCSeed) failed\n");10061007    //1008    // Start threads1009    //1010    if (_beginthread(ThreadSocketHandler, 0, new SOCKET(hListenSocket)) == -1)1011    {1012        strError = "Error: _beginthread(ThreadSocketHandler) failed";1013        printf("%s\n", strError.c_str());1014        return false;1015    }10161017    if (_beginthread(ThreadOpenConnections, 0, NULL) == -1)1018    {1019        strError = "Error: _beginthread(ThreadOpenConnections) failed";1020        printf("%s\n", strError.c_str());1021        return false;1022    }10231024    if (_beginthread(ThreadMessageHandler, 0, NULL) == -1)1025    {1026        strError = "Error: _beginthread(ThreadMessageHandler) failed";1027        printf("%s\n", strError.c_str());1028        return false;1029    }10301031    return true;1032}10331034bool StopNode()1035{1036    printf("StopNode()\n");1037    fShutdown = true;1038    nTransactionsUpdated++;1039    int64 nStart = GetTime();1040    while (vfThreadRunning[0] || vfThreadRunning[2] || vfThreadRunning[3])1041    {1042        if (GetTime() - nStart > 15)1043            break;1044        Sleep(20);1045    }1046    if (vfThreadRunning[0]) printf("ThreadSocketHandler still running\n");1047    if (vfThreadRunning[1]) printf("ThreadOpenConnections still running\n");1048    if (vfThreadRunning[2]) printf("ThreadMessageHandler still running\n");1049    if (vfThreadRunning[3]) printf("ThreadBitcoinMiner still running\n");1050    while (vfThreadRunning[2])1051        Sleep(20);1052    Sleep(50);10531054    // Sockets shutdown1055    WSACleanup();1056    return true;1057}10581059void CheckForShutdown(int n)1060{1061    if (fShutdown)1062    {1063        if (n != -1)1064            vfThreadRunning[n] = false;1065        _endthread();1066    }1067}

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