Bitcoin v0.2.0 · 2009-12-16
net.h
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.45class CMessageHeader;6class CAddress;7class CInv;8class CRequestTracker;9class CNode;10class CBlockIndex;11121314static const unsigned short DEFAULT_PORT = htons(8333);15static const unsigned int PUBLISH_HOPS = 5;16enum17{18 NODE_NETWORK = (1 << 0),19};2021222324bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);25bool GetMyExternalIP(unsigned int& ipRet);26bool AddAddress(CAddrDB& addrdb, CAddress addr, bool fCurrentlyOnline=true);27void AddressCurrentlyConnected(const CAddress& addr);28CNode* FindNode(unsigned int ip);29CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);30void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);31bool AnySubscribed(unsigned int nChannel);32bool BindListenPort(string& strError=REF(string()));33void StartNode(void* parg);34bool StopNode();353637383940414243//44// Message header45// (4) message start46// (12) command47// (4) size4849// The message start string is designed to be unlikely to occur in normal data.50// The characters are rarely used upper ascii, not valid as UTF-8, and produce51// a large 4-byte int at any alignment.52static const char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };5354class CMessageHeader55{56public:57 enum { COMMAND_SIZE=12 };58 char pchMessageStart[sizeof(::pchMessageStart)];59 char pchCommand[COMMAND_SIZE];60 unsigned int nMessageSize;6162 CMessageHeader()63 {64 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));65 memset(pchCommand, 0, sizeof(pchCommand));66 pchCommand[1] = 1;67 nMessageSize = -1;68 }6970 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)71 {72 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));73 strncpy(pchCommand, pszCommand, COMMAND_SIZE);74 nMessageSize = nMessageSizeIn;75 }7677 IMPLEMENT_SERIALIZE78 (79 READWRITE(FLATDATA(pchMessageStart));80 READWRITE(FLATDATA(pchCommand));81 READWRITE(nMessageSize);82 )8384 string GetCommand()85 {86 if (pchCommand[COMMAND_SIZE-1] == 0)87 return string(pchCommand, pchCommand + strlen(pchCommand));88 else89 return string(pchCommand, pchCommand + COMMAND_SIZE);90 }9192 bool IsValid()93 {94 // Check start string95 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)96 return false;9798 // Check the command string for errors99 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)100 {101 if (*p1 == 0)102 {103 // Must be all zeros after the first zero104 for (; p1 < pchCommand + COMMAND_SIZE; p1++)105 if (*p1 != 0)106 return false;107 }108 else if (*p1 < ' ' || *p1 > 0x7E)109 return false;110 }111112 // Message size113 if (nMessageSize > 0x10000000)114 {115 printf("CMessageHeader::IsValid() : nMessageSize too large %u\n", nMessageSize);116 return false;117 }118119 return true;120 }121};122123124125126127128static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };129130class CAddress131{132public:133 uint64 nServices;134 unsigned char pchReserved[12];135 unsigned int ip;136 unsigned short port;137138 // disk only139 unsigned int nTime;140141 // memory only142 unsigned int nLastTry;143144 CAddress()145 {146 Init();147 }148149 CAddress(unsigned int ipIn, unsigned short portIn=DEFAULT_PORT, uint64 nServicesIn=NODE_NETWORK)150 {151 Init();152 ip = ipIn;153 port = portIn;154 nServices = nServicesIn;155 }156157 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)158 {159 Init();160 ip = sockaddr.sin_addr.s_addr;161 port = sockaddr.sin_port;162 nServices = nServicesIn;163 }164165 explicit CAddress(const char* pszIn, uint64 nServicesIn=NODE_NETWORK)166 {167 Init();168 SetAddress(pszIn);169 nServices = nServicesIn;170 }171172 explicit CAddress(string strIn, uint64 nServicesIn=NODE_NETWORK)173 {174 Init();175 SetAddress(strIn.c_str());176 nServices = nServicesIn;177 }178179 void Init()180 {181 nServices = NODE_NETWORK;182 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));183 ip = INADDR_NONE;184 port = DEFAULT_PORT;185 nTime = GetAdjustedTime();186 nLastTry = 0;187 }188189 bool SetAddress(const char* pszIn)190 {191 ip = INADDR_NONE;192 port = DEFAULT_PORT;193 char psz[100];194 strlcpy(psz, pszIn, sizeof(psz));195 unsigned int a=0, b=0, c=0, d=0, e=0;196 if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)197 return false;198 char* pszPort = strchr(psz, ':');199 if (pszPort)200 {201 *pszPort++ = '\0';202 port = htons(atoi(pszPort));203 if (atoi(pszPort) < 0 || atoi(pszPort) > USHRT_MAX)204 port = htons(USHRT_MAX);205 }206 ip = inet_addr(psz);207 return IsValid();208 }209210 bool SetAddress(string strIn)211 {212 return SetAddress(strIn.c_str());213 }214215 IMPLEMENT_SERIALIZE216 (217 if (nType & SER_DISK)218 {219 READWRITE(nVersion);220 READWRITE(nTime);221 }222 READWRITE(nServices);223 READWRITE(FLATDATA(pchReserved)); // for IPv6224 READWRITE(ip);225 READWRITE(port);226 )227228 friend inline bool operator==(const CAddress& a, const CAddress& b)229 {230 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&231 a.ip == b.ip &&232 a.port == b.port);233 }234235 friend inline bool operator!=(const CAddress& a, const CAddress& b)236 {237 return (!(a == b));238 }239240 friend inline bool operator<(const CAddress& a, const CAddress& b)241 {242 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));243 if (ret < 0)244 return true;245 else if (ret == 0)246 {247 if (ntohl(a.ip) < ntohl(b.ip))248 return true;249 else if (a.ip == b.ip)250 return ntohs(a.port) < ntohs(b.port);251 }252 return false;253 }254255 vector<unsigned char> GetKey() const256 {257 CDataStream ss;258 ss.reserve(18);259 ss << FLATDATA(pchReserved) << ip << port;260261 #if defined(_MSC_VER) && _MSC_VER < 1300262 return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);263 #else264 return vector<unsigned char>(ss.begin(), ss.end());265 #endif266 }267268 struct sockaddr_in GetSockAddr() const269 {270 struct sockaddr_in sockaddr;271 memset(&sockaddr, 0, sizeof(sockaddr));272 sockaddr.sin_family = AF_INET;273 sockaddr.sin_addr.s_addr = ip;274 sockaddr.sin_port = port;275 return sockaddr;276 }277278 bool IsIPv4() const279 {280 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);281 }282283 bool IsRoutable() const284 {285 return !(GetByte(3) == 10 ||286 (GetByte(3) == 192 && GetByte(2) == 168) ||287 GetByte(3) == 127 ||288 GetByte(3) == 0 ||289 ip == 0 ||290 ip == INADDR_NONE);291 }292293 bool IsValid() const294 {295 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));296 }297298 unsigned char GetByte(int n) const299 {300 return ((unsigned char*)&ip)[3-n];301 }302303 string ToStringIPPort() const304 {305 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));306 }307308 string ToStringIP() const309 {310 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));311 }312313 string ToStringPort() const314 {315 return strprintf("%u", ntohs(port));316 }317318 string ToStringLog() const319 {320 return "";321 }322323 string ToString() const324 {325 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));326 }327328 void print() const329 {330 printf("CAddress(%s)\n", ToString().c_str());331 }332};333334335336337338339340enum341{342 MSG_TX = 1,343 MSG_BLOCK,344 MSG_REVIEW,345 MSG_PRODUCT,346 MSG_TABLE,347};348349static const char* ppszTypeName[] =350{351 "ERROR",352 "tx",353 "block",354 "review",355 "product",356 "table",357};358359class CInv360{361public:362 int type;363 uint256 hash;364365 CInv()366 {367 type = 0;368 hash = 0;369 }370371 CInv(int typeIn, const uint256& hashIn)372 {373 type = typeIn;374 hash = hashIn;375 }376377 CInv(const string& strType, const uint256& hashIn)378 {379 int i;380 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)381 {382 if (strType == ppszTypeName[i])383 {384 type = i;385 break;386 }387 }388 if (i == ARRAYLEN(ppszTypeName))389 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));390 hash = hashIn;391 }392393 IMPLEMENT_SERIALIZE394 (395 READWRITE(type);396 READWRITE(hash);397 )398399 friend inline bool operator<(const CInv& a, const CInv& b)400 {401 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));402 }403404 bool IsKnownType() const405 {406 return (type >= 1 && type < ARRAYLEN(ppszTypeName));407 }408409 const char* GetCommand() const410 {411 if (!IsKnownType())412 throw std::out_of_range(strprintf("CInv::GetCommand() : type=% unknown type", type));413 return ppszTypeName[type];414 }415416 string ToString() const417 {418 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,16).c_str());419 }420421 void print() const422 {423 printf("CInv(%s)\n", ToString().c_str());424 }425};426427428429430431class CRequestTracker432{433public:434 void (*fn)(void*, CDataStream&);435 void* param1;436437 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)438 {439 fn = fnIn;440 param1 = param1In;441 }442443 bool IsNull()444 {445 return fn == NULL;446 }447};448449450451452453extern bool fClient;454extern uint64 nLocalServices;455extern CAddress addrLocalHost;456extern CNode* pnodeLocalHost;457extern uint64 nLocalHostNonce;458extern array<int, 10> vnThreadsRunning;459extern SOCKET hListenSocket;460extern int64 nThreadSocketHandlerHeartbeat;461462extern vector<CNode*> vNodes;463extern CCriticalSection cs_vNodes;464extern map<vector<unsigned char>, CAddress> mapAddresses;465extern CCriticalSection cs_mapAddresses;466extern map<CInv, CDataStream> mapRelay;467extern deque<pair<int64, CInv> > vRelayExpiration;468extern CCriticalSection cs_mapRelay;469extern map<CInv, int64> mapAlreadyAskedFor;470471// Settings472extern int fUseProxy;473extern CAddress addrProxy;474475476477478479class CNode480{481public:482 // socket483 uint64 nServices;484 SOCKET hSocket;485 CDataStream vSend;486 CDataStream vRecv;487 CCriticalSection cs_vSend;488 CCriticalSection cs_vRecv;489 int64 nLastSend;490 int64 nLastRecv;491 int64 nLastSendEmpty;492 int64 nTimeConnected;493 unsigned int nPushPos;494 CAddress addr;495 int nVersion;496 bool fClient;497 bool fInbound;498 bool fNetworkNode;499 bool fSuccessfullyConnected;500 bool fDisconnect;501protected:502 int nRefCount;503public:504 int64 nReleaseTime;505 map<uint256, CRequestTracker> mapRequests;506 CCriticalSection cs_mapRequests;507 uint256 hashContinue;508 CBlockIndex* pindexLastGetBlocksBegin;509 uint256 hashLastGetBlocksEnd;510511 // flood512 vector<CAddress> vAddrToSend;513 set<CAddress> setAddrKnown;514 bool fGetAddr;515516 // inventory based relay517 set<CInv> setInventoryKnown;518 vector<CInv> vInventoryToSend;519 CCriticalSection cs_inventory;520 multimap<int64, CInv> mapAskFor;521522 // publish and subscription523 vector<char> vfSubscribe;524525526 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)527 {528 nServices = 0;529 hSocket = hSocketIn;530 vSend.SetType(SER_NETWORK);531 vRecv.SetType(SER_NETWORK);532 nLastSend = 0;533 nLastRecv = 0;534 nLastSendEmpty = GetTime();535 nTimeConnected = GetTime();536 nPushPos = -1;537 addr = addrIn;538 nVersion = 0;539 fClient = false; // set by version message540 fInbound = fInboundIn;541 fNetworkNode = false;542 fSuccessfullyConnected = false;543 fDisconnect = false;544 nRefCount = 0;545 nReleaseTime = 0;546 hashContinue = 0;547 pindexLastGetBlocksBegin = 0;548 hashLastGetBlocksEnd = 0;549 fGetAddr = false;550 vfSubscribe.assign(256, false);551552 // Push a version message553 /// when NTP implemented, change to just nTime = GetAdjustedTime()554 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());555 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);556 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);557 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));558 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, string(pszSubVer));559 }560561 ~CNode()562 {563 if (hSocket != INVALID_SOCKET)564 {565 closesocket(hSocket);566 hSocket = INVALID_SOCKET;567 }568 }569570private:571 CNode(const CNode&);572 void operator=(const CNode&);573public:574575576 int GetRefCount()577 {578 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);579 }580581 CNode* AddRef(int64 nTimeout=0)582 {583 if (nTimeout != 0)584 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);585 else586 nRefCount++;587 return this;588 }589590 void Release()591 {592 nRefCount--;593 }594595596597 void AddAddressKnown(const CAddress& addr)598 {599 setAddrKnown.insert(addr);600 }601602 void PushAddress(const CAddress& addr)603 {604 // Known checking here is only to save space from duplicates.605 // SendMessages will filter it again for knowns that were added606 // after addresses were pushed.607 if (!setAddrKnown.count(addr))608 vAddrToSend.push_back(addr);609 }610611612 void AddInventoryKnown(const CInv& inv)613 {614 CRITICAL_BLOCK(cs_inventory)615 setInventoryKnown.insert(inv);616 }617618 void PushInventory(const CInv& inv)619 {620 CRITICAL_BLOCK(cs_inventory)621 if (!setInventoryKnown.count(inv))622 vInventoryToSend.push_back(inv);623 }624625 void AskFor(const CInv& inv)626 {627 // We're using mapAskFor as a priority queue,628 // the key is the earliest time the request can be sent629 int64& nRequestTime = mapAlreadyAskedFor[inv];630 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);631632 // Make sure not to reuse time indexes to keep things in the same order633 int64 nNow = (GetTime() - 1) * 1000000;634 static int64 nLastTime;635 nLastTime = nNow = max(nNow, ++nLastTime);636637 // Each retry is 2 minutes after the last638 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);639 mapAskFor.insert(make_pair(nRequestTime, inv));640 }641642643644 void BeginMessage(const char* pszCommand)645 {646 cs_vSend.Enter();647 if (nPushPos != -1)648 AbortMessage();649 nPushPos = vSend.size();650 vSend << CMessageHeader(pszCommand, 0);651 if (fDebug)652 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());653 printf("sending: %s ", pszCommand);654 }655656 void AbortMessage()657 {658 if (nPushPos == -1)659 return;660 vSend.resize(nPushPos);661 nPushPos = -1;662 cs_vSend.Leave();663 printf("(aborted)\n");664 }665666 void EndMessage()667 {668 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)669 {670 printf("dropmessages DROPPING SEND MESSAGE\n");671 AbortMessage();672 return;673 }674675 if (nPushPos == -1)676 return;677678 // Patch in the size679 unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);680 memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));681682 printf("(%d bytes) ", nSize);683 printf("\n");684685 nPushPos = -1;686 cs_vSend.Leave();687 }688689 void EndMessageAbortIfEmpty()690 {691 if (nPushPos == -1)692 return;693 int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);694 if (nSize > 0)695 EndMessage();696 else697 AbortMessage();698 }699700 const char* GetMessageCommand() const701 {702 if (nPushPos == -1)703 return "";704 return &vSend[nPushPos] + offsetof(CMessageHeader, pchCommand);705 }706707708709710 void PushMessage(const char* pszCommand)711 {712 try713 {714 BeginMessage(pszCommand);715 EndMessage();716 }717 catch (...)718 {719 AbortMessage();720 throw;721 }722 }723724 template<typename T1>725 void PushMessage(const char* pszCommand, const T1& a1)726 {727 try728 {729 BeginMessage(pszCommand);730 vSend << a1;731 EndMessage();732 }733 catch (...)734 {735 AbortMessage();736 throw;737 }738 }739740 template<typename T1, typename T2>741 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)742 {743 try744 {745 BeginMessage(pszCommand);746 vSend << a1 << a2;747 EndMessage();748 }749 catch (...)750 {751 AbortMessage();752 throw;753 }754 }755756 template<typename T1, typename T2, typename T3>757 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)758 {759 try760 {761 BeginMessage(pszCommand);762 vSend << a1 << a2 << a3;763 EndMessage();764 }765 catch (...)766 {767 AbortMessage();768 throw;769 }770 }771772 template<typename T1, typename T2, typename T3, typename T4>773 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)774 {775 try776 {777 BeginMessage(pszCommand);778 vSend << a1 << a2 << a3 << a4;779 EndMessage();780 }781 catch (...)782 {783 AbortMessage();784 throw;785 }786 }787788 template<typename T1, typename T2, typename T3, typename T4, typename T5>789 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)790 {791 try792 {793 BeginMessage(pszCommand);794 vSend << a1 << a2 << a3 << a4 << a5;795 EndMessage();796 }797 catch (...)798 {799 AbortMessage();800 throw;801 }802 }803804 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>805 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)806 {807 try808 {809 BeginMessage(pszCommand);810 vSend << a1 << a2 << a3 << a4 << a5 << a6;811 EndMessage();812 }813 catch (...)814 {815 AbortMessage();816 throw;817 }818 }819820 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>821 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)822 {823 try824 {825 BeginMessage(pszCommand);826 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;827 EndMessage();828 }829 catch (...)830 {831 AbortMessage();832 throw;833 }834 }835836 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>837 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)838 {839 try840 {841 BeginMessage(pszCommand);842 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;843 EndMessage();844 }845 catch (...)846 {847 AbortMessage();848 throw;849 }850 }851852 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>853 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)854 {855 try856 {857 BeginMessage(pszCommand);858 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;859 EndMessage();860 }861 catch (...)862 {863 AbortMessage();864 throw;865 }866 }867868869 void PushRequest(const char* pszCommand,870 void (*fn)(void*, CDataStream&), void* param1)871 {872 uint256 hashReply;873 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));874875 CRITICAL_BLOCK(cs_mapRequests)876 mapRequests[hashReply] = CRequestTracker(fn, param1);877878 PushMessage(pszCommand, hashReply);879 }880881 template<typename T1>882 void PushRequest(const char* pszCommand, const T1& a1,883 void (*fn)(void*, CDataStream&), void* param1)884 {885 uint256 hashReply;886 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));887888 CRITICAL_BLOCK(cs_mapRequests)889 mapRequests[hashReply] = CRequestTracker(fn, param1);890891 PushMessage(pszCommand, hashReply, a1);892 }893894 template<typename T1, typename T2>895 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,896 void (*fn)(void*, CDataStream&), void* param1)897 {898 uint256 hashReply;899 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));900901 CRITICAL_BLOCK(cs_mapRequests)902 mapRequests[hashReply] = CRequestTracker(fn, param1);903904 PushMessage(pszCommand, hashReply, a1, a2);905 }906907908909 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);910 bool IsSubscribed(unsigned int nChannel);911 void Subscribe(unsigned int nChannel, unsigned int nHops=0);912 void CancelSubscribe(unsigned int nChannel);913 void CloseSocketDisconnect();914 void Cleanup();915};916917918919920921922923924925926inline void RelayInventory(const CInv& inv)927{928 // Put on lists to offer to the other nodes929 CRITICAL_BLOCK(cs_vNodes)930 foreach(CNode* pnode, vNodes)931 pnode->PushInventory(inv);932}933934template<typename T>935void RelayMessage(const CInv& inv, const T& a)936{937 CDataStream ss(SER_NETWORK);938 ss.reserve(10000);939 ss << a;940 RelayMessage(inv, ss);941}942943template<>944inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)945{946 CRITICAL_BLOCK(cs_mapRelay)947 {948 // Expire old relay messages949 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())950 {951 mapRelay.erase(vRelayExpiration.front().second);952 vRelayExpiration.pop_front();953 }954955 // Save original serialized message so newer versions are preserved956 mapRelay[inv] = ss;957 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));958 }959960 RelayInventory(inv);961}962963964965966967968969970//971// Templates for the publish and subscription system.972// The object being published as T& obj needs to have:973// a set<unsigned int> setSources member974// specializations of AdvertInsert and AdvertErase975// Currently implemented for CTable and CProduct.976//977978template<typename T>979void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)980{981 // Add to sources982 obj.setSources.insert(pfrom->addr.ip);983984 if (!AdvertInsert(obj))985 return;986987 // Relay988 CRITICAL_BLOCK(cs_vNodes)989 foreach(CNode* pnode, vNodes)990 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))991 pnode->PushMessage("publish", nChannel, nHops, obj);992}993994template<typename T>995void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)996{997 uint256 hash = obj.GetHash();998999 CRITICAL_BLOCK(cs_vNodes)1000 foreach(CNode* pnode, vNodes)1001 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))1002 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);10031004 AdvertErase(obj);1005}10061007template<typename T>1008void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)1009{1010 // Remove a source1011 obj.setSources.erase(pfrom->addr.ip);10121013 // If no longer supported by any sources, cancel it1014 if (obj.setSources.empty())1015 AdvertStopPublish(pfrom, nChannel, nHops, obj);1016}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
