1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
11 extern int nBestHeight;
15 inline unsigned short GetDefaultPort() { return fTestNet ? 18333 : 8333; }
16 static const unsigned int PUBLISH_HOPS = 5;
19 NODE_NETWORK = (1 << 0),
25 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);
26 bool Lookup(const char *pszName, vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
27 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
28 bool GetMyExternalIP(unsigned int& ipRet);
29 bool AddAddress(CAddress addr, int64 nTimePenalty=0);
30 void AddressCurrentlyConnected(const CAddress& addr);
31 CNode* FindNode(unsigned int ip);
32 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
33 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
34 bool AnySubscribed(unsigned int nChannel);
35 void MapPort(bool fMapPort);
36 void DNSAddressSeed();
37 bool BindListenPort(string& strError=REF(string()));
38 void StartNode(void* parg);
55 extern char pchMessageStart[4];
60 enum { COMMAND_SIZE=12 };
61 char pchMessageStart[sizeof(::pchMessageStart)];
62 char pchCommand[COMMAND_SIZE];
63 unsigned int nMessageSize;
64 unsigned int nChecksum;
68 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
69 memset(pchCommand, 0, sizeof(pchCommand));
75 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
77 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
78 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
79 nMessageSize = nMessageSizeIn;
85 READWRITE(FLATDATA(pchMessageStart));
86 READWRITE(FLATDATA(pchCommand));
87 READWRITE(nMessageSize);
94 if (pchCommand[COMMAND_SIZE-1] == 0)
95 return string(pchCommand, pchCommand + strlen(pchCommand));
97 return string(pchCommand, pchCommand + COMMAND_SIZE);
102 // Check start string
103 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
106 // Check the command string for errors
107 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
111 // Must be all zeros after the first zero
112 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
116 else if (*p1 < ' ' || *p1 > 0x7E)
121 if (nMessageSize > MAX_SIZE)
123 printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
136 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
142 unsigned char pchReserved[12];
146 // disk and network only
150 unsigned int nLastTry;
157 CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)
161 port = htons(portIn == 0 ? GetDefaultPort() : portIn);
162 nServices = nServicesIn;
165 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
168 ip = sockaddr.sin_addr.s_addr;
169 port = sockaddr.sin_port;
170 nServices = nServicesIn;
173 explicit CAddress(const char* pszIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
176 Lookup(pszIn, *this, nServicesIn, fNameLookup, portIn);
179 explicit CAddress(const char* pszIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
182 Lookup(pszIn, *this, nServicesIn, fNameLookup, 0, true);
185 explicit CAddress(string strIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
188 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, portIn);
191 explicit CAddress(string strIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
194 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, 0, true);
199 nServices = NODE_NETWORK;
200 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
202 port = htons(GetDefaultPort());
210 const_cast<CAddress*>(this)->Init();
211 if (nType & SER_DISK)
213 if ((nType & SER_DISK) || (nVersion >= 31402 && !(nType & SER_GETHASH)))
215 READWRITE(nServices);
216 READWRITE(FLATDATA(pchReserved)); // for IPv6
221 friend inline bool operator==(const CAddress& a, const CAddress& b)
223 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
228 friend inline bool operator!=(const CAddress& a, const CAddress& b)
233 friend inline bool operator<(const CAddress& a, const CAddress& b)
235 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
240 if (ntohl(a.ip) < ntohl(b.ip))
242 else if (a.ip == b.ip)
243 return ntohs(a.port) < ntohs(b.port);
248 vector<unsigned char> GetKey() const
252 ss << FLATDATA(pchReserved) << ip << port;
254 #if defined(_MSC_VER) && _MSC_VER < 1300
255 return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
257 return vector<unsigned char>(ss.begin(), ss.end());
261 struct sockaddr_in GetSockAddr() const
263 struct sockaddr_in sockaddr;
264 memset(&sockaddr, 0, sizeof(sockaddr));
265 sockaddr.sin_family = AF_INET;
266 sockaddr.sin_addr.s_addr = ip;
267 sockaddr.sin_port = port;
273 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
276 bool IsRoutable() const
279 !(GetByte(3) == 10 ||
280 (GetByte(3) == 192 && GetByte(2) == 168) ||
287 // Clean up 3-byte shifted addresses caused by garbage in size field
288 // of addr messages from versions before 0.2.9 checksum.
289 // Two consecutive addr messages look like this:
290 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
291 // so if the first length field is garbled, it reads the second batch
292 // of addr misaligned by 3 bytes.
293 if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
296 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
299 unsigned char GetByte(int n) const
301 return ((unsigned char*)&ip)[3-n];
304 string ToStringIPPort() const
306 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
309 string ToStringIP() const
311 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
314 string ToStringPort() const
316 return strprintf("%u", ntohs(port));
319 string ToString() const
321 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
326 printf("CAddress(%s)\n", ToString().c_str());
342 static const char* ppszTypeName[] =
361 CInv(int typeIn, const uint256& hashIn)
367 CInv(const string& strType, const uint256& hashIn)
370 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
372 if (strType == ppszTypeName[i])
378 if (i == ARRAYLEN(ppszTypeName))
379 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
389 friend inline bool operator<(const CInv& a, const CInv& b)
391 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
394 bool IsKnownType() const
396 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
399 const char* GetCommand() const
402 throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
403 return ppszTypeName[type];
406 string ToString() const
408 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
413 printf("CInv(%s)\n", ToString().c_str());
421 class CRequestTracker
424 void (*fn)(void*, CDataStream&);
427 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
444 extern bool fAllowDNS;
445 extern uint64 nLocalServices;
446 extern CAddress addrLocalHost;
447 extern CNode* pnodeLocalHost;
448 extern uint64 nLocalHostNonce;
449 extern array<int, 10> vnThreadsRunning;
450 extern SOCKET hListenSocket;
452 extern vector<CNode*> vNodes;
453 extern CCriticalSection cs_vNodes;
454 extern map<vector<unsigned char>, CAddress> mapAddresses;
455 extern CCriticalSection cs_mapAddresses;
456 extern map<CInv, CDataStream> mapRelay;
457 extern deque<pair<int64, CInv> > vRelayExpiration;
458 extern CCriticalSection cs_mapRelay;
459 extern map<CInv, int64> mapAlreadyAskedFor;
462 extern int fUseProxy;
463 extern CAddress addrProxy;
478 CCriticalSection cs_vSend;
479 CCriticalSection cs_vRecv;
482 int64 nLastSendEmpty;
483 int64 nTimeConnected;
484 unsigned int nHeaderStart;
485 unsigned int nMessageStart;
492 bool fSuccessfullyConnected;
498 map<uint256, CRequestTracker> mapRequests;
499 CCriticalSection cs_mapRequests;
500 uint256 hashContinue;
501 CBlockIndex* pindexLastGetBlocksBegin;
502 uint256 hashLastGetBlocksEnd;
506 vector<CAddress> vAddrToSend;
507 set<CAddress> setAddrKnown;
509 set<uint256> setKnown;
511 // inventory based relay
512 set<CInv> setInventoryKnown;
513 vector<CInv> vInventoryToSend;
514 CCriticalSection cs_inventory;
515 multimap<int64, CInv> mapAskFor;
517 // publish and subscription
518 vector<char> vfSubscribe;
521 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
525 vSend.SetType(SER_NETWORK);
527 vRecv.SetType(SER_NETWORK);
529 // Version 0.2 obsoletes 20 Feb 2012
530 if (GetTime() > 1329696000)
532 vSend.SetVersion(209);
533 vRecv.SetVersion(209);
537 nLastSendEmpty = GetTime();
538 nTimeConnected = GetTime();
544 fClient = false; // set by version message
545 fInbound = fInboundIn;
546 fNetworkNode = false;
547 fSuccessfullyConnected = false;
552 pindexLastGetBlocksBegin = 0;
553 hashLastGetBlocksEnd = 0;
554 nStartingHeight = -1;
556 vfSubscribe.assign(256, false);
558 // Be shy and don't send version until we hear
565 if (hSocket != INVALID_SOCKET)
567 closesocket(hSocket);
568 hSocket = INVALID_SOCKET;
574 void operator=(const CNode&);
580 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
583 CNode* AddRef(int64 nTimeout=0)
586 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);
599 void AddAddressKnown(const CAddress& addr)
601 setAddrKnown.insert(addr);
604 void PushAddress(const CAddress& addr)
606 // Known checking here is only to save space from duplicates.
607 // SendMessages will filter it again for knowns that were added
608 // after addresses were pushed.
609 if (addr.IsValid() && !setAddrKnown.count(addr))
610 vAddrToSend.push_back(addr);
614 void AddInventoryKnown(const CInv& inv)
616 CRITICAL_BLOCK(cs_inventory)
617 setInventoryKnown.insert(inv);
620 void PushInventory(const CInv& inv)
622 CRITICAL_BLOCK(cs_inventory)
623 if (!setInventoryKnown.count(inv))
624 vInventoryToSend.push_back(inv);
627 void AskFor(const CInv& inv)
629 // We're using mapAskFor as a priority queue,
630 // the key is the earliest time the request can be sent
631 int64& nRequestTime = mapAlreadyAskedFor[inv];
632 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
634 // Make sure not to reuse time indexes to keep things in the same order
635 int64 nNow = (GetTime() - 1) * 1000000;
636 static int64 nLastTime;
637 nLastTime = nNow = max(nNow, ++nLastTime);
639 // Each retry is 2 minutes after the last
640 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);
641 mapAskFor.insert(make_pair(nRequestTime, inv));
646 void BeginMessage(const char* pszCommand)
649 if (nHeaderStart != -1)
651 nHeaderStart = vSend.size();
652 vSend << CMessageHeader(pszCommand, 0);
653 nMessageStart = vSend.size();
655 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
656 printf("sending: %s ", pszCommand);
661 if (nHeaderStart == -1)
663 vSend.resize(nHeaderStart);
667 printf("(aborted)\n");
672 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
674 printf("dropmessages DROPPING SEND MESSAGE\n");
679 if (nHeaderStart == -1)
683 unsigned int nSize = vSend.size() - nMessageStart;
684 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
687 if (vSend.GetVersion() >= 209)
689 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
690 unsigned int nChecksum = 0;
691 memcpy(&nChecksum, &hash, sizeof(nChecksum));
692 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
693 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
696 printf("(%d bytes) ", nSize);
704 void EndMessageAbortIfEmpty()
706 if (nHeaderStart == -1)
708 int nSize = vSend.size() - nMessageStart;
719 /// when NTP implemented, change to just nTime = GetAdjustedTime()
720 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
721 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
722 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
723 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
724 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
725 nLocalHostNonce, string(pszSubVer), nBestHeight);
731 void PushMessage(const char* pszCommand)
735 BeginMessage(pszCommand);
745 template<typename T1>
746 void PushMessage(const char* pszCommand, const T1& a1)
750 BeginMessage(pszCommand);
761 template<typename T1, typename T2>
762 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
766 BeginMessage(pszCommand);
777 template<typename T1, typename T2, typename T3>
778 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
782 BeginMessage(pszCommand);
783 vSend << a1 << a2 << a3;
793 template<typename T1, typename T2, typename T3, typename T4>
794 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
798 BeginMessage(pszCommand);
799 vSend << a1 << a2 << a3 << a4;
809 template<typename T1, typename T2, typename T3, typename T4, typename T5>
810 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
814 BeginMessage(pszCommand);
815 vSend << a1 << a2 << a3 << a4 << a5;
825 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
826 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
830 BeginMessage(pszCommand);
831 vSend << a1 << a2 << a3 << a4 << a5 << a6;
841 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
842 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)
846 BeginMessage(pszCommand);
847 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
857 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
858 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)
862 BeginMessage(pszCommand);
863 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
873 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
874 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)
878 BeginMessage(pszCommand);
879 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
890 void PushRequest(const char* pszCommand,
891 void (*fn)(void*, CDataStream&), void* param1)
894 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
896 CRITICAL_BLOCK(cs_mapRequests)
897 mapRequests[hashReply] = CRequestTracker(fn, param1);
899 PushMessage(pszCommand, hashReply);
902 template<typename T1>
903 void PushRequest(const char* pszCommand, const T1& a1,
904 void (*fn)(void*, CDataStream&), void* param1)
907 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
909 CRITICAL_BLOCK(cs_mapRequests)
910 mapRequests[hashReply] = CRequestTracker(fn, param1);
912 PushMessage(pszCommand, hashReply, a1);
915 template<typename T1, typename T2>
916 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
917 void (*fn)(void*, CDataStream&), void* param1)
920 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
922 CRITICAL_BLOCK(cs_mapRequests)
923 mapRequests[hashReply] = CRequestTracker(fn, param1);
925 PushMessage(pszCommand, hashReply, a1, a2);
930 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
931 bool IsSubscribed(unsigned int nChannel);
932 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
933 void CancelSubscribe(unsigned int nChannel);
934 void CloseSocketDisconnect();
947 inline void RelayInventory(const CInv& inv)
949 // Put on lists to offer to the other nodes
950 CRITICAL_BLOCK(cs_vNodes)
951 foreach(CNode* pnode, vNodes)
952 pnode->PushInventory(inv);
956 void RelayMessage(const CInv& inv, const T& a)
958 CDataStream ss(SER_NETWORK);
961 RelayMessage(inv, ss);
965 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
967 CRITICAL_BLOCK(cs_mapRelay)
969 // Expire old relay messages
970 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
972 mapRelay.erase(vRelayExpiration.front().second);
973 vRelayExpiration.pop_front();
976 // Save original serialized message so newer versions are preserved
978 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));
992 // Templates for the publish and subscription system.
993 // The object being published as T& obj needs to have:
994 // a set<unsigned int> setSources member
995 // specializations of AdvertInsert and AdvertErase
996 // Currently implemented for CTable and CProduct.
1000 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1003 obj.setSources.insert(pfrom->addr.ip);
1005 if (!AdvertInsert(obj))
1009 CRITICAL_BLOCK(cs_vNodes)
1010 foreach(CNode* pnode, vNodes)
1011 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1012 pnode->PushMessage("publish", nChannel, nHops, obj);
1015 template<typename T>
1016 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1018 uint256 hash = obj.GetHash();
1020 CRITICAL_BLOCK(cs_vNodes)
1021 foreach(CNode* pnode, vNodes)
1022 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1023 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
1028 template<typename T>
1029 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1032 obj.setSources.erase(pfrom->addr.ip);
1034 // If no longer supported by any sources, cancel it
1035 if (obj.setSources.empty())
1036 AdvertStopPublish(pfrom, nChannel, nHops, obj);