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.
8 #include <boost/array.hpp>
9 #include <openssl/rand.h>
12 #include <arpa/inet.h>
18 class CRequestTracker;
21 extern int nBestHeight;
22 extern int nConnectTimeout;
26 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
27 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
28 inline unsigned short GetDefaultPort() { return fTestNet ? 18333 : 8333; }
29 static const unsigned int PUBLISH_HOPS = 5;
32 NODE_NETWORK = (1 << 0),
38 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
39 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
40 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
41 bool GetMyExternalIP(unsigned int& ipRet);
42 bool AddAddress(CAddress addr, int64 nTimePenalty=0);
43 void AddressCurrentlyConnected(const CAddress& addr);
44 CNode* FindNode(unsigned int ip);
45 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
46 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
47 bool AnySubscribed(unsigned int nChannel);
48 void MapPort(bool fMapPort);
49 void DNSAddressSeed();
50 bool BindListenPort(std::string& strError=REF(std::string()));
51 void StartNode(void* parg);
68 extern char pchMessageStart[4];
73 enum { COMMAND_SIZE=12 };
74 char pchMessageStart[sizeof(::pchMessageStart)];
75 char pchCommand[COMMAND_SIZE];
76 unsigned int nMessageSize;
77 unsigned int nChecksum;
81 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
82 memset(pchCommand, 0, sizeof(pchCommand));
88 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
90 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
91 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
92 nMessageSize = nMessageSizeIn;
98 READWRITE(FLATDATA(pchMessageStart));
99 READWRITE(FLATDATA(pchCommand));
100 READWRITE(nMessageSize);
102 READWRITE(nChecksum);
105 std::string GetCommand()
107 if (pchCommand[COMMAND_SIZE-1] == 0)
108 return std::string(pchCommand, pchCommand + strlen(pchCommand));
110 return std::string(pchCommand, pchCommand + COMMAND_SIZE);
115 // Check start string
116 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
119 // Check the command string for errors
120 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
124 // Must be all zeros after the first zero
125 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
129 else if (*p1 < ' ' || *p1 > 0x7E)
134 if (nMessageSize > MAX_SIZE)
136 printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
149 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
155 unsigned char pchReserved[12];
159 // disk and network only
163 unsigned int nLastTry;
170 CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)
174 port = htons(portIn == 0 ? GetDefaultPort() : portIn);
175 nServices = nServicesIn;
178 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
181 ip = sockaddr.sin_addr.s_addr;
182 port = sockaddr.sin_port;
183 nServices = nServicesIn;
186 explicit CAddress(const char* pszIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
189 Lookup(pszIn, *this, nServicesIn, fNameLookup, portIn);
192 explicit CAddress(const char* pszIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
195 Lookup(pszIn, *this, nServicesIn, fNameLookup, 0, true);
198 explicit CAddress(std::string strIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
201 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, portIn);
204 explicit CAddress(std::string strIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
207 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, 0, true);
212 nServices = NODE_NETWORK;
213 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
215 port = htons(GetDefaultPort());
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 std::vector<unsigned char> GetKey() const
265 ss << FLATDATA(pchReserved) << ip << port;
267 #if defined(_MSC_VER) && _MSC_VER < 1300
268 return std::vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
270 return std::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 IsRFC1918() const
291 return IsIPv4() && (GetByte(3) == 10 ||
292 (GetByte(3) == 192 && GetByte(2) == 168) ||
293 (GetByte(3) == 172 &&
294 (GetByte(2) >= 16 && GetByte(2) <= 31)));
297 bool IsRFC3927() const
299 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
304 return IsIPv4() && (GetByte(3) == 127 ||
308 bool IsRoutable() const
311 !(IsRFC1918() || IsRFC3927() || IsLocal());
316 // Clean up 3-byte shifted addresses caused by garbage in size field
317 // of addr messages from versions before 0.2.9 checksum.
318 // Two consecutive addr messages look like this:
319 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
320 // so if the first length field is garbled, it reads the second batch
321 // of addr misaligned by 3 bytes.
322 if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
325 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
328 unsigned char GetByte(int n) const
330 return ((unsigned char*)&ip)[3-n];
333 std::string ToStringIPPort() const
335 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
338 std::string ToStringIP() const
340 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
343 std::string ToStringPort() const
345 return strprintf("%u", ntohs(port));
348 std::string ToString() const
350 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
355 printf("CAddress(%s)\n", ToString().c_str());
371 static const char* ppszTypeName[] =
390 CInv(int typeIn, const uint256& hashIn)
396 CInv(const std::string& strType, const uint256& hashIn)
399 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
401 if (strType == ppszTypeName[i])
407 if (i == ARRAYLEN(ppszTypeName))
408 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
418 friend inline bool operator<(const CInv& a, const CInv& b)
420 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
423 bool IsKnownType() const
425 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
428 const char* GetCommand() const
431 throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
432 return ppszTypeName[type];
435 std::string ToString() const
437 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
442 printf("CInv(%s)\n", ToString().c_str());
450 class CRequestTracker
453 void (*fn)(void*, CDataStream&);
456 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
473 extern bool fAllowDNS;
474 extern uint64 nLocalServices;
475 extern CAddress addrLocalHost;
476 extern CNode* pnodeLocalHost;
477 extern uint64 nLocalHostNonce;
478 extern boost::array<int, 10> vnThreadsRunning;
479 extern SOCKET hListenSocket;
481 extern std::vector<CNode*> vNodes;
482 extern CCriticalSection cs_vNodes;
483 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
484 extern CCriticalSection cs_mapAddresses;
485 extern std::map<CInv, CDataStream> mapRelay;
486 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
487 extern CCriticalSection cs_mapRelay;
488 extern std::map<CInv, int64> mapAlreadyAskedFor;
491 extern int fUseProxy;
492 extern CAddress addrProxy;
507 CCriticalSection cs_vSend;
508 CCriticalSection cs_vRecv;
511 int64 nLastSendEmpty;
512 int64 nTimeConnected;
513 unsigned int nHeaderStart;
514 unsigned int nMessageStart;
517 std::string strSubVer;
521 bool fSuccessfullyConnected;
527 std::map<uint256, CRequestTracker> mapRequests;
528 CCriticalSection cs_mapRequests;
529 uint256 hashContinue;
530 CBlockIndex* pindexLastGetBlocksBegin;
531 uint256 hashLastGetBlocksEnd;
535 std::vector<CAddress> vAddrToSend;
536 std::set<CAddress> setAddrKnown;
538 std::set<uint256> setKnown;
540 // inventory based relay
541 std::set<CInv> setInventoryKnown;
542 std::vector<CInv> vInventoryToSend;
543 CCriticalSection cs_inventory;
544 std::multimap<int64, CInv> mapAskFor;
546 // publish and subscription
547 std::vector<char> vfSubscribe;
550 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
554 vSend.SetType(SER_NETWORK);
556 vRecv.SetType(SER_NETWORK);
558 // Version 0.2 obsoletes 20 Feb 2012
559 if (GetTime() > 1329696000)
561 vSend.SetVersion(209);
562 vRecv.SetVersion(209);
566 nLastSendEmpty = GetTime();
567 nTimeConnected = GetTime();
573 fClient = false; // set by version message
574 fInbound = fInboundIn;
575 fNetworkNode = false;
576 fSuccessfullyConnected = false;
581 pindexLastGetBlocksBegin = 0;
582 hashLastGetBlocksEnd = 0;
583 nStartingHeight = -1;
585 vfSubscribe.assign(256, false);
587 // Be shy and don't send version until we hear
594 if (hSocket != INVALID_SOCKET)
596 closesocket(hSocket);
597 hSocket = INVALID_SOCKET;
603 void operator=(const CNode&);
609 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
612 CNode* AddRef(int64 nTimeout=0)
615 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
628 void AddAddressKnown(const CAddress& addr)
630 setAddrKnown.insert(addr);
633 void PushAddress(const CAddress& addr)
635 // Known checking here is only to save space from duplicates.
636 // SendMessages will filter it again for knowns that were added
637 // after addresses were pushed.
638 if (addr.IsValid() && !setAddrKnown.count(addr))
639 vAddrToSend.push_back(addr);
643 void AddInventoryKnown(const CInv& inv)
645 CRITICAL_BLOCK(cs_inventory)
646 setInventoryKnown.insert(inv);
649 void PushInventory(const CInv& inv)
651 CRITICAL_BLOCK(cs_inventory)
652 if (!setInventoryKnown.count(inv))
653 vInventoryToSend.push_back(inv);
656 void AskFor(const CInv& inv)
658 // We're using mapAskFor as a priority queue,
659 // the key is the earliest time the request can be sent
660 int64& nRequestTime = mapAlreadyAskedFor[inv];
661 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
663 // Make sure not to reuse time indexes to keep things in the same order
664 int64 nNow = (GetTime() - 1) * 1000000;
665 static int64 nLastTime;
666 nLastTime = nNow = std::max(nNow, ++nLastTime);
668 // Each retry is 2 minutes after the last
669 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
670 mapAskFor.insert(std::make_pair(nRequestTime, inv));
675 void BeginMessage(const char* pszCommand)
678 if (nHeaderStart != -1)
680 nHeaderStart = vSend.size();
681 vSend << CMessageHeader(pszCommand, 0);
682 nMessageStart = vSend.size();
684 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
685 printf("sending: %s ", pszCommand);
690 if (nHeaderStart == -1)
692 vSend.resize(nHeaderStart);
696 printf("(aborted)\n");
701 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
703 printf("dropmessages DROPPING SEND MESSAGE\n");
708 if (nHeaderStart == -1)
712 unsigned int nSize = vSend.size() - nMessageStart;
713 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
716 if (vSend.GetVersion() >= 209)
718 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
719 unsigned int nChecksum = 0;
720 memcpy(&nChecksum, &hash, sizeof(nChecksum));
721 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
722 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
725 printf("(%d bytes) ", nSize);
733 void EndMessageAbortIfEmpty()
735 if (nHeaderStart == -1)
737 int nSize = vSend.size() - nMessageStart;
748 /// when NTP implemented, change to just nTime = GetAdjustedTime()
749 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
750 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
751 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
752 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
753 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
754 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
760 void PushMessage(const char* pszCommand)
764 BeginMessage(pszCommand);
774 template<typename T1>
775 void PushMessage(const char* pszCommand, const T1& a1)
779 BeginMessage(pszCommand);
790 template<typename T1, typename T2>
791 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
795 BeginMessage(pszCommand);
806 template<typename T1, typename T2, typename T3>
807 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
811 BeginMessage(pszCommand);
812 vSend << a1 << a2 << a3;
822 template<typename T1, typename T2, typename T3, typename T4>
823 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
827 BeginMessage(pszCommand);
828 vSend << a1 << a2 << a3 << a4;
838 template<typename T1, typename T2, typename T3, typename T4, typename T5>
839 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
843 BeginMessage(pszCommand);
844 vSend << a1 << a2 << a3 << a4 << a5;
854 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
855 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
859 BeginMessage(pszCommand);
860 vSend << a1 << a2 << a3 << a4 << a5 << a6;
870 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
871 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)
875 BeginMessage(pszCommand);
876 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
886 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
887 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)
891 BeginMessage(pszCommand);
892 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
902 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
903 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)
907 BeginMessage(pszCommand);
908 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
919 void PushRequest(const char* pszCommand,
920 void (*fn)(void*, CDataStream&), void* param1)
923 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
925 CRITICAL_BLOCK(cs_mapRequests)
926 mapRequests[hashReply] = CRequestTracker(fn, param1);
928 PushMessage(pszCommand, hashReply);
931 template<typename T1>
932 void PushRequest(const char* pszCommand, const T1& a1,
933 void (*fn)(void*, CDataStream&), void* param1)
936 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
938 CRITICAL_BLOCK(cs_mapRequests)
939 mapRequests[hashReply] = CRequestTracker(fn, param1);
941 PushMessage(pszCommand, hashReply, a1);
944 template<typename T1, typename T2>
945 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
946 void (*fn)(void*, CDataStream&), void* param1)
949 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
951 CRITICAL_BLOCK(cs_mapRequests)
952 mapRequests[hashReply] = CRequestTracker(fn, param1);
954 PushMessage(pszCommand, hashReply, a1, a2);
959 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
960 bool IsSubscribed(unsigned int nChannel);
961 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
962 void CancelSubscribe(unsigned int nChannel);
963 void CloseSocketDisconnect();
976 inline void RelayInventory(const CInv& inv)
978 // Put on lists to offer to the other nodes
979 CRITICAL_BLOCK(cs_vNodes)
980 BOOST_FOREACH(CNode* pnode, vNodes)
981 pnode->PushInventory(inv);
985 void RelayMessage(const CInv& inv, const T& a)
987 CDataStream ss(SER_NETWORK);
990 RelayMessage(inv, ss);
994 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
996 CRITICAL_BLOCK(cs_mapRelay)
998 // Expire old relay messages
999 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
1001 mapRelay.erase(vRelayExpiration.front().second);
1002 vRelayExpiration.pop_front();
1005 // Save original serialized message so newer versions are preserved
1007 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1010 RelayInventory(inv);
1021 // Templates for the publish and subscription system.
1022 // The object being published as T& obj needs to have:
1023 // a set<unsigned int> setSources member
1024 // specializations of AdvertInsert and AdvertErase
1025 // Currently implemented for CTable and CProduct.
1028 template<typename T>
1029 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1032 obj.setSources.insert(pfrom->addr.ip);
1034 if (!AdvertInsert(obj))
1038 CRITICAL_BLOCK(cs_vNodes)
1039 BOOST_FOREACH(CNode* pnode, vNodes)
1040 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1041 pnode->PushMessage("publish", nChannel, nHops, obj);
1044 template<typename T>
1045 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1047 uint256 hash = obj.GetHash();
1049 CRITICAL_BLOCK(cs_vNodes)
1050 BOOST_FOREACH(CNode* pnode, vNodes)
1051 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1052 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
1057 template<typename T>
1058 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1061 obj.setSources.erase(pfrom->addr.ip);
1063 // If no longer supported by any sources, cancel it
1064 if (obj.setSources.empty())
1065 AdvertStopPublish(pfrom, nChannel, nHops, obj);