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;
25 inline unsigned short GetDefaultPort() { return fTestNet ? 18333 : 8333; }
26 static const unsigned int PUBLISH_HOPS = 5;
29 NODE_NETWORK = (1 << 0),
35 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);
36 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
37 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
38 bool GetMyExternalIP(unsigned int& ipRet);
39 bool AddAddress(CAddress addr, int64 nTimePenalty=0);
40 void AddressCurrentlyConnected(const CAddress& addr);
41 CNode* FindNode(unsigned int ip);
42 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
43 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
44 bool AnySubscribed(unsigned int nChannel);
45 void MapPort(bool fMapPort);
46 void DNSAddressSeed();
47 bool BindListenPort(std::string& strError=REF(std::string()));
48 void StartNode(void* parg);
65 extern char pchMessageStart[4];
70 enum { COMMAND_SIZE=12 };
71 char pchMessageStart[sizeof(::pchMessageStart)];
72 char pchCommand[COMMAND_SIZE];
73 unsigned int nMessageSize;
74 unsigned int nChecksum;
78 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
79 memset(pchCommand, 0, sizeof(pchCommand));
85 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
87 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));
88 strncpy(pchCommand, pszCommand, COMMAND_SIZE);
89 nMessageSize = nMessageSizeIn;
95 READWRITE(FLATDATA(pchMessageStart));
96 READWRITE(FLATDATA(pchCommand));
97 READWRITE(nMessageSize);
102 std::string GetCommand()
104 if (pchCommand[COMMAND_SIZE-1] == 0)
105 return std::string(pchCommand, pchCommand + strlen(pchCommand));
107 return std::string(pchCommand, pchCommand + COMMAND_SIZE);
112 // Check start string
113 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)
116 // Check the command string for errors
117 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
121 // Must be all zeros after the first zero
122 for (; p1 < pchCommand + COMMAND_SIZE; p1++)
126 else if (*p1 < ' ' || *p1 > 0x7E)
131 if (nMessageSize > MAX_SIZE)
133 printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand().c_str(), nMessageSize);
146 static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };
152 unsigned char pchReserved[12];
156 // disk and network only
160 unsigned int nLastTry;
167 CAddress(unsigned int ipIn, unsigned short portIn=0, uint64 nServicesIn=NODE_NETWORK)
171 port = htons(portIn == 0 ? GetDefaultPort() : portIn);
172 nServices = nServicesIn;
175 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=NODE_NETWORK)
178 ip = sockaddr.sin_addr.s_addr;
179 port = sockaddr.sin_port;
180 nServices = nServicesIn;
183 explicit CAddress(const char* pszIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
186 Lookup(pszIn, *this, nServicesIn, fNameLookup, portIn);
189 explicit CAddress(const char* pszIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
192 Lookup(pszIn, *this, nServicesIn, fNameLookup, 0, true);
195 explicit CAddress(std::string strIn, int portIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
198 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, portIn);
201 explicit CAddress(std::string strIn, bool fNameLookup = false, uint64 nServicesIn=NODE_NETWORK)
204 Lookup(strIn.c_str(), *this, nServicesIn, fNameLookup, 0, true);
209 nServices = NODE_NETWORK;
210 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));
212 port = htons(GetDefaultPort());
220 const_cast<CAddress*>(this)->Init();
221 if (nType & SER_DISK)
223 if ((nType & SER_DISK) || (nVersion >= 31402 && !(nType & SER_GETHASH)))
225 READWRITE(nServices);
226 READWRITE(FLATDATA(pchReserved)); // for IPv6
231 friend inline bool operator==(const CAddress& a, const CAddress& b)
233 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&
238 friend inline bool operator!=(const CAddress& a, const CAddress& b)
243 friend inline bool operator<(const CAddress& a, const CAddress& b)
245 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));
250 if (ntohl(a.ip) < ntohl(b.ip))
252 else if (a.ip == b.ip)
253 return ntohs(a.port) < ntohs(b.port);
258 std::vector<unsigned char> GetKey() const
262 ss << FLATDATA(pchReserved) << ip << port;
264 #if defined(_MSC_VER) && _MSC_VER < 1300
265 return std::vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);
267 return std::vector<unsigned char>(ss.begin(), ss.end());
271 struct sockaddr_in GetSockAddr() const
273 struct sockaddr_in sockaddr;
274 memset(&sockaddr, 0, sizeof(sockaddr));
275 sockaddr.sin_family = AF_INET;
276 sockaddr.sin_addr.s_addr = ip;
277 sockaddr.sin_port = port;
283 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);
286 bool IsRFC1918() const
288 return IsIPv4() && (GetByte(3) == 10 ||
289 (GetByte(3) == 192 && GetByte(2) == 168) ||
290 (GetByte(3) == 172 &&
291 (GetByte(2) >= 16 && GetByte(2) <= 31)));
294 bool IsRFC3927() const
296 return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
301 return IsIPv4() && (GetByte(3) == 127 ||
305 bool IsRoutable() const
308 !(IsRFC1918() || IsRFC3927() || IsLocal());
313 // Clean up 3-byte shifted addresses caused by garbage in size field
314 // of addr messages from versions before 0.2.9 checksum.
315 // Two consecutive addr messages look like this:
316 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
317 // so if the first length field is garbled, it reads the second batch
318 // of addr misaligned by 3 bytes.
319 if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
322 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
325 unsigned char GetByte(int n) const
327 return ((unsigned char*)&ip)[3-n];
330 std::string ToStringIPPort() const
332 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
335 std::string ToStringIP() const
337 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
340 std::string ToStringPort() const
342 return strprintf("%u", ntohs(port));
345 std::string ToString() const
347 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
352 printf("CAddress(%s)\n", ToString().c_str());
368 static const char* ppszTypeName[] =
387 CInv(int typeIn, const uint256& hashIn)
393 CInv(const std::string& strType, const uint256& hashIn)
396 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
398 if (strType == ppszTypeName[i])
404 if (i == ARRAYLEN(ppszTypeName))
405 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
415 friend inline bool operator<(const CInv& a, const CInv& b)
417 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
420 bool IsKnownType() const
422 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
425 const char* GetCommand() const
428 throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
429 return ppszTypeName[type];
432 std::string ToString() const
434 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
439 printf("CInv(%s)\n", ToString().c_str());
447 class CRequestTracker
450 void (*fn)(void*, CDataStream&);
453 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
470 extern bool fAllowDNS;
471 extern uint64 nLocalServices;
472 extern CAddress addrLocalHost;
473 extern CNode* pnodeLocalHost;
474 extern uint64 nLocalHostNonce;
475 extern boost::array<int, 10> vnThreadsRunning;
476 extern SOCKET hListenSocket;
478 extern std::vector<CNode*> vNodes;
479 extern CCriticalSection cs_vNodes;
480 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
481 extern CCriticalSection cs_mapAddresses;
482 extern std::map<CInv, CDataStream> mapRelay;
483 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
484 extern CCriticalSection cs_mapRelay;
485 extern std::map<CInv, int64> mapAlreadyAskedFor;
488 extern int fUseProxy;
489 extern CAddress addrProxy;
504 CCriticalSection cs_vSend;
505 CCriticalSection cs_vRecv;
508 int64 nLastSendEmpty;
509 int64 nTimeConnected;
510 unsigned int nHeaderStart;
511 unsigned int nMessageStart;
514 std::string strSubVer;
518 bool fSuccessfullyConnected;
524 std::map<uint256, CRequestTracker> mapRequests;
525 CCriticalSection cs_mapRequests;
526 uint256 hashContinue;
527 CBlockIndex* pindexLastGetBlocksBegin;
528 uint256 hashLastGetBlocksEnd;
532 std::vector<CAddress> vAddrToSend;
533 std::set<CAddress> setAddrKnown;
535 std::set<uint256> setKnown;
537 // inventory based relay
538 std::set<CInv> setInventoryKnown;
539 std::vector<CInv> vInventoryToSend;
540 CCriticalSection cs_inventory;
541 std::multimap<int64, CInv> mapAskFor;
543 // publish and subscription
544 std::vector<char> vfSubscribe;
547 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
551 vSend.SetType(SER_NETWORK);
553 vRecv.SetType(SER_NETWORK);
555 // Version 0.2 obsoletes 20 Feb 2012
556 if (GetTime() > 1329696000)
558 vSend.SetVersion(209);
559 vRecv.SetVersion(209);
563 nLastSendEmpty = GetTime();
564 nTimeConnected = GetTime();
570 fClient = false; // set by version message
571 fInbound = fInboundIn;
572 fNetworkNode = false;
573 fSuccessfullyConnected = false;
578 pindexLastGetBlocksBegin = 0;
579 hashLastGetBlocksEnd = 0;
580 nStartingHeight = -1;
582 vfSubscribe.assign(256, false);
584 // Be shy and don't send version until we hear
591 if (hSocket != INVALID_SOCKET)
593 closesocket(hSocket);
594 hSocket = INVALID_SOCKET;
600 void operator=(const CNode&);
606 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
609 CNode* AddRef(int64 nTimeout=0)
612 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
625 void AddAddressKnown(const CAddress& addr)
627 setAddrKnown.insert(addr);
630 void PushAddress(const CAddress& addr)
632 // Known checking here is only to save space from duplicates.
633 // SendMessages will filter it again for knowns that were added
634 // after addresses were pushed.
635 if (addr.IsValid() && !setAddrKnown.count(addr))
636 vAddrToSend.push_back(addr);
640 void AddInventoryKnown(const CInv& inv)
642 CRITICAL_BLOCK(cs_inventory)
643 setInventoryKnown.insert(inv);
646 void PushInventory(const CInv& inv)
648 CRITICAL_BLOCK(cs_inventory)
649 if (!setInventoryKnown.count(inv))
650 vInventoryToSend.push_back(inv);
653 void AskFor(const CInv& inv)
655 // We're using mapAskFor as a priority queue,
656 // the key is the earliest time the request can be sent
657 int64& nRequestTime = mapAlreadyAskedFor[inv];
658 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
660 // Make sure not to reuse time indexes to keep things in the same order
661 int64 nNow = (GetTime() - 1) * 1000000;
662 static int64 nLastTime;
663 nLastTime = nNow = std::max(nNow, ++nLastTime);
665 // Each retry is 2 minutes after the last
666 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
667 mapAskFor.insert(std::make_pair(nRequestTime, inv));
672 void BeginMessage(const char* pszCommand)
675 if (nHeaderStart != -1)
677 nHeaderStart = vSend.size();
678 vSend << CMessageHeader(pszCommand, 0);
679 nMessageStart = vSend.size();
681 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
682 printf("sending: %s ", pszCommand);
687 if (nHeaderStart == -1)
689 vSend.resize(nHeaderStart);
693 printf("(aborted)\n");
698 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
700 printf("dropmessages DROPPING SEND MESSAGE\n");
705 if (nHeaderStart == -1)
709 unsigned int nSize = vSend.size() - nMessageStart;
710 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
713 if (vSend.GetVersion() >= 209)
715 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
716 unsigned int nChecksum = 0;
717 memcpy(&nChecksum, &hash, sizeof(nChecksum));
718 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
719 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
722 printf("(%d bytes) ", nSize);
730 void EndMessageAbortIfEmpty()
732 if (nHeaderStart == -1)
734 int nSize = vSend.size() - nMessageStart;
745 /// when NTP implemented, change to just nTime = GetAdjustedTime()
746 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
747 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
748 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
749 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
750 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
751 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
757 void PushMessage(const char* pszCommand)
761 BeginMessage(pszCommand);
771 template<typename T1>
772 void PushMessage(const char* pszCommand, const T1& a1)
776 BeginMessage(pszCommand);
787 template<typename T1, typename T2>
788 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
792 BeginMessage(pszCommand);
803 template<typename T1, typename T2, typename T3>
804 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
808 BeginMessage(pszCommand);
809 vSend << a1 << a2 << a3;
819 template<typename T1, typename T2, typename T3, typename T4>
820 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
824 BeginMessage(pszCommand);
825 vSend << a1 << a2 << a3 << a4;
835 template<typename T1, typename T2, typename T3, typename T4, typename T5>
836 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
840 BeginMessage(pszCommand);
841 vSend << a1 << a2 << a3 << a4 << a5;
851 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
852 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
856 BeginMessage(pszCommand);
857 vSend << a1 << a2 << a3 << a4 << a5 << a6;
867 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
868 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)
872 BeginMessage(pszCommand);
873 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
883 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
884 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)
888 BeginMessage(pszCommand);
889 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
899 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
900 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)
904 BeginMessage(pszCommand);
905 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
916 void PushRequest(const char* pszCommand,
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);
928 template<typename T1>
929 void PushRequest(const char* pszCommand, const T1& a1,
930 void (*fn)(void*, CDataStream&), void* param1)
933 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
935 CRITICAL_BLOCK(cs_mapRequests)
936 mapRequests[hashReply] = CRequestTracker(fn, param1);
938 PushMessage(pszCommand, hashReply, a1);
941 template<typename T1, typename T2>
942 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
943 void (*fn)(void*, CDataStream&), void* param1)
946 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
948 CRITICAL_BLOCK(cs_mapRequests)
949 mapRequests[hashReply] = CRequestTracker(fn, param1);
951 PushMessage(pszCommand, hashReply, a1, a2);
956 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
957 bool IsSubscribed(unsigned int nChannel);
958 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
959 void CancelSubscribe(unsigned int nChannel);
960 void CloseSocketDisconnect();
973 inline void RelayInventory(const CInv& inv)
975 // Put on lists to offer to the other nodes
976 CRITICAL_BLOCK(cs_vNodes)
977 BOOST_FOREACH(CNode* pnode, vNodes)
978 pnode->PushInventory(inv);
982 void RelayMessage(const CInv& inv, const T& a)
984 CDataStream ss(SER_NETWORK);
987 RelayMessage(inv, ss);
991 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
993 CRITICAL_BLOCK(cs_mapRelay)
995 // Expire old relay messages
996 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
998 mapRelay.erase(vRelayExpiration.front().second);
999 vRelayExpiration.pop_front();
1002 // Save original serialized message so newer versions are preserved
1004 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1007 RelayInventory(inv);
1018 // Templates for the publish and subscription system.
1019 // The object being published as T& obj needs to have:
1020 // a set<unsigned int> setSources member
1021 // specializations of AdvertInsert and AdvertErase
1022 // Currently implemented for CTable and CProduct.
1025 template<typename T>
1026 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1029 obj.setSources.insert(pfrom->addr.ip);
1031 if (!AdvertInsert(obj))
1035 CRITICAL_BLOCK(cs_vNodes)
1036 BOOST_FOREACH(CNode* pnode, vNodes)
1037 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1038 pnode->PushMessage("publish", nChannel, nHops, obj);
1041 template<typename T>
1042 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1044 uint256 hash = obj.GetHash();
1046 CRITICAL_BLOCK(cs_vNodes)
1047 BOOST_FOREACH(CNode* pnode, vNodes)
1048 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1049 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
1054 template<typename T>
1055 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1058 obj.setSources.erase(pfrom->addr.ip);
1060 // If no longer supported by any sources, cancel it
1061 if (obj.setSources.empty())
1062 AdvertStopPublish(pfrom, nChannel, nHops, obj);