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>
19 class CRequestTracker;
22 extern int nBestHeight;
23 extern int nConnectTimeout;
27 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
28 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
29 inline unsigned short GetDefaultPort() { return fTestNet ? 18333 : 8333; }
30 static const unsigned int PUBLISH_HOPS = 5;
33 NODE_NETWORK = (1 << 0),
39 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
40 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
41 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
42 bool GetMyExternalIP(unsigned int& ipRet);
43 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
44 void AddressCurrentlyConnected(const CAddress& addr);
45 CNode* FindNode(unsigned int ip);
46 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
47 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
48 bool AnySubscribed(unsigned int nChannel);
49 void MapPort(bool fMapPort);
50 void DNSAddressSeed();
51 bool BindListenPort(std::string& strError=REF(std::string()));
52 void StartNode(void* parg);
69 extern char pchMessageStart[4];
74 enum { COMMAND_SIZE=12 };
75 char pchMessageStart[sizeof(::pchMessageStart)];
76 char pchCommand[COMMAND_SIZE];
77 unsigned int nMessageSize;
78 unsigned int nChecksum;
82 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
83 memset(pchCommand, 0, sizeof(pchCommand));
89 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
91 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
92 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
93 nMessageSize = nMessageSizeIn;
99 READWRITE(FLATDATA(pchMessageStart));
100 READWRITE(FLATDATA(pchCommand));
101 READWRITE(nMessageSize);
103 READWRITE(nChecksum);
106 std::string GetCommand()
108 if (pchCommand[COMMAND_SIZE-1] == 0)
109 return std::string(pchCommand, pchCommand + strlen(pchCommand));
111 return std::string(pchCommand, pchCommand + COMMAND_SIZE);
116 // Check start string
117 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
120 // Check the command string for errors
121 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
125 // Must be all zeros after the first zero
126 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
130 else if (*p1 < ' ' || *p1 > 0x7E)
135 if (nMessageSize > MAX_SIZE)
137 printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
150 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
156 unsigned char pchReserved[12];
160 // disk and network only
164 unsigned int nLastTry;
171 CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)
175 port = htons(portIn == 0 ? GetDefaultPort() : portIn);
176 nServices = nServicesIn;
179 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
182 ip = sockaddr.sin_addr.s_addr;
183 port = sockaddr.sin_port;
184 nServices = nServicesIn;
187 explicit CAddress(const char* pszIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
190 Lookup(pszIn, *this, nServicesIn, fNameLookup, portIn);
193 explicit CAddress(const char* pszIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
196 Lookup(pszIn, *this, nServicesIn, fNameLookup, 0, true);
199 explicit CAddress(std::string strIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
202 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, portIn);
205 explicit CAddress(std::string strIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
208 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, 0, true);
213 nServices = NODE_NETWORK;
214 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
216 port = htons(GetDefaultPort());
224 const_cast<CAddress*>(this)->Init();
225 if (nType & SER_DISK)
227 if ((nType & SER_DISK) || (nVersion >= 31402 && !(nType & SER_GETHASH)))
229 READWRITE(nServices);
230 READWRITE(FLATDATA(pchReserved)); // for IPv6
235 friend inline bool operator==(const CAddress& a, const CAddress& b)
237 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
242 friend inline bool operator!=(const CAddress& a, const CAddress& b)
247 friend inline bool operator<(const CAddress& a, const CAddress& b)
249 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
254 if (ntohl(a.ip) < ntohl(b.ip))
256 else if (a.ip == b.ip)
257 return ntohs(a.port) < ntohs(b.port);
262 std::vector<unsigned char> GetKey() const
266 ss << FLATDATA(pchReserved) << ip << port;
268 #if defined(_MSC_VER) && _MSC_VER < 1300
269 return std::vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
271 return std::vector<unsigned char>(ss.begin(), ss.end());
275 struct sockaddr_in GetSockAddr() const
277 struct sockaddr_in sockaddr;
278 memset(&sockaddr, 0, sizeof(sockaddr));
279 sockaddr.sin_family = AF_INET;
280 sockaddr.sin_addr.s_addr = ip;
281 sockaddr.sin_port = port;
287 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
290 bool IsRFC1918() const
292 return IsIPv4() && (GetByte(3) == 10 ||
293 (GetByte(3) == 192 && GetByte(2) == 168) ||
294 (GetByte(3) == 172 &&
295 (GetByte(2) >= 16 && GetByte(2) <= 31)));
298 bool IsRFC3927() const
300 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
305 return IsIPv4() && (GetByte(3) == 127 ||
309 bool IsRoutable() const
312 !(IsRFC1918() || IsRFC3927() || IsLocal());
317 // Clean up 3-byte shifted addresses caused by garbage in size field
318 // of addr messages from versions before 0.2.9 checksum.
319 // Two consecutive addr messages look like this:
320 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
321 // so if the first length field is garbled, it reads the second batch
322 // of addr misaligned by 3 bytes.
323 if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
326 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
329 unsigned char GetByte(int n) const
331 return ((unsigned char*)&ip)[3-n];
334 std::string ToStringIPPort() const
336 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
339 std::string ToStringIP() const
341 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
344 std::string ToStringPort() const
346 return strprintf("%u", ntohs(port));
349 std::string ToString() const
351 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
356 printf("CAddress(%s)\n", ToString().c_str());
372 static const char* ppszTypeName[] =
391 CInv(int typeIn, const uint256& hashIn)
397 CInv(const std::string& strType, const uint256& hashIn)
400 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
402 if (strType == ppszTypeName[i])
408 if (i == ARRAYLEN(ppszTypeName))
409 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
419 friend inline bool operator<(const CInv& a, const CInv& b)
421 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
424 bool IsKnownType() const
426 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
429 const char* GetCommand() const
432 throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
433 return ppszTypeName[type];
436 std::string ToString() const
438 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
443 printf("CInv(%s)\n", ToString().c_str());
451 class CRequestTracker
454 void (*fn)(void*, CDataStream&);
457 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
474 extern bool fAllowDNS;
475 extern uint64 nLocalServices;
476 extern CAddress addrLocalHost;
477 extern CNode* pnodeLocalHost;
478 extern uint64 nLocalHostNonce;
479 extern boost::array<int, 10> vnThreadsRunning;
480 extern SOCKET hListenSocket;
482 extern std::vector<CNode*> vNodes;
483 extern CCriticalSection cs_vNodes;
484 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
485 extern CCriticalSection cs_mapAddresses;
486 extern std::map<CInv, CDataStream> mapRelay;
487 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
488 extern CCriticalSection cs_mapRelay;
489 extern std::map<CInv, int64> mapAlreadyAskedFor;
492 extern int fUseProxy;
493 extern CAddress addrProxy;
508 CCriticalSection cs_vSend;
509 CCriticalSection cs_vRecv;
512 int64 nLastSendEmpty;
513 int64 nTimeConnected;
514 unsigned int nHeaderStart;
515 unsigned int nMessageStart;
518 std::string strSubVer;
522 bool fSuccessfullyConnected;
528 std::map<uint256, CRequestTracker> mapRequests;
529 CCriticalSection cs_mapRequests;
530 uint256 hashContinue;
531 CBlockIndex* pindexLastGetBlocksBegin;
532 uint256 hashLastGetBlocksEnd;
536 std::vector<CAddress> vAddrToSend;
537 std::set<CAddress> setAddrKnown;
539 std::set<uint256> setKnown;
541 // inventory based relay
542 std::set<CInv> setInventoryKnown;
543 std::vector<CInv> vInventoryToSend;
544 CCriticalSection cs_inventory;
545 std::multimap<int64, CInv> mapAskFor;
547 // publish and subscription
548 std::vector<char> vfSubscribe;
551 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
555 vSend.SetType(SER_NETWORK);
557 vRecv.SetType(SER_NETWORK);
559 // Version 0.2 obsoletes 20 Feb 2012
560 if (GetTime() > 1329696000)
562 vSend.SetVersion(209);
563 vRecv.SetVersion(209);
567 nLastSendEmpty = GetTime();
568 nTimeConnected = GetTime();
574 fClient = false; // set by version message
575 fInbound = fInboundIn;
576 fNetworkNode = false;
577 fSuccessfullyConnected = false;
582 pindexLastGetBlocksBegin = 0;
583 hashLastGetBlocksEnd = 0;
584 nStartingHeight = -1;
586 vfSubscribe.assign(256, false);
588 // Be shy and don't send version until we hear
595 if (hSocket != INVALID_SOCKET)
597 closesocket(hSocket);
598 hSocket = INVALID_SOCKET;
604 void operator=(const CNode&);
610 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
613 CNode* AddRef(int64 nTimeout=0)
616 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
629 void AddAddressKnown(const CAddress& addr)
631 setAddrKnown.insert(addr);
634 void PushAddress(const CAddress& addr)
636 // Known checking here is only to save space from duplicates.
637 // SendMessages will filter it again for knowns that were added
638 // after addresses were pushed.
639 if (addr.IsValid() && !setAddrKnown.count(addr))
640 vAddrToSend.push_back(addr);
644 void AddInventoryKnown(const CInv& inv)
646 CRITICAL_BLOCK(cs_inventory)
647 setInventoryKnown.insert(inv);
650 void PushInventory(const CInv& inv)
652 CRITICAL_BLOCK(cs_inventory)
653 if (!setInventoryKnown.count(inv))
654 vInventoryToSend.push_back(inv);
657 void AskFor(const CInv& inv)
659 // We're using mapAskFor as a priority queue,
660 // the key is the earliest time the request can be sent
661 int64& nRequestTime = mapAlreadyAskedFor[inv];
662 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
664 // Make sure not to reuse time indexes to keep things in the same order
665 int64 nNow = (GetTime() - 1) * 1000000;
666 static int64 nLastTime;
667 nLastTime = nNow = std::max(nNow, ++nLastTime);
669 // Each retry is 2 minutes after the last
670 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
671 mapAskFor.insert(std::make_pair(nRequestTime, inv));
676 void BeginMessage(const char* pszCommand)
679 if (nHeaderStart != -1)
681 nHeaderStart = vSend.size();
682 vSend << CMessageHeader(pszCommand, 0);
683 nMessageStart = vSend.size();
685 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
686 printf("sending: %s ", pszCommand);
691 if (nHeaderStart == -1)
693 vSend.resize(nHeaderStart);
697 printf("(aborted)\n");
702 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
704 printf("dropmessages DROPPING SEND MESSAGE\n");
709 if (nHeaderStart == -1)
713 unsigned int nSize = vSend.size() - nMessageStart;
714 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
717 if (vSend.GetVersion() >= 209)
719 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
720 unsigned int nChecksum = 0;
721 memcpy(&nChecksum, &hash, sizeof(nChecksum));
722 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
723 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
726 printf("(%d bytes) ", nSize);
734 void EndMessageAbortIfEmpty()
736 if (nHeaderStart == -1)
738 int nSize = vSend.size() - nMessageStart;
749 /// when NTP implemented, change to just nTime = GetAdjustedTime()
750 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
751 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
752 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
753 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
754 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
755 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
761 void PushMessage(const char* pszCommand)
765 BeginMessage(pszCommand);
775 template<typename T1>
776 void PushMessage(const char* pszCommand, const T1& a1)
780 BeginMessage(pszCommand);
791 template<typename T1, typename T2>
792 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
796 BeginMessage(pszCommand);
807 template<typename T1, typename T2, typename T3>
808 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
812 BeginMessage(pszCommand);
813 vSend << a1 << a2 << a3;
823 template<typename T1, typename T2, typename T3, typename T4>
824 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
828 BeginMessage(pszCommand);
829 vSend << a1 << a2 << a3 << a4;
839 template<typename T1, typename T2, typename T3, typename T4, typename T5>
840 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
844 BeginMessage(pszCommand);
845 vSend << a1 << a2 << a3 << a4 << a5;
855 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
856 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
860 BeginMessage(pszCommand);
861 vSend << a1 << a2 << a3 << a4 << a5 << a6;
871 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
872 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)
876 BeginMessage(pszCommand);
877 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
887 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
888 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)
892 BeginMessage(pszCommand);
893 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
903 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
904 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)
908 BeginMessage(pszCommand);
909 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
920 void PushRequest(const char* pszCommand,
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);
932 template<typename T1>
933 void PushRequest(const char* pszCommand, const T1& a1,
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);
945 template<typename T1, typename T2>
946 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
947 void (*fn)(void*, CDataStream&), void* param1)
950 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
952 CRITICAL_BLOCK(cs_mapRequests)
953 mapRequests[hashReply] = CRequestTracker(fn, param1);
955 PushMessage(pszCommand, hashReply, a1, a2);
960 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
961 bool IsSubscribed(unsigned int nChannel);
962 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
963 void CancelSubscribe(unsigned int nChannel);
964 void CloseSocketDisconnect();
977 inline void RelayInventory(const CInv& inv)
979 // Put on lists to offer to the other nodes
980 CRITICAL_BLOCK(cs_vNodes)
981 BOOST_FOREACH(CNode* pnode, vNodes)
982 pnode->PushInventory(inv);
986 void RelayMessage(const CInv& inv, const T& a)
988 CDataStream ss(SER_NETWORK);
991 RelayMessage(inv, ss);
995 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
997 CRITICAL_BLOCK(cs_mapRelay)
999 // Expire old relay messages
1000 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
1002 mapRelay.erase(vRelayExpiration.front().second);
1003 vRelayExpiration.pop_front();
1006 // Save original serialized message so newer versions are preserved
1008 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1011 RelayInventory(inv);
1022 // Templates for the publish and subscription system.
1023 // The object being published as T& obj needs to have:
1024 // a set<unsigned int> setSources member
1025 // specializations of AdvertInsert and AdvertErase
1026 // Currently implemented for CTable and CProduct.
1029 template<typename T>
1030 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1033 obj.setSources.insert(pfrom->addr.ip);
1035 if (!AdvertInsert(obj))
1039 CRITICAL_BLOCK(cs_vNodes)
1040 BOOST_FOREACH(CNode* pnode, vNodes)
1041 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1042 pnode->PushMessage("publish", nChannel, nHops, obj);
1045 template<typename T>
1046 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1048 uint256 hash = obj.GetHash();
1050 CRITICAL_BLOCK(cs_vNodes)
1051 BOOST_FOREACH(CNode* pnode, vNodes)
1052 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1053 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
1058 template<typename T>
1059 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1062 obj.setSources.erase(pfrom->addr.ip);
1064 // If no longer supported by any sources, cancel it
1065 if (obj.setSources.empty())
1066 AdvertStopPublish(pfrom, nChannel, nHops, obj);