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 <boost/foreach.hpp>
10 #include <openssl/rand.h>
13 #include <arpa/inet.h>
19 class CRequestTracker;
22 extern int nBestHeight;
23 extern int nConnectTimeout;
27 inline unsigned short GetDefaultPort() { return fTestNet ? 18333 : 8333; }
28 static const unsigned int PUBLISH_HOPS = 5;
31 NODE_NETWORK = (1 << 0),
37 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
38 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
39 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
40 bool GetMyExternalIP(unsigned int& ipRet);
41 bool AddAddress(CAddress addr, int64 nTimePenalty=0);
42 void AddressCurrentlyConnected(const CAddress& addr);
43 CNode* FindNode(unsigned int ip);
44 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
45 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
46 bool AnySubscribed(unsigned int nChannel);
47 void MapPort(bool fMapPort);
48 void DNSAddressSeed();
49 bool BindListenPort(std::string& strError=REF(std::string()));
50 void StartNode(void* parg);
67 extern char pchMessageStart[4];
72 enum { COMMAND_SIZE=12 };
73 char pchMessageStart[sizeof(::pchMessageStart)];
74 char pchCommand[COMMAND_SIZE];
75 unsigned int nMessageSize;
76 unsigned int nChecksum;
80 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
81 memset(pchCommand, 0, sizeof(pchCommand));
87 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
89 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
90 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
91 nMessageSize = nMessageSizeIn;
97 READWRITE(FLATDATA(pchMessageStart));
98 READWRITE(FLATDATA(pchCommand));
99 READWRITE(nMessageSize);
101 READWRITE(nChecksum);
104 std::string GetCommand()
106 if (pchCommand[COMMAND_SIZE-1] == 0)
107 return std::string(pchCommand, pchCommand + strlen(pchCommand));
109 return std::string(pchCommand, pchCommand + COMMAND_SIZE);
114 // Check start string
115 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
118 // Check the command string for errors
119 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
123 // Must be all zeros after the first zero
124 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
128 else if (*p1 < ' ' || *p1 > 0x7E)
133 if (nMessageSize > MAX_SIZE)
135 printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
148 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
154 unsigned char pchReserved[12];
158 // disk and network only
162 unsigned int nLastTry;
169 CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)
173 port = htons(portIn == 0 ? GetDefaultPort() : portIn);
174 nServices = nServicesIn;
177 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
180 ip = sockaddr.sin_addr.s_addr;
181 port = sockaddr.sin_port;
182 nServices = nServicesIn;
185 explicit CAddress(const char* pszIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
188 Lookup(pszIn, *this, nServicesIn, fNameLookup, portIn);
191 explicit CAddress(const char* pszIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
194 Lookup(pszIn, *this, nServicesIn, fNameLookup, 0, true);
197 explicit CAddress(std::string strIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
200 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, portIn);
203 explicit CAddress(std::string strIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
206 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, 0, true);
211 nServices = NODE_NETWORK;
212 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
214 port = htons(GetDefaultPort());
222 const_cast<CAddress*>(this)->Init();
223 if (nType & SER_DISK)
225 if ((nType & SER_DISK) || (nVersion >= 31402 && !(nType & SER_GETHASH)))
227 READWRITE(nServices);
228 READWRITE(FLATDATA(pchReserved)); // for IPv6
233 friend inline bool operator==(const CAddress& a, const CAddress& b)
235 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
240 friend inline bool operator!=(const CAddress& a, const CAddress& b)
245 friend inline bool operator<(const CAddress& a, const CAddress& b)
247 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
252 if (ntohl(a.ip) < ntohl(b.ip))
254 else if (a.ip == b.ip)
255 return ntohs(a.port) < ntohs(b.port);
260 std::vector<unsigned char> GetKey() const
264 ss << FLATDATA(pchReserved) << ip << port;
266 #if defined(_MSC_VER) && _MSC_VER < 1300
267 return std::vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
269 return std::vector<unsigned char>(ss.begin(), ss.end());
273 struct sockaddr_in GetSockAddr() const
275 struct sockaddr_in sockaddr;
276 memset(&sockaddr, 0, sizeof(sockaddr));
277 sockaddr.sin_family = AF_INET;
278 sockaddr.sin_addr.s_addr = ip;
279 sockaddr.sin_port = port;
285 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
288 bool IsRFC1918() const
290 return IsIPv4() && (GetByte(3) == 10 ||
291 (GetByte(3) == 192 && GetByte(2) == 168) ||
292 (GetByte(3) == 172 &&
293 (GetByte(2) >= 16 && GetByte(2) <= 31)));
296 bool IsRFC3927() const
298 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
303 return IsIPv4() && (GetByte(3) == 127 ||
307 bool IsRoutable() const
310 !(IsRFC1918() || IsRFC3927() || IsLocal());
315 // Clean up 3-byte shifted addresses caused by garbage in size field
316 // of addr messages from versions before 0.2.9 checksum.
317 // Two consecutive addr messages look like this:
318 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
319 // so if the first length field is garbled, it reads the second batch
320 // of addr misaligned by 3 bytes.
321 if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
324 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
327 unsigned char GetByte(int n) const
329 return ((unsigned char*)&ip)[3-n];
332 std::string ToStringIPPort() const
334 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
337 std::string ToStringIP() const
339 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
342 std::string ToStringPort() const
344 return strprintf("%u", ntohs(port));
347 std::string ToString() const
349 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
354 printf("CAddress(%s)\n", ToString().c_str());
370 static const char* ppszTypeName[] =
389 CInv(int typeIn, const uint256& hashIn)
395 CInv(const std::string& strType, const uint256& hashIn)
398 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
400 if (strType == ppszTypeName[i])
406 if (i == ARRAYLEN(ppszTypeName))
407 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
417 friend inline bool operator<(const CInv& a, const CInv& b)
419 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
422 bool IsKnownType() const
424 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
427 const char* GetCommand() const
430 throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
431 return ppszTypeName[type];
434 std::string ToString() const
436 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
441 printf("CInv(%s)\n", ToString().c_str());
449 class CRequestTracker
452 void (*fn)(void*, CDataStream&);
455 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
472 extern bool fAllowDNS;
473 extern uint64 nLocalServices;
474 extern CAddress addrLocalHost;
475 extern CNode* pnodeLocalHost;
476 extern uint64 nLocalHostNonce;
477 extern boost::array<int, 10> vnThreadsRunning;
478 extern SOCKET hListenSocket;
480 extern std::vector<CNode*> vNodes;
481 extern CCriticalSection cs_vNodes;
482 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
483 extern CCriticalSection cs_mapAddresses;
484 extern std::map<CInv, CDataStream> mapRelay;
485 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
486 extern CCriticalSection cs_mapRelay;
487 extern std::map<CInv, int64> mapAlreadyAskedFor;
490 extern int fUseProxy;
491 extern CAddress addrProxy;
506 CCriticalSection cs_vSend;
507 CCriticalSection cs_vRecv;
510 int64 nLastSendEmpty;
511 int64 nTimeConnected;
512 unsigned int nHeaderStart;
513 unsigned int nMessageStart;
516 std::string strSubVer;
520 bool fSuccessfullyConnected;
526 std::map<uint256, CRequestTracker> mapRequests;
527 CCriticalSection cs_mapRequests;
528 uint256 hashContinue;
529 CBlockIndex* pindexLastGetBlocksBegin;
530 uint256 hashLastGetBlocksEnd;
534 std::vector<CAddress> vAddrToSend;
535 std::set<CAddress> setAddrKnown;
537 std::set<uint256> setKnown;
539 // inventory based relay
540 std::set<CInv> setInventoryKnown;
541 std::vector<CInv> vInventoryToSend;
542 CCriticalSection cs_inventory;
543 std::multimap<int64, CInv> mapAskFor;
545 // publish and subscription
546 std::vector<char> vfSubscribe;
549 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
553 vSend.SetType(SER_NETWORK);
555 vRecv.SetType(SER_NETWORK);
557 // Version 0.2 obsoletes 20 Feb 2012
558 if (GetTime() > 1329696000)
560 vSend.SetVersion(209);
561 vRecv.SetVersion(209);
565 nLastSendEmpty = GetTime();
566 nTimeConnected = GetTime();
572 fClient = false; // set by version message
573 fInbound = fInboundIn;
574 fNetworkNode = false;
575 fSuccessfullyConnected = false;
580 pindexLastGetBlocksBegin = 0;
581 hashLastGetBlocksEnd = 0;
582 nStartingHeight = -1;
584 vfSubscribe.assign(256, false);
586 // Be shy and don't send version until we hear
593 if (hSocket != INVALID_SOCKET)
595 closesocket(hSocket);
596 hSocket = INVALID_SOCKET;
602 void operator=(const CNode&);
608 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
611 CNode* AddRef(int64 nTimeout=0)
614 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
627 void AddAddressKnown(const CAddress& addr)
629 setAddrKnown.insert(addr);
632 void PushAddress(const CAddress& addr)
634 // Known checking here is only to save space from duplicates.
635 // SendMessages will filter it again for knowns that were added
636 // after addresses were pushed.
637 if (addr.IsValid() && !setAddrKnown.count(addr))
638 vAddrToSend.push_back(addr);
642 void AddInventoryKnown(const CInv& inv)
644 CRITICAL_BLOCK(cs_inventory)
645 setInventoryKnown.insert(inv);
648 void PushInventory(const CInv& inv)
650 CRITICAL_BLOCK(cs_inventory)
651 if (!setInventoryKnown.count(inv))
652 vInventoryToSend.push_back(inv);
655 void AskFor(const CInv& inv)
657 // We're using mapAskFor as a priority queue,
658 // the key is the earliest time the request can be sent
659 int64& nRequestTime = mapAlreadyAskedFor[inv];
660 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
662 // Make sure not to reuse time indexes to keep things in the same order
663 int64 nNow = (GetTime() - 1) * 1000000;
664 static int64 nLastTime;
665 nLastTime = nNow = std::max(nNow, ++nLastTime);
667 // Each retry is 2 minutes after the last
668 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
669 mapAskFor.insert(std::make_pair(nRequestTime, inv));
674 void BeginMessage(const char* pszCommand)
677 if (nHeaderStart != -1)
679 nHeaderStart = vSend.size();
680 vSend << CMessageHeader(pszCommand, 0);
681 nMessageStart = vSend.size();
683 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
684 printf("sending: %s ", pszCommand);
689 if (nHeaderStart == -1)
691 vSend.resize(nHeaderStart);
695 printf("(aborted)\n");
700 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
702 printf("dropmessages DROPPING SEND MESSAGE\n");
707 if (nHeaderStart == -1)
711 unsigned int nSize = vSend.size() - nMessageStart;
712 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
715 if (vSend.GetVersion() >= 209)
717 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
718 unsigned int nChecksum = 0;
719 memcpy(&nChecksum, &hash, sizeof(nChecksum));
720 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
721 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
724 printf("(%d bytes) ", nSize);
732 void EndMessageAbortIfEmpty()
734 if (nHeaderStart == -1)
736 int nSize = vSend.size() - nMessageStart;
747 /// when NTP implemented, change to just nTime = GetAdjustedTime()
748 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
749 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
750 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
751 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
752 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
753 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
759 void PushMessage(const char* pszCommand)
763 BeginMessage(pszCommand);
773 template<typename T1>
774 void PushMessage(const char* pszCommand, const T1& a1)
778 BeginMessage(pszCommand);
789 template<typename T1, typename T2>
790 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
794 BeginMessage(pszCommand);
805 template<typename T1, typename T2, typename T3>
806 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
810 BeginMessage(pszCommand);
811 vSend << a1 << a2 << a3;
821 template<typename T1, typename T2, typename T3, typename T4>
822 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
826 BeginMessage(pszCommand);
827 vSend << a1 << a2 << a3 << a4;
837 template<typename T1, typename T2, typename T3, typename T4, typename T5>
838 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
842 BeginMessage(pszCommand);
843 vSend << a1 << a2 << a3 << a4 << a5;
853 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
854 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
858 BeginMessage(pszCommand);
859 vSend << a1 << a2 << a3 << a4 << a5 << a6;
869 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
870 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)
874 BeginMessage(pszCommand);
875 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
885 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
886 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)
890 BeginMessage(pszCommand);
891 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
901 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
902 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)
906 BeginMessage(pszCommand);
907 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
918 void PushRequest(const char* pszCommand,
919 void (*fn)(void*, CDataStream&), void* param1)
922 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
924 CRITICAL_BLOCK(cs_mapRequests)
925 mapRequests[hashReply] = CRequestTracker(fn, param1);
927 PushMessage(pszCommand, hashReply);
930 template<typename T1>
931 void PushRequest(const char* pszCommand, const T1& a1,
932 void (*fn)(void*, CDataStream&), void* param1)
935 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
937 CRITICAL_BLOCK(cs_mapRequests)
938 mapRequests[hashReply] = CRequestTracker(fn, param1);
940 PushMessage(pszCommand, hashReply, a1);
943 template<typename T1, typename T2>
944 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
945 void (*fn)(void*, CDataStream&), void* param1)
948 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
950 CRITICAL_BLOCK(cs_mapRequests)
951 mapRequests[hashReply] = CRequestTracker(fn, param1);
953 PushMessage(pszCommand, hashReply, a1, a2);
958 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
959 bool IsSubscribed(unsigned int nChannel);
960 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
961 void CancelSubscribe(unsigned int nChannel);
962 void CloseSocketDisconnect();
975 inline void RelayInventory(const CInv& inv)
977 // Put on lists to offer to the other nodes
978 CRITICAL_BLOCK(cs_vNodes)
979 BOOST_FOREACH(CNode* pnode, vNodes)
980 pnode->PushInventory(inv);
984 void RelayMessage(const CInv& inv, const T& a)
986 CDataStream ss(SER_NETWORK);
989 RelayMessage(inv, ss);
993 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
995 CRITICAL_BLOCK(cs_mapRelay)
997 // Expire old relay messages
998 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
1000 mapRelay.erase(vRelayExpiration.front().second);
1001 vRelayExpiration.pop_front();
1004 // Save original serialized message so newer versions are preserved
1006 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1009 RelayInventory(inv);
1020 // Templates for the publish and subscription system.
1021 // The object being published as T& obj needs to have:
1022 // a set<unsigned int> setSources member
1023 // specializations of AdvertInsert and AdvertErase
1024 // Currently implemented for CTable and CProduct.
1027 template<typename T>
1028 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1031 obj.setSources.insert(pfrom->addr.ip);
1033 if (!AdvertInsert(obj))
1037 CRITICAL_BLOCK(cs_vNodes)
1038 BOOST_FOREACH(CNode* pnode, vNodes)
1039 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1040 pnode->PushMessage("publish", nChannel, nHops, obj);
1043 template<typename T>
1044 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1046 uint256 hash = obj.GetHash();
1048 CRITICAL_BLOCK(cs_vNodes)
1049 BOOST_FOREACH(CNode* pnode, vNodes)
1050 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1051 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
1056 template<typename T>
1057 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1060 obj.setSources.erase(pfrom->addr.ip);
1062 // If no longer supported by any sources, cancel it
1063 if (obj.setSources.empty())
1064 AdvertStopPublish(pfrom, nChannel, nHops, obj);