1 // Copyright (c) 2009-2010 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
14 static const unsigned short DEFAULT_PORT = htons(8333);
\r
15 static const unsigned int PUBLISH_HOPS = 5;
\r
18 NODE_NETWORK = (1 << 0),
\r
24 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);
\r
25 bool GetMyExternalIP(unsigned int& ipRet);
\r
26 bool AddAddress(CAddress addr, bool fCurrentlyOnline=true);
\r
27 void AddressCurrentlyConnected(const CAddress& addr);
\r
28 CNode* FindNode(unsigned int ip);
\r
29 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
\r
30 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
\r
31 bool AnySubscribed(unsigned int nChannel);
\r
32 bool BindListenPort(string& strError=REF(string()));
\r
33 void StartNode(void* parg);
\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 nLastTry;
\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 memset(&sockaddr, 0, sizeof(sockaddr));
\r
272 sockaddr.sin_family = AF_INET;
\r
273 sockaddr.sin_addr.s_addr = ip;
\r
274 sockaddr.sin_port = port;
\r
278 bool IsIPv4() const
\r
280 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
\r
283 bool IsRoutable() const
\r
285 return !(GetByte(3) == 10 ||
\r
286 (GetByte(3) == 192 && GetByte(2) == 168) ||
\r
287 GetByte(3) == 127 ||
\r
290 ip == INADDR_NONE);
\r
293 bool IsValid() const
\r
295 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
\r
298 unsigned char GetByte(int n) const
\r
300 return ((unsigned char*)&ip)[3-n];
\r
303 string ToStringIPPort() const
\r
305 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
\r
308 string ToStringIP() const
\r
310 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
\r
313 string ToStringPort() const
\r
315 return strprintf("%u", ntohs(port));
\r
318 string ToStringLog() const
\r
323 string ToString() const
\r
325 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
\r
330 printf("CAddress(%s)\n", ToString().c_str());
\r
346 static const char* ppszTypeName[] =
\r
365 CInv(int typeIn, const uint256& hashIn)
\r
371 CInv(const string& strType, const uint256& hashIn)
\r
374 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
\r
376 if (strType == ppszTypeName[i])
\r
382 if (i == ARRAYLEN(ppszTypeName))
\r
383 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
\r
387 IMPLEMENT_SERIALIZE
\r
393 friend inline bool operator<(const CInv& a, const CInv& b)
\r
395 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
\r
398 bool IsKnownType() const
\r
400 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
\r
403 const char* GetCommand() const
\r
405 if (!IsKnownType())
\r
406 throw std::out_of_range(strprintf("CInv::GetCommand() : type=% unknown type", type));
\r
407 return ppszTypeName[type];
\r
410 string ToString() const
\r
412 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,16).c_str());
\r
417 printf("CInv(%s)\n", ToString().c_str());
\r
425 class CRequestTracker
\r
428 void (*fn)(void*, CDataStream&);
\r
431 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
\r
447 extern bool fClient;
\r
448 extern uint64 nLocalServices;
\r
449 extern CAddress addrLocalHost;
\r
450 extern CNode* pnodeLocalHost;
\r
451 extern uint64 nLocalHostNonce;
\r
452 extern array<int, 10> vnThreadsRunning;
\r
453 extern SOCKET hListenSocket;
\r
454 extern int64 nThreadSocketHandlerHeartbeat;
\r
456 extern vector<CNode*> vNodes;
\r
457 extern CCriticalSection cs_vNodes;
\r
458 extern map<vector<unsigned char>, CAddress> mapAddresses;
\r
459 extern CCriticalSection cs_mapAddresses;
\r
460 extern map<CInv, CDataStream> mapRelay;
\r
461 extern deque<pair<int64, CInv> > vRelayExpiration;
\r
462 extern CCriticalSection cs_mapRelay;
\r
463 extern map<CInv, int64> mapAlreadyAskedFor;
\r
466 extern int fUseProxy;
\r
467 extern CAddress addrProxy;
\r
481 CCriticalSection cs_vSend;
\r
482 CCriticalSection cs_vRecv;
\r
485 int64 nLastSendEmpty;
\r
486 int64 nTimeConnected;
\r
487 unsigned int nPushPos;
\r
493 bool fSuccessfullyConnected;
\r
498 int64 nReleaseTime;
\r
499 map<uint256, CRequestTracker> mapRequests;
\r
500 CCriticalSection cs_mapRequests;
\r
501 uint256 hashContinue;
\r
502 CBlockIndex* pindexLastGetBlocksBegin;
\r
503 uint256 hashLastGetBlocksEnd;
\r
506 vector<CAddress> vAddrToSend;
\r
507 set<CAddress> setAddrKnown;
\r
510 // inventory based relay
\r
511 set<CInv> setInventoryKnown;
\r
512 vector<CInv> vInventoryToSend;
\r
513 CCriticalSection cs_inventory;
\r
514 multimap<int64, CInv> mapAskFor;
\r
515 int64 nLastSentTxInv;
\r
517 // publish and subscription
\r
518 vector<char> vfSubscribe;
\r
521 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
\r
524 hSocket = hSocketIn;
\r
525 vSend.SetType(SER_NETWORK);
\r
526 vRecv.SetType(SER_NETWORK);
\r
529 nLastSendEmpty = GetTime();
\r
530 nTimeConnected = GetTime();
\r
534 fClient = false; // set by version message
\r
535 fInbound = fInboundIn;
\r
536 fNetworkNode = false;
\r
537 fSuccessfullyConnected = false;
\r
538 fDisconnect = false;
\r
542 pindexLastGetBlocksBegin = 0;
\r
543 hashLastGetBlocksEnd = 0;
\r
545 vfSubscribe.assign(256, false);
\r
547 // Push a version message
\r
548 /// when NTP implemented, change to just nTime = GetAdjustedTime()
\r
549 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
\r
550 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
\r
551 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
\r
552 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
\r
553 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, string(pszSubVer));
\r
558 if (hSocket != INVALID_SOCKET)
\r
560 closesocket(hSocket);
\r
561 hSocket = INVALID_SOCKET;
\r
566 CNode(const CNode&);
\r
567 void operator=(const CNode&);
\r
573 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
\r
576 CNode* AddRef(int64 nTimeout=0)
\r
579 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);
\r
592 void AddAddressKnown(const CAddress& addr)
\r
594 setAddrKnown.insert(addr);
\r
597 void PushAddress(const CAddress& addr)
\r
599 // Known checking here is only to save space from duplicates.
\r
600 // SendMessages will filter it again for knowns that were added
\r
601 // after addresses were pushed.
\r
602 if (!setAddrKnown.count(addr))
\r
603 vAddrToSend.push_back(addr);
\r
607 void AddInventoryKnown(const CInv& inv)
\r
609 CRITICAL_BLOCK(cs_inventory)
\r
610 setInventoryKnown.insert(inv);
\r
613 void PushInventory(const CInv& inv)
\r
615 CRITICAL_BLOCK(cs_inventory)
\r
616 if (!setInventoryKnown.count(inv))
\r
617 vInventoryToSend.push_back(inv);
\r
620 void AskFor(const CInv& inv)
\r
622 // We're using mapAskFor as a priority queue,
\r
623 // the key is the earliest time the request can be sent
\r
624 int64& nRequestTime = mapAlreadyAskedFor[inv];
\r
625 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
\r
627 // Make sure not to reuse time indexes to keep things in the same order
\r
628 int64 nNow = (GetTime() - 1) * 1000000;
\r
629 static int64 nLastTime;
\r
630 nLastTime = nNow = max(nNow, ++nLastTime);
\r
632 // Each retry is 2 minutes after the last
\r
633 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);
\r
634 mapAskFor.insert(make_pair(nRequestTime, inv));
\r
639 void BeginMessage(const char* pszCommand)
\r
642 if (nPushPos != -1)
\r
644 nPushPos = vSend.size();
\r
645 vSend << CMessageHeader(pszCommand, 0);
\r
647 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
\r
648 printf("sending: %s ", pszCommand);
\r
651 void AbortMessage()
\r
653 if (nPushPos == -1)
\r
655 vSend.resize(nPushPos);
\r
658 printf("(aborted)\n");
\r
663 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
\r
665 printf("dropmessages DROPPING SEND MESSAGE\n");
\r
670 if (nPushPos == -1)
\r
673 // Patch in the size
\r
674 unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
675 memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
\r
677 printf("(%d bytes) ", nSize);
\r
684 void EndMessageAbortIfEmpty()
\r
686 if (nPushPos == -1)
\r
688 int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
695 const char* GetMessageCommand() const
\r
697 if (nPushPos == -1)
\r
699 return &vSend[nPushPos] + offsetof(CMessageHeader, pchCommand);
\r
705 void PushMessage(const char* pszCommand)
\r
709 BeginMessage(pszCommand);
\r
719 template<typename T1>
\r
720 void PushMessage(const char* pszCommand, const T1& a1)
\r
724 BeginMessage(pszCommand);
\r
735 template<typename T1, typename T2>
\r
736 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
\r
740 BeginMessage(pszCommand);
\r
751 template<typename T1, typename T2, typename T3>
\r
752 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
\r
756 BeginMessage(pszCommand);
\r
757 vSend << a1 << a2 << a3;
\r
767 template<typename T1, typename T2, typename T3, typename T4>
\r
768 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
\r
772 BeginMessage(pszCommand);
\r
773 vSend << a1 << a2 << a3 << a4;
\r
783 template<typename T1, typename T2, typename T3, typename T4, typename T5>
\r
784 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
\r
788 BeginMessage(pszCommand);
\r
789 vSend << a1 << a2 << a3 << a4 << a5;
\r
799 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
\r
800 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
\r
804 BeginMessage(pszCommand);
\r
805 vSend << a1 << a2 << a3 << a4 << a5 << a6;
\r
815 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
\r
816 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
820 BeginMessage(pszCommand);
\r
821 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
\r
831 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
\r
832 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
836 BeginMessage(pszCommand);
\r
837 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
\r
847 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
\r
848 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
852 BeginMessage(pszCommand);
\r
853 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
\r
864 void PushRequest(const char* pszCommand,
\r
865 void (*fn)(void*, CDataStream&), void* param1)
\r
868 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
870 CRITICAL_BLOCK(cs_mapRequests)
\r
871 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
873 PushMessage(pszCommand, hashReply);
\r
876 template<typename T1>
\r
877 void PushRequest(const char* pszCommand, const T1& a1,
\r
878 void (*fn)(void*, CDataStream&), void* param1)
\r
881 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
883 CRITICAL_BLOCK(cs_mapRequests)
\r
884 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
886 PushMessage(pszCommand, hashReply, a1);
\r
889 template<typename T1, typename T2>
\r
890 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
\r
891 void (*fn)(void*, CDataStream&), void* param1)
\r
894 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
896 CRITICAL_BLOCK(cs_mapRequests)
\r
897 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
899 PushMessage(pszCommand, hashReply, a1, a2);
\r
904 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
\r
905 bool IsSubscribed(unsigned int nChannel);
\r
906 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
\r
907 void CancelSubscribe(unsigned int nChannel);
\r
908 void CloseSocketDisconnect();
\r
921 inline void RelayInventory(const CInv& inv)
\r
923 // Put on lists to offer to the other nodes
\r
924 CRITICAL_BLOCK(cs_vNodes)
\r
925 foreach(CNode* pnode, vNodes)
\r
926 pnode->PushInventory(inv);
\r
929 template<typename T>
\r
930 void RelayMessage(const CInv& inv, const T& a)
\r
932 CDataStream ss(SER_NETWORK);
\r
935 RelayMessage(inv, ss);
\r
939 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
\r
941 CRITICAL_BLOCK(cs_mapRelay)
\r
943 // Expire old relay messages
\r
944 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
\r
946 mapRelay.erase(vRelayExpiration.front().second);
\r
947 vRelayExpiration.pop_front();
\r
950 // Save original serialized message so newer versions are preserved
\r
951 mapRelay[inv] = ss;
\r
952 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));
\r
955 RelayInventory(inv);
\r
966 // Templates for the publish and subscription system.
\r
967 // The object being published as T& obj needs to have:
\r
968 // a set<unsigned int> setSources member
\r
969 // specializations of AdvertInsert and AdvertErase
\r
970 // Currently implemented for CTable and CProduct.
\r
973 template<typename T>
\r
974 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
977 obj.setSources.insert(pfrom->addr.ip);
\r
979 if (!AdvertInsert(obj))
\r
983 CRITICAL_BLOCK(cs_vNodes)
\r
984 foreach(CNode* pnode, vNodes)
\r
985 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
986 pnode->PushMessage("publish", nChannel, nHops, obj);
\r
989 template<typename T>
\r
990 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
992 uint256 hash = obj.GetHash();
\r
994 CRITICAL_BLOCK(cs_vNodes)
\r
995 foreach(CNode* pnode, vNodes)
\r
996 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
997 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
\r
1002 template<typename T>
\r
1003 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
1005 // Remove a source
\r
1006 obj.setSources.erase(pfrom->addr.ip);
\r
1008 // If no longer supported by any sources, cancel it
\r
1009 if (obj.setSources.empty())
\r
1010 AdvertStopPublish(pfrom, nChannel, nHops, obj);
\r