1 // Copyright (c) 2009 Satoshi Nakamoto
\r
2 // Distributed under the MIT/X11 software license, see the accompanying
\r
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
\r
5 class CMessageHeader;
\r
8 class CRequestTracker;
\r
13 static const unsigned short DEFAULT_PORT = htons(8333);
\r
14 static const unsigned int PUBLISH_HOPS = 5;
\r
17 NODE_NETWORK = (1 << 0),
\r
23 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);
\r
24 bool GetMyExternalIP(unsigned int& ipRet);
\r
25 bool AddAddress(CAddrDB& addrdb, const CAddress& addr);
\r
26 CNode* FindNode(unsigned int ip);
\r
27 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
\r
28 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
\r
29 bool AnySubscribed(unsigned int nChannel);
\r
30 bool StartNode(string& strError=REF(string()));
\r
32 void CheckForShutdown(int n);
\r
44 // (4) message start
\r
48 // The message start string is designed to be unlikely to occur in normal data.
\r
49 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
\r
50 // a large 4-byte int at any alignment.
\r
51 static const char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
\r
53 class CMessageHeader
\r
56 enum { COMMAND_SIZE=12 };
\r
57 char pchMessageStart[sizeof(::pchMessageStart)];
\r
58 char pchCommand[COMMAND_SIZE];
\r
59 unsigned int nMessageSize;
\r
63 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
\r
64 memset(pchCommand, 0, sizeof(pchCommand));
\r
69 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
\r
71 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
\r
72 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
\r
73 nMessageSize = nMessageSizeIn;
\r
78 READWRITE(FLATDATA(pchMessageStart));
\r
79 READWRITE(FLATDATA(pchCommand));
\r
80 READWRITE(nMessageSize);
\r
85 if (pchCommand[COMMAND_SIZE-1] == 0)
\r
86 return string(pchCommand, pchCommand + strlen(pchCommand));
\r
88 return string(pchCommand, pchCommand + COMMAND_SIZE);
\r
93 // Check start string
\r
94 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
\r
97 // Check the command string for errors
\r
98 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
\r
102 // Must be all zeros after the first zero
\r
103 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
\r
107 else if (*p1 < ' ' || *p1 > 0x7E)
\r
112 if (nMessageSize > 0x10000000)
\r
114 printf("CMessageHeader::IsValid() : nMessageSize too large %u\n", nMessageSize);
\r
127 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
\r
133 unsigned char pchReserved[12];
\r
135 unsigned short port;
\r
138 unsigned int nTime;
\r
141 unsigned int nLastFailed;
\r
146 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
148 port = DEFAULT_PORT;
\r
149 nTime = GetAdjustedTime();
\r
153 CAddress(unsigned int ipIn, unsigned short portIn=DEFAULT_PORT, uint64 nServicesIn=0)
\r
155 nServices = nServicesIn;
\r
156 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
159 nTime = GetAdjustedTime();
\r
163 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=0)
\r
165 nServices = nServicesIn;
\r
166 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
167 ip = sockaddr.sin_addr.s_addr;
\r
168 port = sockaddr.sin_port;
\r
169 nTime = GetAdjustedTime();
\r
173 explicit CAddress(const char* pszIn, uint64 nServicesIn=0)
\r
175 nServices = nServicesIn;
\r
176 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
178 port = DEFAULT_PORT;
\r
179 nTime = GetAdjustedTime();
\r
183 if (strlen(pszIn) > ARRAYLEN(psz)-1)
\r
185 strcpy(psz, pszIn);
\r
186 unsigned int a=0, b=0, c=0, d=0, e=0;
\r
187 if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)
\r
189 char* pszPort = strchr(psz, ':');
\r
193 port = htons(atoi(pszPort));
\r
194 if (atoi(pszPort) > USHRT_MAX)
\r
195 port = htons(USHRT_MAX);
\r
196 if (atoi(pszPort) < 0)
\r
199 ip = inet_addr(psz);
\r
202 IMPLEMENT_SERIALIZE
\r
204 if (nType & SER_DISK)
\r
206 READWRITE(nVersion);
\r
209 READWRITE(nServices);
\r
210 READWRITE(FLATDATA(pchReserved)); // for IPv6
\r
215 friend inline bool operator==(const CAddress& a, const CAddress& b)
\r
217 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
\r
222 friend inline bool operator!=(const CAddress& a, const CAddress& b)
\r
224 return (!(a == b));
\r
227 friend inline bool operator<(const CAddress& a, const CAddress& b)
\r
229 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
\r
234 if (ntohl(a.ip) < ntohl(b.ip))
\r
236 else if (a.ip == b.ip)
\r
237 return ntohs(a.port) < ntohs(b.port);
\r
242 vector<unsigned char> GetKey() const
\r
246 ss << FLATDATA(pchReserved) << ip << port;
\r
248 #if defined(_MSC_VER) && _MSC_VER < 1300
\r
249 return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
\r
251 return vector<unsigned char>(ss.begin(), ss.end());
\r
255 struct sockaddr_in GetSockAddr() const
\r
257 struct sockaddr_in sockaddr;
\r
258 sockaddr.sin_family = AF_INET;
\r
259 sockaddr.sin_addr.s_addr = ip;
\r
260 sockaddr.sin_port = port;
\r
264 bool IsIPv4() const
\r
266 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
\r
269 bool IsRoutable() const
\r
271 return !(GetByte(3) == 10 || (GetByte(3) == 192 && GetByte(2) == 168) || GetByte(3) == 127 || GetByte(3) == 0);
\r
274 unsigned char GetByte(int n) const
\r
276 return ((unsigned char*)&ip)[3-n];
\r
279 string ToStringIPPort() const
\r
281 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
\r
284 string ToStringIP() const
\r
286 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
\r
289 string ToStringPort() const
\r
291 return strprintf("%u", ntohs(port));
\r
294 string ToStringLog() const
\r
299 string ToString() const
\r
301 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
\r
306 printf("CAddress(%s)\n", ToString().c_str());
\r
325 static const char* ppszTypeName[] =
\r
347 CInv(int typeIn, const uint256& hashIn)
\r
353 CInv(const string& strType, const uint256& hashIn)
\r
356 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
\r
358 if (strType == ppszTypeName[i])
\r
364 if (i == ARRAYLEN(ppszTypeName))
\r
365 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
\r
369 IMPLEMENT_SERIALIZE
\r
375 friend inline bool operator<(const CInv& a, const CInv& b)
\r
377 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
\r
380 bool IsKnownType() const
\r
382 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
\r
385 const char* GetCommand() const
\r
387 if (!IsKnownType())
\r
388 throw std::out_of_range(strprintf("CInv::GetCommand() : type=% unknown type", type));
\r
389 return ppszTypeName[type];
\r
392 string ToString() const
\r
394 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,14).c_str());
\r
399 printf("CInv(%s)\n", ToString().c_str());
\r
407 class CRequestTracker
\r
410 void (*fn)(void*, CDataStream&);
\r
413 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
\r
429 extern bool fClient;
\r
430 extern uint64 nLocalServices;
\r
431 extern CAddress addrLocalHost;
\r
432 extern CNode* pnodeLocalHost;
\r
433 extern uint64 nLocalHostNonce;
\r
434 extern bool fShutdown;
\r
435 extern array<int, 10> vnThreadsRunning;
\r
436 extern vector<CNode*> vNodes;
\r
437 extern CCriticalSection cs_vNodes;
\r
438 extern map<vector<unsigned char>, CAddress> mapAddresses;
\r
439 extern CCriticalSection cs_mapAddresses;
\r
440 extern map<CInv, CDataStream> mapRelay;
\r
441 extern deque<pair<int64, CInv> > vRelayExpiration;
\r
442 extern CCriticalSection cs_mapRelay;
\r
443 extern map<CInv, int64> mapAlreadyAskedFor;
\r
446 extern int fUseProxy;
\r
447 extern CAddress addrProxy;
\r
461 CCriticalSection cs_vSend;
\r
462 CCriticalSection cs_vRecv;
\r
463 unsigned int nPushPos;
\r
469 bool fSuccessfullyConnected;
\r
474 int64 nReleaseTime;
\r
475 map<uint256, CRequestTracker> mapRequests;
\r
476 CCriticalSection cs_mapRequests;
\r
479 vector<CAddress> vAddrToSend;
\r
480 set<CAddress> setAddrKnown;
\r
483 // inventory based relay
\r
484 set<CInv> setInventoryKnown;
\r
485 set<CInv> setInventoryKnown2;
\r
486 vector<CInv> vInventoryToSend;
\r
487 CCriticalSection cs_inventory;
\r
488 multimap<int64, CInv> mapAskFor;
\r
490 // publish and subscription
\r
491 vector<char> vfSubscribe;
\r
494 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
\r
497 hSocket = hSocketIn;
\r
498 vSend.SetType(SER_NETWORK);
\r
499 vRecv.SetType(SER_NETWORK);
\r
503 fClient = false; // set by version message
\r
504 fInbound = fInboundIn;
\r
505 fNetworkNode = false;
\r
506 fSuccessfullyConnected = false;
\r
507 fDisconnect = false;
\r
511 vfSubscribe.assign(256, false);
\r
513 // Push a version message
\r
514 /// when NTP implemented, change to just nTime = GetAdjustedTime()
\r
515 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
\r
516 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
\r
517 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
\r
518 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
\r
519 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce);
\r
524 if (hSocket != INVALID_SOCKET)
\r
525 closesocket(hSocket);
\r
529 CNode(const CNode&);
\r
530 void operator=(const CNode&);
\r
534 bool ReadyToDisconnect()
\r
536 return fDisconnect || GetRefCount() <= 0;
\r
541 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
\r
544 void AddRef(int64 nTimeout=0)
\r
547 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);
\r
559 void AddAddressKnown(const CAddress& addr)
\r
561 setAddrKnown.insert(addr);
\r
564 void PushAddress(const CAddress& addr)
\r
566 // Known checking here is only to save space from duplicates.
\r
567 // SendMessages will filter it again for knowns that were added
\r
568 // after addresses were pushed.
\r
569 if (!setAddrKnown.count(addr))
\r
570 vAddrToSend.push_back(addr);
\r
574 void AddInventoryKnown(const CInv& inv)
\r
576 CRITICAL_BLOCK(cs_inventory)
\r
577 setInventoryKnown.insert(inv);
\r
580 void PushInventory(const CInv& inv)
\r
582 CRITICAL_BLOCK(cs_inventory)
\r
583 if (!setInventoryKnown.count(inv))
\r
584 vInventoryToSend.push_back(inv);
\r
587 void AskFor(const CInv& inv)
\r
589 // We're using mapAskFor as a priority queue,
\r
590 // the key is the earliest time the request can be sent
\r
591 int64& nRequestTime = mapAlreadyAskedFor[inv];
\r
592 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
\r
594 // Make sure not to reuse time indexes to keep things in the same order
\r
595 int64 nNow = (GetTime() - 1) * 1000000;
\r
596 static int64 nLastTime;
\r
597 nLastTime = nNow = max(nNow, ++nLastTime);
\r
599 // Each retry is 2 minutes after the last
\r
600 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);
\r
601 mapAskFor.insert(make_pair(nRequestTime, inv));
\r
605 void BeginMessage(const char* pszCommand)
\r
608 if (nPushPos != -1)
\r
610 nPushPos = vSend.size();
\r
611 vSend << CMessageHeader(pszCommand, 0);
\r
612 printf("sending: %s ", pszCommand);
\r
615 void AbortMessage()
\r
617 if (nPushPos == -1)
\r
619 vSend.resize(nPushPos);
\r
622 printf("(aborted)\n");
\r
627 extern int nDropMessagesTest;
\r
628 if (nDropMessagesTest > 0 && GetRand(nDropMessagesTest) == 0)
\r
630 printf("dropmessages DROPPING SEND MESSAGE\n");
\r
635 if (nPushPos == -1)
\r
638 // Patch in the size
\r
639 unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
640 memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
\r
642 printf("(%d bytes) ", nSize);
\r
649 void EndMessageAbortIfEmpty()
\r
651 if (nPushPos == -1)
\r
653 int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
660 const char* GetMessageCommand() const
\r
662 if (nPushPos == -1)
\r
664 return &vSend[nPushPos] + offsetof(CMessageHeader, pchCommand);
\r
670 void PushMessage(const char* pszCommand)
\r
674 BeginMessage(pszCommand);
\r
684 template<typename T1>
\r
685 void PushMessage(const char* pszCommand, const T1& a1)
\r
689 BeginMessage(pszCommand);
\r
700 template<typename T1, typename T2>
\r
701 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
\r
705 BeginMessage(pszCommand);
\r
716 template<typename T1, typename T2, typename T3>
\r
717 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
\r
721 BeginMessage(pszCommand);
\r
722 vSend << a1 << a2 << a3;
\r
732 template<typename T1, typename T2, typename T3, typename T4>
\r
733 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
\r
737 BeginMessage(pszCommand);
\r
738 vSend << a1 << a2 << a3 << a4;
\r
748 template<typename T1, typename T2, typename T3, typename T4, typename T5>
\r
749 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
\r
753 BeginMessage(pszCommand);
\r
754 vSend << a1 << a2 << a3 << a4 << a5;
\r
764 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
\r
765 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
\r
769 BeginMessage(pszCommand);
\r
770 vSend << a1 << a2 << a3 << a4 << a5 << a6;
\r
780 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
\r
781 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)
\r
785 BeginMessage(pszCommand);
\r
786 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
\r
796 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
\r
797 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)
\r
801 BeginMessage(pszCommand);
\r
802 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
\r
812 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
\r
813 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)
\r
817 BeginMessage(pszCommand);
\r
818 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
\r
829 void PushRequest(const char* pszCommand,
\r
830 void (*fn)(void*, CDataStream&), void* param1)
\r
833 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
835 CRITICAL_BLOCK(cs_mapRequests)
\r
836 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
838 PushMessage(pszCommand, hashReply);
\r
841 template<typename T1>
\r
842 void PushRequest(const char* pszCommand, const T1& a1,
\r
843 void (*fn)(void*, CDataStream&), void* param1)
\r
846 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
848 CRITICAL_BLOCK(cs_mapRequests)
\r
849 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
851 PushMessage(pszCommand, hashReply, a1);
\r
854 template<typename T1, typename T2>
\r
855 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
\r
856 void (*fn)(void*, CDataStream&), void* param1)
\r
859 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
861 CRITICAL_BLOCK(cs_mapRequests)
\r
862 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
864 PushMessage(pszCommand, hashReply, a1, a2);
\r
869 bool IsSubscribed(unsigned int nChannel);
\r
870 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
\r
871 void CancelSubscribe(unsigned int nChannel);
\r
872 void DoDisconnect();
\r
884 inline void RelayInventory(const CInv& inv)
\r
886 // Put on lists to offer to the other nodes
\r
887 CRITICAL_BLOCK(cs_vNodes)
\r
888 foreach(CNode* pnode, vNodes)
\r
889 pnode->PushInventory(inv);
\r
892 template<typename T>
\r
893 void RelayMessage(const CInv& inv, const T& a)
\r
895 CDataStream ss(SER_NETWORK);
\r
898 RelayMessage(inv, ss);
\r
902 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
\r
904 CRITICAL_BLOCK(cs_mapRelay)
\r
906 // Expire old relay messages
\r
907 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
\r
909 mapRelay.erase(vRelayExpiration.front().second);
\r
910 vRelayExpiration.pop_front();
\r
913 // Save original serialized message so newer versions are preserved
\r
914 mapRelay[inv] = ss;
\r
915 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));
\r
918 RelayInventory(inv);
\r
929 // Templates for the publish and subscription system.
\r
930 // The object being published as T& obj needs to have:
\r
931 // a set<unsigned int> setSources member
\r
932 // specializations of AdvertInsert and AdvertErase
\r
933 // Currently implemented for CTable and CProduct.
\r
936 template<typename T>
\r
937 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
940 obj.setSources.insert(pfrom->addr.ip);
\r
942 if (!AdvertInsert(obj))
\r
946 CRITICAL_BLOCK(cs_vNodes)
\r
947 foreach(CNode* pnode, vNodes)
\r
948 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
949 pnode->PushMessage("publish", nChannel, nHops, obj);
\r
952 template<typename T>
\r
953 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
955 uint256 hash = obj.GetHash();
\r
957 CRITICAL_BLOCK(cs_vNodes)
\r
958 foreach(CNode* pnode, vNodes)
\r
959 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
960 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
\r
965 template<typename T>
\r
966 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
969 obj.setSources.erase(pfrom->addr.ip);
\r
971 // If no longer supported by any sources, cancel it
\r
972 if (obj.setSources.empty())
\r
973 AdvertStopPublish(pfrom, nChannel, nHops, obj);
\r