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
25 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);
\r
26 bool GetMyExternalIP(unsigned int& ipRet);
\r
27 bool AddAddress(CAddrDB& addrdb, 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 void ThreadBitcoinMiner(void* parg);
\r
33 bool StartNode(string& strError=REF(string()));
\r
35 void CheckForShutdown(int n);
\r
47 // (4) message start
\r
51 // The message start string is designed to be unlikely to occur in normal data.
\r
52 // The characters are rarely used upper ascii, not valid as UTF-8, and produce
\r
53 // a large 4-byte int at any alignment.
\r
54 static const char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };
\r
56 class CMessageHeader
\r
59 enum { COMMAND_SIZE=12 };
\r
60 char pchMessageStart[sizeof(::pchMessageStart)];
\r
61 char pchCommand[COMMAND_SIZE];
\r
62 unsigned int nMessageSize;
\r
66 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
\r
67 memset(pchCommand, 0, sizeof(pchCommand));
\r
72 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
\r
74 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
\r
75 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
\r
76 nMessageSize = nMessageSizeIn;
\r
81 READWRITE(FLATDATA(pchMessageStart));
\r
82 READWRITE(FLATDATA(pchCommand));
\r
83 READWRITE(nMessageSize);
\r
88 if (pchCommand[COMMAND_SIZE-1] == 0)
\r
89 return string(pchCommand, pchCommand + strlen(pchCommand));
\r
91 return string(pchCommand, pchCommand + COMMAND_SIZE);
\r
96 // Check start string
\r
97 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
\r
100 // Check the command string for errors
\r
101 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
\r
105 // Must be all zeros after the first zero
\r
106 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
\r
110 else if (*p1 < ' ' || *p1 > 0x7E)
\r
115 if (nMessageSize > 0x10000000)
\r
117 printf("CMessageHeader::IsValid() : nMessageSize too large %u\n", nMessageSize);
\r
130 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
\r
136 unsigned char pchReserved[12];
\r
138 unsigned short port;
\r
141 unsigned int nTime;
\r
144 unsigned int nLastFailed;
\r
149 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
151 port = DEFAULT_PORT;
\r
152 nTime = GetAdjustedTime();
\r
156 CAddress(unsigned int ipIn, unsigned short portIn=DEFAULT_PORT, uint64 nServicesIn=0)
\r
158 nServices = nServicesIn;
\r
159 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
162 nTime = GetAdjustedTime();
\r
166 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=0)
\r
168 nServices = nServicesIn;
\r
169 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
170 ip = sockaddr.sin_addr.s_addr;
\r
171 port = sockaddr.sin_port;
\r
172 nTime = GetAdjustedTime();
\r
176 explicit CAddress(const char* pszIn, uint64 nServicesIn=0)
\r
178 nServices = nServicesIn;
\r
179 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
\r
181 port = DEFAULT_PORT;
\r
182 nTime = GetAdjustedTime();
\r
186 if (strlen(pszIn) > ARRAYLEN(psz)-1)
\r
188 strcpy(psz, pszIn);
\r
189 unsigned int a, b, c, d, e;
\r
190 if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)
\r
192 char* pszPort = strchr(psz, ':');
\r
196 port = htons(atoi(pszPort));
\r
198 ip = inet_addr(psz);
\r
201 IMPLEMENT_SERIALIZE
\r
203 if (nType & SER_DISK)
\r
205 READWRITE(nVersion);
\r
208 READWRITE(nServices);
\r
209 READWRITE(FLATDATA(pchReserved));
\r
214 friend inline bool operator==(const CAddress& a, const CAddress& b)
\r
216 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
\r
221 friend inline bool operator<(const CAddress& a, const CAddress& b)
\r
223 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
\r
228 if (ntohl(a.ip) < ntohl(b.ip))
\r
230 else if (a.ip == b.ip)
\r
231 return ntohs(a.port) < ntohs(b.port);
\r
236 vector<unsigned char> GetKey() const
\r
240 ss << FLATDATA(pchReserved) << ip << port;
\r
242 #if defined(_MSC_VER) && _MSC_VER < 1300
\r
243 return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
\r
245 return vector<unsigned char>(ss.begin(), ss.end());
\r
249 struct sockaddr_in GetSockAddr() const
\r
251 struct sockaddr_in sockaddr;
\r
252 sockaddr.sin_family = AF_INET;
\r
253 sockaddr.sin_addr.s_addr = ip;
\r
254 sockaddr.sin_port = port;
\r
258 bool IsIPv4() const
\r
260 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
\r
263 bool IsRoutable() const
\r
265 return !(GetByte(3) == 10 || (GetByte(3) == 192 && GetByte(2) == 168) || GetByte(3) == 127 || GetByte(3) == 0);
\r
268 unsigned char GetByte(int n) const
\r
270 return ((unsigned char*)&ip)[3-n];
\r
273 string ToStringIPPort() const
\r
275 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
\r
278 string ToStringIP() const
\r
280 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
\r
283 string ToString() const
\r
285 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
\r
286 //return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
\r
291 printf("CAddress(%s)\n", ToString().c_str());
\r
310 static const char* ppszTypeName[] =
\r
332 CInv(int typeIn, const uint256& hashIn)
\r
338 CInv(const string& strType, const uint256& hashIn)
\r
341 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
\r
343 if (strType == ppszTypeName[i])
\r
349 if (i == ARRAYLEN(ppszTypeName))
\r
350 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
\r
354 IMPLEMENT_SERIALIZE
\r
360 friend inline bool operator<(const CInv& a, const CInv& b)
\r
362 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
\r
365 bool IsKnownType() const
\r
367 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
\r
370 const char* GetCommand() const
\r
372 if (!IsKnownType())
\r
373 throw std::out_of_range(strprintf("CInv::GetCommand() : type=% unknown type", type));
\r
374 return ppszTypeName[type];
\r
377 string ToString() const
\r
379 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,14).c_str());
\r
384 printf("CInv(%s)\n", ToString().c_str());
\r
392 class CRequestTracker
\r
395 void (*fn)(void*, CDataStream&);
\r
398 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
\r
414 extern bool fClient;
\r
415 extern uint64 nLocalServices;
\r
416 extern CAddress addrLocalHost;
\r
417 extern CNode* pnodeLocalHost;
\r
418 extern bool fShutdown;
\r
419 extern array<bool, 10> vfThreadRunning;
\r
420 extern vector<CNode*> vNodes;
\r
421 extern CCriticalSection cs_vNodes;
\r
422 extern map<vector<unsigned char>, CAddress> mapAddresses;
\r
423 extern CCriticalSection cs_mapAddresses;
\r
424 extern map<CInv, CDataStream> mapRelay;
\r
425 extern deque<pair<int64, CInv> > vRelayExpiration;
\r
426 extern CCriticalSection cs_mapRelay;
\r
427 extern map<CInv, int64> mapAlreadyAskedFor;
\r
428 extern CAddress addrProxy;
\r
442 CCriticalSection cs_vSend;
\r
443 CCriticalSection cs_vRecv;
\r
444 unsigned int nPushPos;
\r
454 int64 nReleaseTime;
\r
455 map<uint256, CRequestTracker> mapRequests;
\r
456 CCriticalSection cs_mapRequests;
\r
459 vector<CAddress> vAddrToSend;
\r
460 set<CAddress> setAddrKnown;
\r
462 // inventory based relay
\r
463 set<CInv> setInventoryKnown;
\r
464 set<CInv> setInventoryKnown2;
\r
465 vector<CInv> vInventoryToSend;
\r
466 CCriticalSection cs_inventory;
\r
467 multimap<int64, CInv> mapAskFor;
\r
469 // publish and subscription
\r
470 vector<char> vfSubscribe;
\r
473 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
\r
476 hSocket = hSocketIn;
\r
477 vSend.SetType(SER_NETWORK);
\r
478 vRecv.SetType(SER_NETWORK);
\r
482 fClient = false; // set by version message
\r
483 fInbound = fInboundIn;
\r
484 fNetworkNode = false;
\r
485 fDisconnect = false;
\r
488 vfSubscribe.assign(256, false);
\r
490 // Push a version message
\r
491 /// when NTP implemented, change to just nTime = GetAdjustedTime()
\r
492 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
\r
493 PushMessage("version", VERSION, nLocalServices, nTime, addr);
\r
498 if (hSocket != INVALID_SOCKET)
\r
499 closesocket(hSocket);
\r
503 CNode(const CNode&);
\r
504 void operator=(const CNode&);
\r
508 bool ReadyToDisconnect()
\r
510 return fDisconnect || GetRefCount() <= 0;
\r
515 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
\r
518 void AddRef(int64 nTimeout=0)
\r
521 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);
\r
533 void AddInventoryKnown(const CInv& inv)
\r
535 CRITICAL_BLOCK(cs_inventory)
\r
536 setInventoryKnown.insert(inv);
\r
539 void PushInventory(const CInv& inv)
\r
541 CRITICAL_BLOCK(cs_inventory)
\r
542 if (!setInventoryKnown.count(inv))
\r
543 vInventoryToSend.push_back(inv);
\r
546 void AskFor(const CInv& inv)
\r
548 // We're using mapAskFor as a priority queue,
\r
549 // the key is the earliest time the request can be sent
\r
550 int64& nRequestTime = mapAlreadyAskedFor[inv];
\r
551 printf("askfor %s %I64d\n", inv.ToString().c_str(), nRequestTime);
\r
553 // Make sure not to reuse time indexes to keep things in the same order
\r
554 int64 nNow = (GetTime() - 1) * 1000000;
\r
555 static int64 nLastTime;
\r
556 nLastTime = nNow = max(nNow, ++nLastTime);
\r
558 // Each retry is 2 minutes after the last
\r
559 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);
\r
560 mapAskFor.insert(make_pair(nRequestTime, inv));
\r
565 void BeginMessage(const char* pszCommand)
\r
567 EnterCriticalSection(&cs_vSend);
\r
568 if (nPushPos != -1)
\r
570 nPushPos = vSend.size();
\r
571 vSend << CMessageHeader(pszCommand, 0);
\r
572 printf("sending: %-12s ", pszCommand);
\r
575 void AbortMessage()
\r
577 if (nPushPos == -1)
\r
579 vSend.resize(nPushPos);
\r
581 LeaveCriticalSection(&cs_vSend);
\r
582 printf("(aborted)\n");
\r
587 extern int nDropMessagesTest;
\r
588 if (nDropMessagesTest > 0 && GetRand(nDropMessagesTest) == 0)
\r
590 printf("dropmessages DROPPING SEND MESSAGE\n");
\r
595 if (nPushPos == -1)
\r
598 // Patch in the size
\r
599 unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
600 memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
\r
602 printf("(%d bytes) ", nSize);
\r
603 //for (int i = nPushPos+sizeof(CMessageHeader); i < min(vSend.size(), nPushPos+sizeof(CMessageHeader)+20U); i++)
\r
604 // printf("%02x ", vSend[i] & 0xff);
\r
608 LeaveCriticalSection(&cs_vSend);
\r
611 void EndMessageAbortIfEmpty()
\r
613 if (nPushPos == -1)
\r
615 int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);
\r
622 const char* GetMessageCommand() const
\r
624 if (nPushPos == -1)
\r
626 return &vSend[nPushPos] + offsetof(CMessageHeader, pchCommand);
\r
632 void PushMessage(const char* pszCommand)
\r
636 BeginMessage(pszCommand);
\r
646 template<typename T1>
\r
647 void PushMessage(const char* pszCommand, const T1& a1)
\r
651 BeginMessage(pszCommand);
\r
662 template<typename T1, typename T2>
\r
663 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
\r
667 BeginMessage(pszCommand);
\r
678 template<typename T1, typename T2, typename T3>
\r
679 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
\r
683 BeginMessage(pszCommand);
\r
684 vSend << a1 << a2 << a3;
\r
694 template<typename T1, typename T2, typename T3, typename T4>
\r
695 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
\r
699 BeginMessage(pszCommand);
\r
700 vSend << a1 << a2 << a3 << a4;
\r
711 void PushRequest(const char* pszCommand,
\r
712 void (*fn)(void*, CDataStream&), void* param1)
\r
715 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
717 CRITICAL_BLOCK(cs_mapRequests)
\r
718 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
720 PushMessage(pszCommand, hashReply);
\r
723 template<typename T1>
\r
724 void PushRequest(const char* pszCommand, const T1& a1,
\r
725 void (*fn)(void*, CDataStream&), void* param1)
\r
728 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
730 CRITICAL_BLOCK(cs_mapRequests)
\r
731 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
733 PushMessage(pszCommand, hashReply, a1);
\r
736 template<typename T1, typename T2>
\r
737 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
\r
738 void (*fn)(void*, CDataStream&), void* param1)
\r
741 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
\r
743 CRITICAL_BLOCK(cs_mapRequests)
\r
744 mapRequests[hashReply] = CRequestTracker(fn, param1);
\r
746 PushMessage(pszCommand, hashReply, a1, a2);
\r
751 bool IsSubscribed(unsigned int nChannel);
\r
752 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
\r
753 void CancelSubscribe(unsigned int nChannel);
\r
766 inline void RelayInventory(const CInv& inv)
\r
768 // Put on lists to offer to the other nodes
\r
769 CRITICAL_BLOCK(cs_vNodes)
\r
770 foreach(CNode* pnode, vNodes)
\r
771 pnode->PushInventory(inv);
\r
774 template<typename T>
\r
775 void RelayMessage(const CInv& inv, const T& a)
\r
777 CDataStream ss(SER_NETWORK);
\r
780 RelayMessage(inv, ss);
\r
784 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
\r
786 CRITICAL_BLOCK(cs_mapRelay)
\r
788 // Expire old relay messages
\r
789 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
\r
791 mapRelay.erase(vRelayExpiration.front().second);
\r
792 vRelayExpiration.pop_front();
\r
795 // Save original serialized message so newer versions are preserved
\r
796 mapRelay[inv] = ss;
\r
797 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));
\r
800 RelayInventory(inv);
\r
811 // Templates for the publish and subscription system.
\r
812 // The object being published as T& obj needs to have:
\r
813 // a set<unsigned int> setSources member
\r
814 // specializations of AdvertInsert and AdvertErase
\r
815 // Currently implemented for CTable and CProduct.
\r
818 template<typename T>
\r
819 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
822 obj.setSources.insert(pfrom->addr.ip);
\r
824 if (!AdvertInsert(obj))
\r
828 CRITICAL_BLOCK(cs_vNodes)
\r
829 foreach(CNode* pnode, vNodes)
\r
830 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
831 pnode->PushMessage("publish", nChannel, nHops, obj);
\r
834 template<typename T>
\r
835 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
837 uint256 hash = obj.GetHash();
\r
839 CRITICAL_BLOCK(cs_vNodes)
\r
840 foreach(CNode* pnode, vNodes)
\r
841 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
\r
842 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
\r
847 template<typename T>
\r
848 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
\r
851 obj.setSources.erase(pfrom->addr.ip);
\r
853 // If no longer supported by any sources, cancel it
\r
854 if (obj.setSources.empty())
\r
855 AdvertStopPublish(pfrom, nChannel, nHops, obj);
\r