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 BindListenPort(string& strError=REF(string()));
\r
32 void StartNode(void* parg);
\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 nLastTry;
\r
148 CAddress(unsigned int ipIn, unsigned short portIn=DEFAULT_PORT, uint64 nServicesIn=NODE_NETWORK)
\r
153 nServices = nServicesIn;
\r
156 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
\r
159 ip = sockaddr.sin_addr.s_addr;
\r
160 port = sockaddr.sin_port;
\r
161 nServices = nServicesIn;
\r
164 explicit CAddress(const char* pszIn, uint64 nServicesIn=NODE_NETWORK)
\r
168 nServices = nServicesIn;
\r
171 explicit CAddress(string strIn, uint64 nServicesIn=NODE_NETWORK)
\r
174 SetAddress(strIn.c_str());
\r
175 nServices = nServicesIn;
\r
180 nServices = NODE_NETWORK;
\r
181 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
183 port = DEFAULT_PORT;
\r
184 nTime = GetAdjustedTime();
\r
188 bool SetAddress(const char* pszIn)
\r
191 port = DEFAULT_PORT;
\r
193 strlcpy(psz, pszIn, sizeof(psz));
\r
194 unsigned int a=0, b=0, c=0, d=0, e=0;
\r
195 if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)
\r
197 char* pszPort = strchr(psz, ':');
\r
201 port = htons(atoi(pszPort));
\r
202 if (atoi(pszPort) < 0 || atoi(pszPort) > USHRT_MAX)
\r
203 port = htons(USHRT_MAX);
\r
205 ip = inet_addr(psz);
\r
209 bool SetAddress(string strIn)
\r
211 return SetAddress(strIn.c_str());
\r
214 IMPLEMENT_SERIALIZE
\r
216 if (nType & SER_DISK)
\r
218 READWRITE(nVersion);
\r
221 READWRITE(nServices);
\r
222 READWRITE(FLATDATA(pchReserved)); // for IPv6
\r
227 friend inline bool operator==(const CAddress& a, const CAddress& b)
\r
229 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
\r
234 friend inline bool operator!=(const CAddress& a, const CAddress& b)
\r
236 return (!(a == b));
\r
239 friend inline bool operator<(const CAddress& a, const CAddress& b)
\r
241 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
\r
246 if (ntohl(a.ip) < ntohl(b.ip))
\r
248 else if (a.ip == b.ip)
\r
249 return ntohs(a.port) < ntohs(b.port);
\r
254 vector<unsigned char> GetKey() const
\r
258 ss << FLATDATA(pchReserved) << ip << port;
\r
260 #if defined(_MSC_VER) && _MSC_VER < 1300
\r
261 return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
\r
263 return vector<unsigned char>(ss.begin(), ss.end());
\r
267 struct sockaddr_in GetSockAddr() const
\r
269 struct sockaddr_in sockaddr;
\r
270 memset(&sockaddr, 0, sizeof(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,16).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 array<int, 10> vnThreadsRunning;
\r
458 extern SOCKET hListenSocket;
\r
459 extern int64 nThreadSocketHandlerHeartbeat;
\r
461 extern vector<CNode*> vNodes;
\r
462 extern CCriticalSection cs_vNodes;
\r
463 extern map<vector<unsigned char>, CAddress> mapAddresses;
\r
464 extern CCriticalSection cs_mapAddresses;
\r
465 extern map<CInv, CDataStream> mapRelay;
\r
466 extern deque<pair<int64, CInv> > vRelayExpiration;
\r
467 extern CCriticalSection cs_mapRelay;
\r
468 extern map<CInv, int64> mapAlreadyAskedFor;
\r
471 extern int fUseProxy;
\r
472 extern CAddress addrProxy;
\r
486 CCriticalSection cs_vSend;
\r
487 CCriticalSection cs_vRecv;
\r
490 int64 nLastSendEmpty;
\r
491 int64 nTimeConnected;
\r
492 unsigned int nPushPos;
\r
498 bool fSuccessfullyConnected;
\r
503 int64 nReleaseTime;
\r
504 map<uint256, CRequestTracker> mapRequests;
\r
505 CCriticalSection cs_mapRequests;
\r
506 uint256 hashContinue;
\r
509 vector<CAddress> vAddrToSend;
\r
510 set<CAddress> setAddrKnown;
\r
513 // inventory based relay
\r
514 set<CInv> setInventoryKnown;
\r
515 vector<CInv> vInventoryToSend;
\r
516 CCriticalSection cs_inventory;
\r
517 multimap<int64, CInv> mapAskFor;
\r
519 // publish and subscription
\r
520 vector<char> vfSubscribe;
\r
523 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
\r
526 hSocket = hSocketIn;
\r
527 vSend.SetType(SER_NETWORK);
\r
528 vRecv.SetType(SER_NETWORK);
\r
531 nLastSendEmpty = GetTime();
\r
532 nTimeConnected = GetTime();
\r
536 fClient = false; // set by version message
\r
537 fInbound = fInboundIn;
\r
538 fNetworkNode = false;
\r
539 fSuccessfullyConnected = false;
\r
540 fDisconnect = false;
\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
638 void BeginMessage(const char* pszCommand)
\r
641 if (nPushPos != -1)
\r
643 nPushPos = vSend.size();
\r
644 vSend << CMessageHeader(pszCommand, 0);
\r
646 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
\r
647 printf("sending: %s ", pszCommand);
\r
650 void AbortMessage()
\r
652 if (nPushPos == -1)
\r
654 vSend.resize(nPushPos);
\r
657 printf("(aborted)\n");
\r
662 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
\r
664 printf("dropmessages DROPPING SEND MESSAGE\n");
\r
669 if (nPushPos == -1)
\r
672 // Patch in the size
\r
673 unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
674 memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
\r
676 printf("(%d bytes) ", nSize);
\r
683 void EndMessageAbortIfEmpty()
\r
685 if (nPushPos == -1)
\r
687 int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
694 const char* GetMessageCommand() const
\r
696 if (nPushPos == -1)
\r
698 return &vSend[nPushPos] + offsetof(CMessageHeader, pchCommand);
\r
704 void PushMessage(const char* pszCommand)
\r
708 BeginMessage(pszCommand);
\r
718 template<typename T1>
\r
719 void PushMessage(const char* pszCommand, const T1& a1)
\r
723 BeginMessage(pszCommand);
\r
734 template<typename T1, typename T2>
\r
735 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
\r
739 BeginMessage(pszCommand);
\r
750 template<typename T1, typename T2, typename T3>
\r
751 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
\r
755 BeginMessage(pszCommand);
\r
756 vSend << a1 << a2 << a3;
\r
766 template<typename T1, typename T2, typename T3, typename T4>
\r
767 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
\r
771 BeginMessage(pszCommand);
\r
772 vSend << a1 << a2 << a3 << a4;
\r
782 template<typename T1, typename T2, typename T3, typename T4, typename T5>
\r
783 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
\r
787 BeginMessage(pszCommand);
\r
788 vSend << a1 << a2 << a3 << a4 << a5;
\r
798 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
\r
799 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
\r
803 BeginMessage(pszCommand);
\r
804 vSend << a1 << a2 << a3 << a4 << a5 << a6;
\r
814 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
\r
815 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
819 BeginMessage(pszCommand);
\r
820 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
\r
830 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
\r
831 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
835 BeginMessage(pszCommand);
\r
836 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
\r
846 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
\r
847 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
851 BeginMessage(pszCommand);
\r
852 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
\r
863 void PushRequest(const char* pszCommand,
\r
864 void (*fn)(void*, CDataStream&), void* param1)
\r
867 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
869 CRITICAL_BLOCK(cs_mapRequests)
\r
870 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
872 PushMessage(pszCommand, hashReply);
\r
875 template<typename T1>
\r
876 void PushRequest(const char* pszCommand, const T1& a1,
\r
877 void (*fn)(void*, CDataStream&), void* param1)
\r
880 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
882 CRITICAL_BLOCK(cs_mapRequests)
\r
883 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
885 PushMessage(pszCommand, hashReply, a1);
\r
888 template<typename T1, typename T2>
\r
889 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
\r
890 void (*fn)(void*, CDataStream&), void* param1)
\r
893 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
895 CRITICAL_BLOCK(cs_mapRequests)
\r
896 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
898 PushMessage(pszCommand, hashReply, a1, a2);
\r
903 bool IsSubscribed(unsigned int nChannel);
\r
904 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
\r
905 void CancelSubscribe(unsigned int nChannel);
\r
906 void CloseSocketDisconnect();
\r
919 inline void RelayInventory(const CInv& inv)
\r
921 // Put on lists to offer to the other nodes
\r
922 CRITICAL_BLOCK(cs_vNodes)
\r
923 foreach(CNode* pnode, vNodes)
\r
924 pnode->PushInventory(inv);
\r
927 template<typename T>
\r
928 void RelayMessage(const CInv& inv, const T& a)
\r
930 CDataStream ss(SER_NETWORK);
\r
933 RelayMessage(inv, ss);
\r
937 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
\r
939 CRITICAL_BLOCK(cs_mapRelay)
\r
941 // Expire old relay messages
\r
942 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
\r
944 mapRelay.erase(vRelayExpiration.front().second);
\r
945 vRelayExpiration.pop_front();
\r
948 // Save original serialized message so newer versions are preserved
\r
949 mapRelay[inv] = ss;
\r
950 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));
\r
953 RelayInventory(inv);
\r
964 // Templates for the publish and subscription system.
\r
965 // The object being published as T& obj needs to have:
\r
966 // a set<unsigned int> setSources member
\r
967 // specializations of AdvertInsert and AdvertErase
\r
968 // Currently implemented for CTable and CProduct.
\r
971 template<typename T>
\r
972 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
975 obj.setSources.insert(pfrom->addr.ip);
\r
977 if (!AdvertInsert(obj))
\r
981 CRITICAL_BLOCK(cs_vNodes)
\r
982 foreach(CNode* pnode, vNodes)
\r
983 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
984 pnode->PushMessage("publish", nChannel, nHops, obj);
\r
987 template<typename T>
\r
988 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
990 uint256 hash = obj.GetHash();
\r
992 CRITICAL_BLOCK(cs_vNodes)
\r
993 foreach(CNode* pnode, vNodes)
\r
994 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
995 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
\r
1000 template<typename T>
\r
1001 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
1003 // Remove a source
\r
1004 obj.setSources.erase(pfrom->addr.ip);
\r
1006 // If no longer supported by any sources, cancel it
\r
1007 if (obj.setSources.empty())
\r
1008 AdvertStopPublish(pfrom, nChannel, nHops, obj);
\r