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, CAddress addr, bool fCurrentlyOnline=true);
\r
26 void AddressCurrentlyConnected(const CAddress& addr);
\r
27 CNode* FindNode(unsigned int ip);
\r
28 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
\r
29 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
\r
30 bool AnySubscribed(unsigned int nChannel);
\r
31 bool StartNode(string& strError=REF(string()));
\r
33 void CheckForShutdown(int n);
\r
45 // (4) message start
\r
49 // The message start string is designed to be unlikely to occur in normal data.
\r
50 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
\r
51 // a large 4-byte int at any alignment.
\r
52 static const char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
\r
54 class CMessageHeader
\r
57 enum { COMMAND_SIZE=12 };
\r
58 char pchMessageStart[sizeof(::pchMessageStart)];
\r
59 char pchCommand[COMMAND_SIZE];
\r
60 unsigned int nMessageSize;
\r
64 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
\r
65 memset(pchCommand, 0, sizeof(pchCommand));
\r
70 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
\r
72 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
\r
73 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
\r
74 nMessageSize = nMessageSizeIn;
\r
79 READWRITE(FLATDATA(pchMessageStart));
\r
80 READWRITE(FLATDATA(pchCommand));
\r
81 READWRITE(nMessageSize);
\r
86 if (pchCommand[COMMAND_SIZE-1] == 0)
\r
87 return string(pchCommand, pchCommand + strlen(pchCommand));
\r
89 return string(pchCommand, pchCommand + COMMAND_SIZE);
\r
94 // Check start string
\r
95 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
\r
98 // Check the command string for errors
\r
99 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
\r
103 // Must be all zeros after the first zero
\r
104 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
\r
108 else if (*p1 < ' ' || *p1 > 0x7E)
\r
113 if (nMessageSize > 0x10000000)
\r
115 printf("CMessageHeader::IsValid() : nMessageSize too large %u\n", nMessageSize);
\r
128 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
\r
134 unsigned char pchReserved[12];
\r
136 unsigned short port;
\r
139 unsigned int nTime;
\r
142 unsigned int nLastFailed;
\r
149 CAddress(unsigned int ipIn, unsigned short portIn=DEFAULT_PORT, uint64 nServicesIn=NODE_NETWORK)
\r
154 nServices = nServicesIn;
\r
157 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
\r
160 ip = sockaddr.sin_addr.s_addr;
\r
161 port = sockaddr.sin_port;
\r
162 nServices = nServicesIn;
\r
165 explicit CAddress(const char* pszIn, uint64 nServicesIn=NODE_NETWORK)
\r
169 nServices = nServicesIn;
\r
172 explicit CAddress(string strIn, uint64 nServicesIn=NODE_NETWORK)
\r
175 SetAddress(strIn.c_str());
\r
176 nServices = nServicesIn;
\r
181 nServices = NODE_NETWORK;
\r
182 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
184 port = DEFAULT_PORT;
\r
185 nTime = GetAdjustedTime();
\r
189 bool SetAddress(const char* pszIn)
\r
192 port = DEFAULT_PORT;
\r
194 strlcpy(psz, pszIn, sizeof(psz));
\r
195 unsigned int a=0, b=0, c=0, d=0, e=0;
\r
196 if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)
\r
198 char* pszPort = strchr(psz, ':');
\r
202 port = htons(atoi(pszPort));
\r
203 if (atoi(pszPort) < 0 || atoi(pszPort) > USHRT_MAX)
\r
204 port = htons(USHRT_MAX);
\r
206 ip = inet_addr(psz);
\r
210 bool SetAddress(string strIn)
\r
212 return SetAddress(strIn.c_str());
\r
215 IMPLEMENT_SERIALIZE
\r
217 if (nType & SER_DISK)
\r
219 READWRITE(nVersion);
\r
222 READWRITE(nServices);
\r
223 READWRITE(FLATDATA(pchReserved)); // for IPv6
\r
228 friend inline bool operator==(const CAddress& a, const CAddress& b)
\r
230 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
\r
235 friend inline bool operator!=(const CAddress& a, const CAddress& b)
\r
237 return (!(a == b));
\r
240 friend inline bool operator<(const CAddress& a, const CAddress& b)
\r
242 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
\r
247 if (ntohl(a.ip) < ntohl(b.ip))
\r
249 else if (a.ip == b.ip)
\r
250 return ntohs(a.port) < ntohs(b.port);
\r
255 vector<unsigned char> GetKey() const
\r
259 ss << FLATDATA(pchReserved) << ip << port;
\r
261 #if defined(_MSC_VER) && _MSC_VER < 1300
\r
262 return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
\r
264 return vector<unsigned char>(ss.begin(), ss.end());
\r
268 struct sockaddr_in GetSockAddr() const
\r
270 struct sockaddr_in sockaddr;
\r
271 sockaddr.sin_family = AF_INET;
\r
272 sockaddr.sin_addr.s_addr = ip;
\r
273 sockaddr.sin_port = port;
\r
277 bool IsIPv4() const
\r
279 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
\r
282 bool IsRoutable() const
\r
284 return !(GetByte(3) == 10 ||
\r
285 (GetByte(3) == 192 && GetByte(2) == 168) ||
\r
286 GetByte(3) == 127 ||
\r
289 ip == INADDR_NONE);
\r
292 bool IsValid() const
\r
294 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
\r
297 unsigned char GetByte(int n) const
\r
299 return ((unsigned char*)&ip)[3-n];
\r
302 string ToStringIPPort() const
\r
304 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
\r
307 string ToStringIP() const
\r
309 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
\r
312 string ToStringPort() const
\r
314 return strprintf("%u", ntohs(port));
\r
317 string ToStringLog() const
\r
322 string ToString() const
\r
324 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
\r
329 printf("CAddress(%s)\n", ToString().c_str());
\r
348 static const char* ppszTypeName[] =
\r
370 CInv(int typeIn, const uint256& hashIn)
\r
376 CInv(const string& strType, const uint256& hashIn)
\r
379 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
\r
381 if (strType == ppszTypeName[i])
\r
387 if (i == ARRAYLEN(ppszTypeName))
\r
388 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
\r
392 IMPLEMENT_SERIALIZE
\r
398 friend inline bool operator<(const CInv& a, const CInv& b)
\r
400 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
\r
403 bool IsKnownType() const
\r
405 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
\r
408 const char* GetCommand() const
\r
410 if (!IsKnownType())
\r
411 throw std::out_of_range(strprintf("CInv::GetCommand() : type=% unknown type", type));
\r
412 return ppszTypeName[type];
\r
415 string ToString() const
\r
417 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,14).c_str());
\r
422 printf("CInv(%s)\n", ToString().c_str());
\r
430 class CRequestTracker
\r
433 void (*fn)(void*, CDataStream&);
\r
436 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
\r
452 extern bool fClient;
\r
453 extern uint64 nLocalServices;
\r
454 extern CAddress addrLocalHost;
\r
455 extern CNode* pnodeLocalHost;
\r
456 extern uint64 nLocalHostNonce;
\r
457 extern bool fShutdown;
\r
458 extern array<int, 10> vnThreadsRunning;
\r
459 extern vector<CNode*> vNodes;
\r
460 extern CCriticalSection cs_vNodes;
\r
461 extern map<vector<unsigned char>, CAddress> mapAddresses;
\r
462 extern CCriticalSection cs_mapAddresses;
\r
463 extern map<CInv, CDataStream> mapRelay;
\r
464 extern deque<pair<int64, CInv> > vRelayExpiration;
\r
465 extern CCriticalSection cs_mapRelay;
\r
466 extern map<CInv, int64> mapAlreadyAskedFor;
\r
469 extern int fUseProxy;
\r
470 extern CAddress addrProxy;
\r
484 CCriticalSection cs_vSend;
\r
485 CCriticalSection cs_vRecv;
\r
486 unsigned int nPushPos;
\r
492 bool fSuccessfullyConnected;
\r
497 int64 nReleaseTime;
\r
498 map<uint256, CRequestTracker> mapRequests;
\r
499 CCriticalSection cs_mapRequests;
\r
502 vector<CAddress> vAddrToSend;
\r
503 set<CAddress> setAddrKnown;
\r
506 // inventory based relay
\r
507 set<CInv> setInventoryKnown;
\r
508 set<CInv> setInventoryKnown2;
\r
509 vector<CInv> vInventoryToSend;
\r
510 CCriticalSection cs_inventory;
\r
511 multimap<int64, CInv> mapAskFor;
\r
513 // publish and subscription
\r
514 vector<char> vfSubscribe;
\r
517 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
\r
520 hSocket = hSocketIn;
\r
521 vSend.SetType(SER_NETWORK);
\r
522 vRecv.SetType(SER_NETWORK);
\r
526 fClient = false; // set by version message
\r
527 fInbound = fInboundIn;
\r
528 fNetworkNode = false;
\r
529 fSuccessfullyConnected = false;
\r
530 fDisconnect = false;
\r
534 vfSubscribe.assign(256, false);
\r
536 // Push a version message
\r
537 /// when NTP implemented, change to just nTime = GetAdjustedTime()
\r
538 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
\r
539 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
\r
540 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
\r
541 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
\r
542 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce);
\r
547 if (hSocket != INVALID_SOCKET)
\r
548 closesocket(hSocket);
\r
552 CNode(const CNode&);
\r
553 void operator=(const CNode&);
\r
557 bool ReadyToDisconnect()
\r
559 return fDisconnect || GetRefCount() <= 0;
\r
564 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
\r
567 void AddRef(int64 nTimeout=0)
\r
570 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);
\r
582 void AddAddressKnown(const CAddress& addr)
\r
584 setAddrKnown.insert(addr);
\r
587 void PushAddress(const CAddress& addr)
\r
589 // Known checking here is only to save space from duplicates.
\r
590 // SendMessages will filter it again for knowns that were added
\r
591 // after addresses were pushed.
\r
592 if (!setAddrKnown.count(addr))
\r
593 vAddrToSend.push_back(addr);
\r
597 void AddInventoryKnown(const CInv& inv)
\r
599 CRITICAL_BLOCK(cs_inventory)
\r
600 setInventoryKnown.insert(inv);
\r
603 void PushInventory(const CInv& inv)
\r
605 CRITICAL_BLOCK(cs_inventory)
\r
606 if (!setInventoryKnown.count(inv))
\r
607 vInventoryToSend.push_back(inv);
\r
610 void AskFor(const CInv& inv)
\r
612 // We're using mapAskFor as a priority queue,
\r
613 // the key is the earliest time the request can be sent
\r
614 int64& nRequestTime = mapAlreadyAskedFor[inv];
\r
615 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
\r
617 // Make sure not to reuse time indexes to keep things in the same order
\r
618 int64 nNow = (GetTime() - 1) * 1000000;
\r
619 static int64 nLastTime;
\r
620 nLastTime = nNow = max(nNow, ++nLastTime);
\r
622 // Each retry is 2 minutes after the last
\r
623 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);
\r
624 mapAskFor.insert(make_pair(nRequestTime, inv));
\r
628 void BeginMessage(const char* pszCommand)
\r
631 if (nPushPos != -1)
\r
633 nPushPos = vSend.size();
\r
634 vSend << CMessageHeader(pszCommand, 0);
\r
635 printf("sending: %s ", pszCommand);
\r
638 void AbortMessage()
\r
640 if (nPushPos == -1)
\r
642 vSend.resize(nPushPos);
\r
645 printf("(aborted)\n");
\r
650 extern int nDropMessagesTest;
\r
651 if (nDropMessagesTest > 0 && GetRand(nDropMessagesTest) == 0)
\r
653 printf("dropmessages DROPPING SEND MESSAGE\n");
\r
658 if (nPushPos == -1)
\r
661 // Patch in the size
\r
662 unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
663 memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
\r
665 printf("(%d bytes) ", nSize);
\r
672 void EndMessageAbortIfEmpty()
\r
674 if (nPushPos == -1)
\r
676 int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
683 const char* GetMessageCommand() const
\r
685 if (nPushPos == -1)
\r
687 return &vSend[nPushPos] + offsetof(CMessageHeader, pchCommand);
\r
693 void PushMessage(const char* pszCommand)
\r
697 BeginMessage(pszCommand);
\r
707 template<typename T1>
\r
708 void PushMessage(const char* pszCommand, const T1& a1)
\r
712 BeginMessage(pszCommand);
\r
723 template<typename T1, typename T2>
\r
724 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
\r
728 BeginMessage(pszCommand);
\r
739 template<typename T1, typename T2, typename T3>
\r
740 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
\r
744 BeginMessage(pszCommand);
\r
745 vSend << a1 << a2 << a3;
\r
755 template<typename T1, typename T2, typename T3, typename T4>
\r
756 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
\r
760 BeginMessage(pszCommand);
\r
761 vSend << a1 << a2 << a3 << a4;
\r
771 template<typename T1, typename T2, typename T3, typename T4, typename T5>
\r
772 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
\r
776 BeginMessage(pszCommand);
\r
777 vSend << a1 << a2 << a3 << a4 << a5;
\r
787 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
\r
788 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
\r
792 BeginMessage(pszCommand);
\r
793 vSend << a1 << a2 << a3 << a4 << a5 << a6;
\r
803 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
\r
804 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
808 BeginMessage(pszCommand);
\r
809 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
\r
819 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
\r
820 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
824 BeginMessage(pszCommand);
\r
825 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
\r
835 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
\r
836 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
840 BeginMessage(pszCommand);
\r
841 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
\r
852 void PushRequest(const char* pszCommand,
\r
853 void (*fn)(void*, CDataStream&), void* param1)
\r
856 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
858 CRITICAL_BLOCK(cs_mapRequests)
\r
859 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
861 PushMessage(pszCommand, hashReply);
\r
864 template<typename T1>
\r
865 void PushRequest(const char* pszCommand, const T1& a1,
\r
866 void (*fn)(void*, CDataStream&), void* param1)
\r
869 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
871 CRITICAL_BLOCK(cs_mapRequests)
\r
872 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
874 PushMessage(pszCommand, hashReply, a1);
\r
877 template<typename T1, typename T2>
\r
878 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
\r
879 void (*fn)(void*, CDataStream&), void* param1)
\r
882 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
884 CRITICAL_BLOCK(cs_mapRequests)
\r
885 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
887 PushMessage(pszCommand, hashReply, a1, a2);
\r
892 bool IsSubscribed(unsigned int nChannel);
\r
893 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
\r
894 void CancelSubscribe(unsigned int nChannel);
\r
895 void DoDisconnect();
\r
907 inline void RelayInventory(const CInv& inv)
\r
909 // Put on lists to offer to the other nodes
\r
910 CRITICAL_BLOCK(cs_vNodes)
\r
911 foreach(CNode* pnode, vNodes)
\r
912 pnode->PushInventory(inv);
\r
915 template<typename T>
\r
916 void RelayMessage(const CInv& inv, const T& a)
\r
918 CDataStream ss(SER_NETWORK);
\r
921 RelayMessage(inv, ss);
\r
925 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
\r
927 CRITICAL_BLOCK(cs_mapRelay)
\r
929 // Expire old relay messages
\r
930 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
\r
932 mapRelay.erase(vRelayExpiration.front().second);
\r
933 vRelayExpiration.pop_front();
\r
936 // Save original serialized message so newer versions are preserved
\r
937 mapRelay[inv] = ss;
\r
938 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));
\r
941 RelayInventory(inv);
\r
952 // Templates for the publish and subscription system.
\r
953 // The object being published as T& obj needs to have:
\r
954 // a set<unsigned int> setSources member
\r
955 // specializations of AdvertInsert and AdvertErase
\r
956 // Currently implemented for CTable and CProduct.
\r
959 template<typename T>
\r
960 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
963 obj.setSources.insert(pfrom->addr.ip);
\r
965 if (!AdvertInsert(obj))
\r
969 CRITICAL_BLOCK(cs_vNodes)
\r
970 foreach(CNode* pnode, vNodes)
\r
971 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
972 pnode->PushMessage("publish", nChannel, nHops, obj);
\r
975 template<typename T>
\r
976 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
978 uint256 hash = obj.GetHash();
\r
980 CRITICAL_BLOCK(cs_vNodes)
\r
981 foreach(CNode* pnode, vNodes)
\r
982 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
983 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
\r
988 template<typename T>
\r
989 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
992 obj.setSources.erase(pfrom->addr.ip);
\r
994 // If no longer supported by any sources, cancel it
\r
995 if (obj.setSources.empty())
\r
996 AdvertStopPublish(pfrom, nChannel, nHops, obj);
\r