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.h

1,045 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.45class CMessageHeader;6class CAddress;7class CInv;8class CRequestTracker;9class CNode;10class CBlockIndex;11extern int nBestHeight;12131415inline unsigned short GetDefaultPort() { return fTestNet ? htons(18333) : htons(8333); }16static const unsigned int PUBLISH_HOPS = 5;17enum18{19    NODE_NETWORK = (1 << 0),20};2122232425bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);26bool GetMyExternalIP(unsigned int& ipRet);27bool AddAddress(CAddress addr, int64 nTimePenalty=0);28void AddressCurrentlyConnected(const CAddress& addr);29CNode* FindNode(unsigned int ip);30CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);31void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);32bool AnySubscribed(unsigned int nChannel);33bool BindListenPort(string& strError=REF(string()));34void StartNode(void* parg);35bool StopNode();363738394041424344//45// Message header46//  (4) message start47//  (12) command48//  (4) size49//  (4) checksum5051extern char pchMessageStart[4];5253class CMessageHeader54{55public:56    enum { COMMAND_SIZE=12 };57    char pchMessageStart[sizeof(::pchMessageStart)];58    char pchCommand[COMMAND_SIZE];59    unsigned int nMessageSize;60    unsigned int nChecksum;6162    CMessageHeader()63    {64        memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));65        memset(pchCommand, 0, sizeof(pchCommand));66        pchCommand[1] = 1;67        nMessageSize = -1;68        nChecksum = 0;69    }7071    CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)72    {73        memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));74        strncpy(pchCommand, pszCommand, COMMAND_SIZE);75        nMessageSize = nMessageSizeIn;76        nChecksum = 0;77    }7879    IMPLEMENT_SERIALIZE80    (81        READWRITE(FLATDATA(pchMessageStart));82        READWRITE(FLATDATA(pchCommand));83        READWRITE(nMessageSize);84        if (nVersion >= 209)85            READWRITE(nChecksum);86    )8788    string GetCommand()89    {90        if (pchCommand[COMMAND_SIZE-1] == 0)91            return string(pchCommand, pchCommand + strlen(pchCommand));92        else93            return string(pchCommand, pchCommand + COMMAND_SIZE);94    }9596    bool IsValid()97    {98        // Check start string99        if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)100            return false;101102        // Check the command string for errors103        for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)104        {105            if (*p1 == 0)106            {107                // Must be all zeros after the first zero108                for (; p1 < pchCommand + COMMAND_SIZE; p1++)109                    if (*p1 != 0)110                        return false;111            }112            else if (*p1 < ' ' || *p1 > 0x7E)113                return false;114        }115116        // Message size117        if (nMessageSize > MAX_SIZE)118        {119            printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);120            return false;121        }122123        return true;124    }125};126127128129130131132static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };133134class CAddress135{136public:137    uint64 nServices;138    unsigned char pchReserved[12];139    unsigned int ip;140    unsigned short port;141142    // disk and network only143    unsigned int nTime;144145    // memory only146    unsigned int nLastTry;147148    CAddress()149    {150        Init();151    }152153    CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)154    {155        Init();156        ip = ipIn;157        port = (portIn == 0 ? GetDefaultPort() : portIn);158        nServices = nServicesIn;159    }160161    explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)162    {163        Init();164        ip = sockaddr.sin_addr.s_addr;165        port = sockaddr.sin_port;166        nServices = nServicesIn;167    }168169    explicit CAddress(const char* pszIn, uint64 nServicesIn=NODE_NETWORK)170    {171        Init();172        SetAddress(pszIn);173        nServices = nServicesIn;174    }175176    explicit CAddress(string strIn, uint64 nServicesIn=NODE_NETWORK)177    {178        Init();179        SetAddress(strIn.c_str());180        nServices = nServicesIn;181    }182183    void Init()184    {185        nServices = NODE_NETWORK;186        memcpy(pchReserved, pchIPv4, sizeof(pchReserved));187        ip = INADDR_NONE;188        port = GetDefaultPort();189        nTime = 100000000;190        nLastTry = 0;191    }192193    bool SetAddress(const char* pszIn)194    {195        ip = INADDR_NONE;196        port = GetDefaultPort();197        char psz[100];198        strlcpy(psz, pszIn, sizeof(psz));199        unsigned int a=0, b=0, c=0, d=0, e=0;200        if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)201            return false;202        char* pszPort = strchr(psz, ':');203        if (pszPort)204        {205            *pszPort++ = '\0';206            port = htons(atoi(pszPort));207            if (atoi(pszPort) < 0 || atoi(pszPort) > USHRT_MAX)208                port = htons(USHRT_MAX);209        }210        ip = inet_addr(psz);211        return IsValid();212    }213214    bool SetAddress(string strIn)215    {216        return SetAddress(strIn.c_str());217    }218219    IMPLEMENT_SERIALIZE220    (221        if (fRead)222            const_cast<CAddress*>(this)->Init();223        if (nType & SER_DISK)224            READWRITE(nVersion);225        if ((nType & SER_DISK) || (nVersion >= 31402 && !(nType & SER_GETHASH)))226            READWRITE(nTime);227        READWRITE(nServices);228        READWRITE(FLATDATA(pchReserved)); // for IPv6229        READWRITE(ip);230        READWRITE(port);231    )232233    friend inline bool operator==(const CAddress& a, const CAddress& b)234    {235        return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&236                a.ip   == b.ip &&237                a.port == b.port);238    }239240    friend inline bool operator!=(const CAddress& a, const CAddress& b)241    {242        return (!(a == b));243    }244245    friend inline bool operator<(const CAddress& a, const CAddress& b)246    {247        int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));248        if (ret < 0)249            return true;250        else if (ret == 0)251        {252            if (ntohl(a.ip) < ntohl(b.ip))253                return true;254            else if (a.ip == b.ip)255                return ntohs(a.port) < ntohs(b.port);256        }257        return false;258    }259260    vector<unsigned char> GetKey() const261    {262        CDataStream ss;263        ss.reserve(18);264        ss << FLATDATA(pchReserved) << ip << port;265266        #if defined(_MSC_VER) && _MSC_VER < 1300267        return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);268        #else269        return vector<unsigned char>(ss.begin(), ss.end());270        #endif271    }272273    struct sockaddr_in GetSockAddr() const274    {275        struct sockaddr_in sockaddr;276        memset(&sockaddr, 0, sizeof(sockaddr));277        sockaddr.sin_family = AF_INET;278        sockaddr.sin_addr.s_addr = ip;279        sockaddr.sin_port = port;280        return sockaddr;281    }282283    bool IsIPv4() const284    {285        return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);286    }287288    bool IsRoutable() const289    {290        return IsValid() &&291            !(GetByte(3) == 10 ||292              (GetByte(3) == 192 && GetByte(2) == 168) ||293              GetByte(3) == 127 ||294              GetByte(3) == 0);295    }296297    bool IsValid() const298    {299        // Clean up 3-byte shifted addresses caused by garbage in size field300        // of addr messages from versions before 0.2.9 checksum.301        // Two consecutive addr messages look like this:302        // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...303        // so if the first length field is garbled, it reads the second batch304        // of addr misaligned by 3 bytes.305        if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)306            return false;307308        return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));309    }310311    unsigned char GetByte(int n) const312    {313        return ((unsigned char*)&ip)[3-n];314    }315316    string ToStringIPPort() const317    {318        return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));319    }320321    string ToStringIP() const322    {323        return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));324    }325326    string ToStringPort() const327    {328        return strprintf("%u", ntohs(port));329    }330331    string ToStringLog() const332    {333        return "";334    }335336    string ToString() const337    {338        return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));339    }340341    void print() const342    {343        printf("CAddress(%s)\n", ToString().c_str());344    }345};346347348349350351352353enum354{355    MSG_TX = 1,356    MSG_BLOCK,357};358359static const char* ppszTypeName[] =360{361    "ERROR",362    "tx",363    "block",364};365366class CInv367{368public:369    int type;370    uint256 hash;371372    CInv()373    {374        type = 0;375        hash = 0;376    }377378    CInv(int typeIn, const uint256& hashIn)379    {380        type = typeIn;381        hash = hashIn;382    }383384    CInv(const string& strType, const uint256& hashIn)385    {386        int i;387        for (i = 1; i < ARRAYLEN(ppszTypeName); i++)388        {389            if (strType == ppszTypeName[i])390            {391                type = i;392                break;393            }394        }395        if (i == ARRAYLEN(ppszTypeName))396            throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));397        hash = hashIn;398    }399400    IMPLEMENT_SERIALIZE401    (402        READWRITE(type);403        READWRITE(hash);404    )405406    friend inline bool operator<(const CInv& a, const CInv& b)407    {408        return (a.type < b.type || (a.type == b.type && a.hash < b.hash));409    }410411    bool IsKnownType() const412    {413        return (type >= 1 && type < ARRAYLEN(ppszTypeName));414    }415416    const char* GetCommand() const417    {418        if (!IsKnownType())419            throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));420        return ppszTypeName[type];421    }422423    string ToString() const424    {425        return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());426    }427428    void print() const429    {430        printf("CInv(%s)\n", ToString().c_str());431    }432};433434435436437438class CRequestTracker439{440public:441    void (*fn)(void*, CDataStream&);442    void* param1;443444    explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)445    {446        fn = fnIn;447        param1 = param1In;448    }449450    bool IsNull()451    {452        return fn == NULL;453    }454};455456457458459460extern bool fClient;461extern uint64 nLocalServices;462extern CAddress addrLocalHost;463extern CNode* pnodeLocalHost;464extern uint64 nLocalHostNonce;465extern array<int, 10> vnThreadsRunning;466extern SOCKET hListenSocket;467468extern vector<CNode*> vNodes;469extern CCriticalSection cs_vNodes;470extern map<vector<unsigned char>, CAddress> mapAddresses;471extern CCriticalSection cs_mapAddresses;472extern map<CInv, CDataStream> mapRelay;473extern deque<pair<int64, CInv> > vRelayExpiration;474extern CCriticalSection cs_mapRelay;475extern map<CInv, int64> mapAlreadyAskedFor;476477// Settings478extern int fUseProxy;479extern CAddress addrProxy;480481482483484485486class CNode487{488public:489    // socket490    uint64 nServices;491    SOCKET hSocket;492    CDataStream vSend;493    CDataStream vRecv;494    CCriticalSection cs_vSend;495    CCriticalSection cs_vRecv;496    int64 nLastSend;497    int64 nLastRecv;498    int64 nLastSendEmpty;499    int64 nTimeConnected;500    unsigned int nHeaderStart;501    unsigned int nMessageStart;502    CAddress addr;503    int nVersion;504    string strSubVer;505    bool fClient;506    bool fInbound;507    bool fNetworkNode;508    bool fSuccessfullyConnected;509    bool fDisconnect;510protected:511    int nRefCount;512public:513    int64 nReleaseTime;514    map<uint256, CRequestTracker> mapRequests;515    CCriticalSection cs_mapRequests;516    uint256 hashContinue;517    CBlockIndex* pindexLastGetBlocksBegin;518    uint256 hashLastGetBlocksEnd;519    int nStartingHeight;520521    // flood relay522    vector<CAddress> vAddrToSend;523    set<CAddress> setAddrKnown;524    bool fGetAddr;525    set<uint256> setKnown;526527    // inventory based relay528    set<CInv> setInventoryKnown;529    vector<CInv> vInventoryToSend;530    CCriticalSection cs_inventory;531    multimap<int64, CInv> mapAskFor;532533    // publish and subscription534    vector<char> vfSubscribe;535536537    CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)538    {539        nServices = 0;540        hSocket = hSocketIn;541        vSend.SetType(SER_NETWORK);542        vSend.SetVersion(0);543        vRecv.SetType(SER_NETWORK);544        vRecv.SetVersion(0);545        // Version 0.2 obsoletes 20 Feb 2012546        if (GetTime() > 1329696000)547        {548            vSend.SetVersion(209);549            vRecv.SetVersion(209);550        }551        nLastSend = 0;552        nLastRecv = 0;553        nLastSendEmpty = GetTime();554        nTimeConnected = GetTime();555        nHeaderStart = -1;556        nMessageStart = -1;557        addr = addrIn;558        nVersion = 0;559        strSubVer = "";560        fClient = false; // set by version message561        fInbound = fInboundIn;562        fNetworkNode = false;563        fSuccessfullyConnected = false;564        fDisconnect = false;565        nRefCount = 0;566        nReleaseTime = 0;567        hashContinue = 0;568        pindexLastGetBlocksBegin = 0;569        hashLastGetBlocksEnd = 0;570        nStartingHeight = -1;571        fGetAddr = false;572        vfSubscribe.assign(256, false);573574        // Push a version message575        /// when NTP implemented, change to just nTime = GetAdjustedTime()576        int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());577        CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);578        CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);579        RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));580        PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,581                    nLocalHostNonce, string(pszSubVer), nBestHeight);582    }583584    ~CNode()585    {586        if (hSocket != INVALID_SOCKET)587        {588            closesocket(hSocket);589            hSocket = INVALID_SOCKET;590        }591    }592593private:594    CNode(const CNode&);595    void operator=(const CNode&);596public:597598599    int GetRefCount()600    {601        return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);602    }603604    CNode* AddRef(int64 nTimeout=0)605    {606        if (nTimeout != 0)607            nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);608        else609            nRefCount++;610        return this;611    }612613    void Release()614    {615        nRefCount--;616    }617618619620    void AddAddressKnown(const CAddress& addr)621    {622        setAddrKnown.insert(addr);623    }624625    void PushAddress(const CAddress& addr)626    {627        // Known checking here is only to save space from duplicates.628        // SendMessages will filter it again for knowns that were added629        // after addresses were pushed.630        if (addr.IsValid() && !setAddrKnown.count(addr))631            vAddrToSend.push_back(addr);632    }633634635    void AddInventoryKnown(const CInv& inv)636    {637        CRITICAL_BLOCK(cs_inventory)638            setInventoryKnown.insert(inv);639    }640641    void PushInventory(const CInv& inv)642    {643        CRITICAL_BLOCK(cs_inventory)644            if (!setInventoryKnown.count(inv))645                vInventoryToSend.push_back(inv);646    }647648    void AskFor(const CInv& inv)649    {650        // We're using mapAskFor as a priority queue,651        // the key is the earliest time the request can be sent652        int64& nRequestTime = mapAlreadyAskedFor[inv];653        printf("askfor %s   %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);654655        // Make sure not to reuse time indexes to keep things in the same order656        int64 nNow = (GetTime() - 1) * 1000000;657        static int64 nLastTime;658        nLastTime = nNow = max(nNow, ++nLastTime);659660        // Each retry is 2 minutes after the last661        nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);662        mapAskFor.insert(make_pair(nRequestTime, inv));663    }664665666667    void BeginMessage(const char* pszCommand)668    {669        cs_vSend.Enter();670        if (nHeaderStart != -1)671            AbortMessage();672        nHeaderStart = vSend.size();673        vSend << CMessageHeader(pszCommand, 0);674        nMessageStart = vSend.size();675        if (fDebug)676            printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());677        printf("sending: %s ", pszCommand);678    }679680    void AbortMessage()681    {682        if (nHeaderStart == -1)683            return;684        vSend.resize(nHeaderStart);685        nHeaderStart = -1;686        nMessageStart = -1;687        cs_vSend.Leave();688        printf("(aborted)\n");689    }690691    void EndMessage()692    {693        if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)694        {695            printf("dropmessages DROPPING SEND MESSAGE\n");696            AbortMessage();697            return;698        }699700        if (nHeaderStart == -1)701            return;702703        // Set the size704        unsigned int nSize = vSend.size() - nMessageStart;705        memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));706707        // Set the checksum708        if (vSend.GetVersion() >= 209)709        {710            uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());711            unsigned int nChecksum = 0;712            memcpy(&nChecksum, &hash, sizeof(nChecksum));713            assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));714            memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));715        }716717        printf("(%d bytes) ", nSize);718        printf("\n");719720        nHeaderStart = -1;721        nMessageStart = -1;722        cs_vSend.Leave();723    }724725    void EndMessageAbortIfEmpty()726    {727        if (nHeaderStart == -1)728            return;729        int nSize = vSend.size() - nMessageStart;730        if (nSize > 0)731            EndMessage();732        else733            AbortMessage();734    }735736737738739    void PushMessage(const char* pszCommand)740    {741        try742        {743            BeginMessage(pszCommand);744            EndMessage();745        }746        catch (...)747        {748            AbortMessage();749            throw;750        }751    }752753    template<typename T1>754    void PushMessage(const char* pszCommand, const T1& a1)755    {756        try757        {758            BeginMessage(pszCommand);759            vSend << a1;760            EndMessage();761        }762        catch (...)763        {764            AbortMessage();765            throw;766        }767    }768769    template<typename T1, typename T2>770    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)771    {772        try773        {774            BeginMessage(pszCommand);775            vSend << a1 << a2;776            EndMessage();777        }778        catch (...)779        {780            AbortMessage();781            throw;782        }783    }784785    template<typename T1, typename T2, typename T3>786    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)787    {788        try789        {790            BeginMessage(pszCommand);791            vSend << a1 << a2 << a3;792            EndMessage();793        }794        catch (...)795        {796            AbortMessage();797            throw;798        }799    }800801    template<typename T1, typename T2, typename T3, typename T4>802    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)803    {804        try805        {806            BeginMessage(pszCommand);807            vSend << a1 << a2 << a3 << a4;808            EndMessage();809        }810        catch (...)811        {812            AbortMessage();813            throw;814        }815    }816817    template<typename T1, typename T2, typename T3, typename T4, typename T5>818    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)819    {820        try821        {822            BeginMessage(pszCommand);823            vSend << a1 << a2 << a3 << a4 << a5;824            EndMessage();825        }826        catch (...)827        {828            AbortMessage();829            throw;830        }831    }832833    template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>834    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)835    {836        try837        {838            BeginMessage(pszCommand);839            vSend << a1 << a2 << a3 << a4 << a5 << a6;840            EndMessage();841        }842        catch (...)843        {844            AbortMessage();845            throw;846        }847    }848849    template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>850    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7)851    {852        try853        {854            BeginMessage(pszCommand);855            vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;856            EndMessage();857        }858        catch (...)859        {860            AbortMessage();861            throw;862        }863    }864865    template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>866    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8)867    {868        try869        {870            BeginMessage(pszCommand);871            vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;872            EndMessage();873        }874        catch (...)875        {876            AbortMessage();877            throw;878        }879    }880881    template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>882    void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9)883    {884        try885        {886            BeginMessage(pszCommand);887            vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;888            EndMessage();889        }890        catch (...)891        {892            AbortMessage();893            throw;894        }895    }896897898    void PushRequest(const char* pszCommand,899                     void (*fn)(void*, CDataStream&), void* param1)900    {901        uint256 hashReply;902        RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));903904        CRITICAL_BLOCK(cs_mapRequests)905            mapRequests[hashReply] = CRequestTracker(fn, param1);906907        PushMessage(pszCommand, hashReply);908    }909910    template<typename T1>911    void PushRequest(const char* pszCommand, const T1& a1,912                     void (*fn)(void*, CDataStream&), void* param1)913    {914        uint256 hashReply;915        RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));916917        CRITICAL_BLOCK(cs_mapRequests)918            mapRequests[hashReply] = CRequestTracker(fn, param1);919920        PushMessage(pszCommand, hashReply, a1);921    }922923    template<typename T1, typename T2>924    void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,925                     void (*fn)(void*, CDataStream&), void* param1)926    {927        uint256 hashReply;928        RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));929930        CRITICAL_BLOCK(cs_mapRequests)931            mapRequests[hashReply] = CRequestTracker(fn, param1);932933        PushMessage(pszCommand, hashReply, a1, a2);934    }935936937938    void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);939    bool IsSubscribed(unsigned int nChannel);940    void Subscribe(unsigned int nChannel, unsigned int nHops=0);941    void CancelSubscribe(unsigned int nChannel);942    void CloseSocketDisconnect();943    void Cleanup();944};945946947948949950951952953954955inline void RelayInventory(const CInv& inv)956{957    // Put on lists to offer to the other nodes958    CRITICAL_BLOCK(cs_vNodes)959        foreach(CNode* pnode, vNodes)960            pnode->PushInventory(inv);961}962963template<typename T>964void RelayMessage(const CInv& inv, const T& a)965{966    CDataStream ss(SER_NETWORK);967    ss.reserve(10000);968    ss << a;969    RelayMessage(inv, ss);970}971972template<>973inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)974{975    CRITICAL_BLOCK(cs_mapRelay)976    {977        // Expire old relay messages978        while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())979        {980            mapRelay.erase(vRelayExpiration.front().second);981            vRelayExpiration.pop_front();982        }983984        // Save original serialized message so newer versions are preserved985        mapRelay[inv] = ss;986        vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));987    }988989    RelayInventory(inv);990}991992993994995996997998999//1000// Templates for the publish and subscription system.1001// The object being published as T& obj needs to have:1002//   a set<unsigned int> setSources member1003//   specializations of AdvertInsert and AdvertErase1004// Currently implemented for CTable and CProduct.1005//10061007template<typename T>1008void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)1009{1010    // Add to sources1011    obj.setSources.insert(pfrom->addr.ip);10121013    if (!AdvertInsert(obj))1014        return;10151016    // Relay1017    CRITICAL_BLOCK(cs_vNodes)1018        foreach(CNode* pnode, vNodes)1019            if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))1020                pnode->PushMessage("publish", nChannel, nHops, obj);1021}10221023template<typename T>1024void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)1025{1026    uint256 hash = obj.GetHash();10271028    CRITICAL_BLOCK(cs_vNodes)1029        foreach(CNode* pnode, vNodes)1030            if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))1031                pnode->PushMessage("pub-cancel", nChannel, nHops, hash);10321033    AdvertErase(obj);1034}10351036template<typename T>1037void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)1038{1039    // Remove a source1040    obj.setSources.erase(pfrom->addr.ip);10411042    // If no longer supported by any sources, cancel it1043    if (obj.setSources.empty())1044        AdvertStopPublish(pfrom, nChannel, nHops, obj);1045}

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