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 ? htons(18333) : htons(8333); }
16 static const unsigned int PUBLISH_HOPS = 5;
19 NODE_NETWORK = (1 << 0),
25 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);
26 bool GetMyExternalIP(unsigned int& ipRet);
27 bool AddAddress(CAddress addr, int64 nTimePenalty=0);
28 void AddressCurrentlyConnected(const CAddress& addr);
29 CNode* FindNode(unsigned int ip);
30 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
31 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
32 bool AnySubscribed(unsigned int nChannel);
33 void DNSAddressSeed();
34 bool BindListenPort(string& strError=REF(string()));
35 void StartNode(void* parg);
52 extern char pchMessageStart[4];
57 enum { COMMAND_SIZE=12 };
58 char pchMessageStart[sizeof(::pchMessageStart)];
59 char pchCommand[COMMAND_SIZE];
60 unsigned int nMessageSize;
61 unsigned int nChecksum;
65 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
66 memset(pchCommand, 0, sizeof(pchCommand));
72 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
74 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
75 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
76 nMessageSize = nMessageSizeIn;
82 READWRITE(FLATDATA(pchMessageStart));
83 READWRITE(FLATDATA(pchCommand));
84 READWRITE(nMessageSize);
91 if (pchCommand[COMMAND_SIZE-1] == 0)
92 return string(pchCommand, pchCommand + strlen(pchCommand));
94 return string(pchCommand, pchCommand + COMMAND_SIZE);
100 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
103 // Check the command string for errors
104 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
108 // Must be all zeros after the first zero
109 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
113 else if (*p1 < ' ' || *p1 > 0x7E)
118 if (nMessageSize > MAX_SIZE)
120 printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
133 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
139 unsigned char pchReserved[12];
143 // disk and network only
147 unsigned int nLastTry;
154 CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)
158 port = (portIn == 0 ? GetDefaultPort() : portIn);
159 nServices = nServicesIn;
162 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
165 ip = sockaddr.sin_addr.s_addr;
166 port = sockaddr.sin_port;
167 nServices = nServicesIn;
170 explicit CAddress(const char* pszIn, uint64 nServicesIn=NODE_NETWORK)
174 nServices = nServicesIn;
177 explicit CAddress(string strIn, uint64 nServicesIn=NODE_NETWORK)
180 SetAddress(strIn.c_str());
181 nServices = nServicesIn;
186 nServices = NODE_NETWORK;
187 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
189 port = GetDefaultPort();
194 bool SetAddress(const char* pszIn)
197 port = GetDefaultPort();
199 strlcpy(psz, pszIn, sizeof(psz));
200 unsigned int a=0, b=0, c=0, d=0, e=0;
201 if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)
203 char* pszPort = strchr(psz, ':');
207 port = htons(atoi(pszPort));
208 if (atoi(pszPort) < 0 || atoi(pszPort) > USHRT_MAX)
209 port = htons(USHRT_MAX);
215 bool SetAddress(string strIn)
217 return SetAddress(strIn.c_str());
223 const_cast<CAddress*>(this)->Init();
224 if (nType & SER_DISK)
226 if ((nType & SER_DISK) || (nVersion >= 31402 && !(nType & SER_GETHASH)))
228 READWRITE(nServices);
229 READWRITE(FLATDATA(pchReserved)); // for IPv6
234 friend inline bool operator==(const CAddress& a, const CAddress& b)
236 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
241 friend inline bool operator!=(const CAddress& a, const CAddress& b)
246 friend inline bool operator<(const CAddress& a, const CAddress& b)
248 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
253 if (ntohl(a.ip) < ntohl(b.ip))
255 else if (a.ip == b.ip)
256 return ntohs(a.port) < ntohs(b.port);
261 vector<unsigned char> GetKey() const
265 ss << FLATDATA(pchReserved) << ip << port;
267 #if defined(_MSC_VER) && _MSC_VER < 1300
268 return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
270 return vector<unsigned char>(ss.begin(), ss.end());
274 struct sockaddr_in GetSockAddr() const
276 struct sockaddr_in sockaddr;
277 memset(&sockaddr, 0, sizeof(sockaddr));
278 sockaddr.sin_family = AF_INET;
279 sockaddr.sin_addr.s_addr = ip;
280 sockaddr.sin_port = port;
286 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
289 bool IsRoutable() const
292 !(GetByte(3) == 10 ||
293 (GetByte(3) == 192 && GetByte(2) == 168) ||
300 // Clean up 3-byte shifted addresses caused by garbage in size field
301 // of addr messages from versions before 0.2.9 checksum.
302 // Two consecutive addr messages look like this:
303 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
304 // so if the first length field is garbled, it reads the second batch
305 // of addr misaligned by 3 bytes.
306 if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
309 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
312 unsigned char GetByte(int n) const
314 return ((unsigned char*)&ip)[3-n];
317 string ToStringIPPort() const
319 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
322 string ToStringIP() const
324 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
327 string ToStringPort() const
329 return strprintf("%u", ntohs(port));
332 string ToStringLog() const
337 string ToString() const
339 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
344 printf("CAddress(%s)\n", ToString().c_str());
360 static const char* ppszTypeName[] =
379 CInv(int typeIn, const uint256& hashIn)
385 CInv(const string& strType, const uint256& hashIn)
388 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
390 if (strType == ppszTypeName[i])
396 if (i == ARRAYLEN(ppszTypeName))
397 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
407 friend inline bool operator<(const CInv& a, const CInv& b)
409 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
412 bool IsKnownType() const
414 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
417 const char* GetCommand() const
420 throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
421 return ppszTypeName[type];
424 string ToString() const
426 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
431 printf("CInv(%s)\n", ToString().c_str());
439 class CRequestTracker
442 void (*fn)(void*, CDataStream&);
445 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
462 extern uint64 nLocalServices;
463 extern CAddress addrLocalHost;
464 extern CNode* pnodeLocalHost;
465 extern uint64 nLocalHostNonce;
466 extern array<int, 10> vnThreadsRunning;
467 extern SOCKET hListenSocket;
469 extern vector<CNode*> vNodes;
470 extern CCriticalSection cs_vNodes;
471 extern map<vector<unsigned char>, CAddress> mapAddresses;
472 extern CCriticalSection cs_mapAddresses;
473 extern map<CInv, CDataStream> mapRelay;
474 extern deque<pair<int64, CInv> > vRelayExpiration;
475 extern CCriticalSection cs_mapRelay;
476 extern map<CInv, int64> mapAlreadyAskedFor;
479 extern int fUseProxy;
480 extern CAddress addrProxy;
495 CCriticalSection cs_vSend;
496 CCriticalSection cs_vRecv;
499 int64 nLastSendEmpty;
500 int64 nTimeConnected;
501 unsigned int nHeaderStart;
502 unsigned int nMessageStart;
509 bool fSuccessfullyConnected;
515 map<uint256, CRequestTracker> mapRequests;
516 CCriticalSection cs_mapRequests;
517 uint256 hashContinue;
518 CBlockIndex* pindexLastGetBlocksBegin;
519 uint256 hashLastGetBlocksEnd;
523 vector<CAddress> vAddrToSend;
524 set<CAddress> setAddrKnown;
526 set<uint256> setKnown;
528 // inventory based relay
529 set<CInv> setInventoryKnown;
530 vector<CInv> vInventoryToSend;
531 CCriticalSection cs_inventory;
532 multimap<int64, CInv> mapAskFor;
534 // publish and subscription
535 vector<char> vfSubscribe;
538 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
542 vSend.SetType(SER_NETWORK);
544 vRecv.SetType(SER_NETWORK);
546 // Version 0.2 obsoletes 20 Feb 2012
547 if (GetTime() > 1329696000)
549 vSend.SetVersion(209);
550 vRecv.SetVersion(209);
554 nLastSendEmpty = GetTime();
555 nTimeConnected = GetTime();
561 fClient = false; // set by version message
562 fInbound = fInboundIn;
563 fNetworkNode = false;
564 fSuccessfullyConnected = false;
569 pindexLastGetBlocksBegin = 0;
570 hashLastGetBlocksEnd = 0;
571 nStartingHeight = -1;
573 vfSubscribe.assign(256, false);
575 // Be shy and don't send version until we hear
582 if (hSocket != INVALID_SOCKET)
584 closesocket(hSocket);
585 hSocket = INVALID_SOCKET;
591 void operator=(const CNode&);
597 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
600 CNode* AddRef(int64 nTimeout=0)
603 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);
616 void AddAddressKnown(const CAddress& addr)
618 setAddrKnown.insert(addr);
621 void PushAddress(const CAddress& addr)
623 // Known checking here is only to save space from duplicates.
624 // SendMessages will filter it again for knowns that were added
625 // after addresses were pushed.
626 if (addr.IsValid() && !setAddrKnown.count(addr))
627 vAddrToSend.push_back(addr);
631 void AddInventoryKnown(const CInv& inv)
633 CRITICAL_BLOCK(cs_inventory)
634 setInventoryKnown.insert(inv);
637 void PushInventory(const CInv& inv)
639 CRITICAL_BLOCK(cs_inventory)
640 if (!setInventoryKnown.count(inv))
641 vInventoryToSend.push_back(inv);
644 void AskFor(const CInv& inv)
646 // We're using mapAskFor as a priority queue,
647 // the key is the earliest time the request can be sent
648 int64& nRequestTime = mapAlreadyAskedFor[inv];
649 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
651 // Make sure not to reuse time indexes to keep things in the same order
652 int64 nNow = (GetTime() - 1) * 1000000;
653 static int64 nLastTime;
654 nLastTime = nNow = max(nNow, ++nLastTime);
656 // Each retry is 2 minutes after the last
657 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);
658 mapAskFor.insert(make_pair(nRequestTime, inv));
663 void BeginMessage(const char* pszCommand)
666 if (nHeaderStart != -1)
668 nHeaderStart = vSend.size();
669 vSend << CMessageHeader(pszCommand, 0);
670 nMessageStart = vSend.size();
672 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
673 printf("sending: %s ", pszCommand);
678 if (nHeaderStart == -1)
680 vSend.resize(nHeaderStart);
684 printf("(aborted)\n");
689 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
691 printf("dropmessages DROPPING SEND MESSAGE\n");
696 if (nHeaderStart == -1)
700 unsigned int nSize = vSend.size() - nMessageStart;
701 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
704 if (vSend.GetVersion() >= 209)
706 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
707 unsigned int nChecksum = 0;
708 memcpy(&nChecksum, &hash, sizeof(nChecksum));
709 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
710 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
713 printf("(%d bytes) ", nSize);
721 void EndMessageAbortIfEmpty()
723 if (nHeaderStart == -1)
725 int nSize = vSend.size() - nMessageStart;
736 /// when NTP implemented, change to just nTime = GetAdjustedTime()
737 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
738 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
739 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
740 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
741 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
742 nLocalHostNonce, string(pszSubVer), nBestHeight);
748 void PushMessage(const char* pszCommand)
752 BeginMessage(pszCommand);
762 template<typename T1>
763 void PushMessage(const char* pszCommand, const T1& a1)
767 BeginMessage(pszCommand);
778 template<typename T1, typename T2>
779 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
783 BeginMessage(pszCommand);
794 template<typename T1, typename T2, typename T3>
795 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
799 BeginMessage(pszCommand);
800 vSend << a1 << a2 << a3;
810 template<typename T1, typename T2, typename T3, typename T4>
811 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
815 BeginMessage(pszCommand);
816 vSend << a1 << a2 << a3 << a4;
826 template<typename T1, typename T2, typename T3, typename T4, typename T5>
827 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
831 BeginMessage(pszCommand);
832 vSend << a1 << a2 << a3 << a4 << a5;
842 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
843 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
847 BeginMessage(pszCommand);
848 vSend << a1 << a2 << a3 << a4 << a5 << a6;
858 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
859 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)
863 BeginMessage(pszCommand);
864 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
874 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
875 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)
879 BeginMessage(pszCommand);
880 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
890 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
891 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)
895 BeginMessage(pszCommand);
896 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
907 void PushRequest(const char* pszCommand,
908 void (*fn)(void*, CDataStream&), void* param1)
911 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
913 CRITICAL_BLOCK(cs_mapRequests)
914 mapRequests[hashReply] = CRequestTracker(fn, param1);
916 PushMessage(pszCommand, hashReply);
919 template<typename T1>
920 void PushRequest(const char* pszCommand, const T1& a1,
921 void (*fn)(void*, CDataStream&), void* param1)
924 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
926 CRITICAL_BLOCK(cs_mapRequests)
927 mapRequests[hashReply] = CRequestTracker(fn, param1);
929 PushMessage(pszCommand, hashReply, a1);
932 template<typename T1, typename T2>
933 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
934 void (*fn)(void*, CDataStream&), void* param1)
937 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
939 CRITICAL_BLOCK(cs_mapRequests)
940 mapRequests[hashReply] = CRequestTracker(fn, param1);
942 PushMessage(pszCommand, hashReply, a1, a2);
947 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
948 bool IsSubscribed(unsigned int nChannel);
949 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
950 void CancelSubscribe(unsigned int nChannel);
951 void CloseSocketDisconnect();
964 inline void RelayInventory(const CInv& inv)
966 // Put on lists to offer to the other nodes
967 CRITICAL_BLOCK(cs_vNodes)
968 foreach(CNode* pnode, vNodes)
969 pnode->PushInventory(inv);
973 void RelayMessage(const CInv& inv, const T& a)
975 CDataStream ss(SER_NETWORK);
978 RelayMessage(inv, ss);
982 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
984 CRITICAL_BLOCK(cs_mapRelay)
986 // Expire old relay messages
987 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
989 mapRelay.erase(vRelayExpiration.front().second);
990 vRelayExpiration.pop_front();
993 // Save original serialized message so newer versions are preserved
995 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));
1009 // Templates for the publish and subscription system.
1010 // The object being published as T& obj needs to have:
1011 // a set<unsigned int> setSources member
1012 // specializations of AdvertInsert and AdvertErase
1013 // Currently implemented for CTable and CProduct.
1016 template<typename T>
1017 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1020 obj.setSources.insert(pfrom->addr.ip);
1022 if (!AdvertInsert(obj))
1026 CRITICAL_BLOCK(cs_vNodes)
1027 foreach(CNode* pnode, vNodes)
1028 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1029 pnode->PushMessage("publish", nChannel, nHops, obj);
1032 template<typename T>
1033 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1035 uint256 hash = obj.GetHash();
1037 CRITICAL_BLOCK(cs_vNodes)
1038 foreach(CNode* pnode, vNodes)
1039 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1040 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
1045 template<typename T>
1046 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1049 obj.setSources.erase(pfrom->addr.ip);
1051 // If no longer supported by any sources, cancel it
1052 if (obj.setSources.empty())
1053 AdvertStopPublish(pfrom, nChannel, nHops, obj);