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 IsRoutable() const
289 !(GetByte(3) == 10 ||
290 (GetByte(3) == 192 && GetByte(2) == 168) ||
297 // Clean up 3-byte shifted addresses caused by garbage in size field
298 // of addr messages from versions before 0.2.9 checksum.
299 // Two consecutive addr messages look like this:
300 // header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
301 // so if the first length field is garbled, it reads the second batch
302 // of addr misaligned by 3 bytes.
303 if (memcmp(pchReserved, pchIPv4+3, sizeof(pchIPv4)-3) == 0)
306 return (ip != 0 && ip != INADDR_NONE && port != htons(USHRT_MAX));
309 unsigned char GetByte(int n) const
311 return ((unsigned char*)&ip)[3-n];
314 std::string ToStringIPPort() const
316 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
319 std::string ToStringIP() const
321 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
324 std::string ToStringPort() const
326 return strprintf("%u", ntohs(port));
329 std::string ToString() const
331 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));
336 printf("CAddress(%s)\n", ToString().c_str());
352 static const char* ppszTypeName[] =
371 CInv(int typeIn, const uint256& hashIn)
377 CInv(const std::string& strType, const uint256& hashIn)
380 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
382 if (strType == ppszTypeName[i])
388 if (i == ARRAYLEN(ppszTypeName))
389 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));
399 friend inline bool operator<(const CInv& a, const CInv& b)
401 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
404 bool IsKnownType() const
406 return (type >= 1 && type < ARRAYLEN(ppszTypeName));
409 const char* GetCommand() const
412 throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
413 return ppszTypeName[type];
416 std::string ToString() const
418 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,20).c_str());
423 printf("CInv(%s)\n", ToString().c_str());
431 class CRequestTracker
434 void (*fn)(void*, CDataStream&);
437 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
454 extern bool fAllowDNS;
455 extern uint64 nLocalServices;
456 extern CAddress addrLocalHost;
457 extern CNode* pnodeLocalHost;
458 extern uint64 nLocalHostNonce;
459 extern boost::array<int, 10> vnThreadsRunning;
460 extern SOCKET hListenSocket;
462 extern std::vector<CNode*> vNodes;
463 extern CCriticalSection cs_vNodes;
464 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
465 extern CCriticalSection cs_mapAddresses;
466 extern std::map<CInv, CDataStream> mapRelay;
467 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
468 extern CCriticalSection cs_mapRelay;
469 extern std::map<CInv, int64> mapAlreadyAskedFor;
472 extern int fUseProxy;
473 extern CAddress addrProxy;
488 CCriticalSection cs_vSend;
489 CCriticalSection cs_vRecv;
492 int64 nLastSendEmpty;
493 int64 nTimeConnected;
494 unsigned int nHeaderStart;
495 unsigned int nMessageStart;
498 std::string strSubVer;
502 bool fSuccessfullyConnected;
508 std::map<uint256, CRequestTracker> mapRequests;
509 CCriticalSection cs_mapRequests;
510 uint256 hashContinue;
511 CBlockIndex* pindexLastGetBlocksBegin;
512 uint256 hashLastGetBlocksEnd;
516 std::vector<CAddress> vAddrToSend;
517 std::set<CAddress> setAddrKnown;
519 std::set<uint256> setKnown;
521 // inventory based relay
522 std::set<CInv> setInventoryKnown;
523 std::vector<CInv> vInventoryToSend;
524 CCriticalSection cs_inventory;
525 std::multimap<int64, CInv> mapAskFor;
527 // publish and subscription
528 std::vector<char> vfSubscribe;
531 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
535 vSend.SetType(SER_NETWORK);
537 vRecv.SetType(SER_NETWORK);
539 // Version 0.2 obsoletes 20 Feb 2012
540 if (GetTime() > 1329696000)
542 vSend.SetVersion(209);
543 vRecv.SetVersion(209);
547 nLastSendEmpty = GetTime();
548 nTimeConnected = GetTime();
554 fClient = false; // set by version message
555 fInbound = fInboundIn;
556 fNetworkNode = false;
557 fSuccessfullyConnected = false;
562 pindexLastGetBlocksBegin = 0;
563 hashLastGetBlocksEnd = 0;
564 nStartingHeight = -1;
566 vfSubscribe.assign(256, false);
568 // Be shy and don't send version until we hear
575 if (hSocket != INVALID_SOCKET)
577 closesocket(hSocket);
578 hSocket = INVALID_SOCKET;
584 void operator=(const CNode&);
590 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
593 CNode* AddRef(int64 nTimeout=0)
596 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
609 void AddAddressKnown(const CAddress& addr)
611 setAddrKnown.insert(addr);
614 void PushAddress(const CAddress& addr)
616 // Known checking here is only to save space from duplicates.
617 // SendMessages will filter it again for knowns that were added
618 // after addresses were pushed.
619 if (addr.IsValid() && !setAddrKnown.count(addr))
620 vAddrToSend.push_back(addr);
624 void AddInventoryKnown(const CInv& inv)
626 CRITICAL_BLOCK(cs_inventory)
627 setInventoryKnown.insert(inv);
630 void PushInventory(const CInv& inv)
632 CRITICAL_BLOCK(cs_inventory)
633 if (!setInventoryKnown.count(inv))
634 vInventoryToSend.push_back(inv);
637 void AskFor(const CInv& inv)
639 // We're using mapAskFor as a priority queue,
640 // the key is the earliest time the request can be sent
641 int64& nRequestTime = mapAlreadyAskedFor[inv];
642 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
644 // Make sure not to reuse time indexes to keep things in the same order
645 int64 nNow = (GetTime() - 1) * 1000000;
646 static int64 nLastTime;
647 nLastTime = nNow = std::max(nNow, ++nLastTime);
649 // Each retry is 2 minutes after the last
650 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
651 mapAskFor.insert(std::make_pair(nRequestTime, inv));
656 void BeginMessage(const char* pszCommand)
659 if (nHeaderStart != -1)
661 nHeaderStart = vSend.size();
662 vSend << CMessageHeader(pszCommand, 0);
663 nMessageStart = vSend.size();
665 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
666 printf("sending: %s ", pszCommand);
671 if (nHeaderStart == -1)
673 vSend.resize(nHeaderStart);
677 printf("(aborted)\n");
682 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
684 printf("dropmessages DROPPING SEND MESSAGE\n");
689 if (nHeaderStart == -1)
693 unsigned int nSize = vSend.size() - nMessageStart;
694 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
697 if (vSend.GetVersion() >= 209)
699 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
700 unsigned int nChecksum = 0;
701 memcpy(&nChecksum, &hash, sizeof(nChecksum));
702 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
703 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
706 printf("(%d bytes) ", nSize);
714 void EndMessageAbortIfEmpty()
716 if (nHeaderStart == -1)
718 int nSize = vSend.size() - nMessageStart;
729 /// when NTP implemented, change to just nTime = GetAdjustedTime()
730 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
731 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
732 CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
733 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
734 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
735 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
741 void PushMessage(const char* pszCommand)
745 BeginMessage(pszCommand);
755 template<typename T1>
756 void PushMessage(const char* pszCommand, const T1& a1)
760 BeginMessage(pszCommand);
771 template<typename T1, typename T2>
772 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
776 BeginMessage(pszCommand);
787 template<typename T1, typename T2, typename T3>
788 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
792 BeginMessage(pszCommand);
793 vSend << a1 << a2 << a3;
803 template<typename T1, typename T2, typename T3, typename T4>
804 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
808 BeginMessage(pszCommand);
809 vSend << a1 << a2 << a3 << a4;
819 template<typename T1, typename T2, typename T3, typename T4, typename T5>
820 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
824 BeginMessage(pszCommand);
825 vSend << a1 << a2 << a3 << a4 << a5;
835 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
836 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
840 BeginMessage(pszCommand);
841 vSend << a1 << a2 << a3 << a4 << a5 << a6;
851 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
852 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)
856 BeginMessage(pszCommand);
857 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
867 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
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, const T8& a8)
872 BeginMessage(pszCommand);
873 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
883 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
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, const T9& a9)
888 BeginMessage(pszCommand);
889 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
900 void PushRequest(const char* pszCommand,
901 void (*fn)(void*, CDataStream&), void* param1)
904 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
906 CRITICAL_BLOCK(cs_mapRequests)
907 mapRequests[hashReply] = CRequestTracker(fn, param1);
909 PushMessage(pszCommand, hashReply);
912 template<typename T1>
913 void PushRequest(const char* pszCommand, const T1& a1,
914 void (*fn)(void*, CDataStream&), void* param1)
917 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
919 CRITICAL_BLOCK(cs_mapRequests)
920 mapRequests[hashReply] = CRequestTracker(fn, param1);
922 PushMessage(pszCommand, hashReply, a1);
925 template<typename T1, typename T2>
926 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
927 void (*fn)(void*, CDataStream&), void* param1)
930 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
932 CRITICAL_BLOCK(cs_mapRequests)
933 mapRequests[hashReply] = CRequestTracker(fn, param1);
935 PushMessage(pszCommand, hashReply, a1, a2);
940 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
941 bool IsSubscribed(unsigned int nChannel);
942 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
943 void CancelSubscribe(unsigned int nChannel);
944 void CloseSocketDisconnect();
957 inline void RelayInventory(const CInv& inv)
959 // Put on lists to offer to the other nodes
960 CRITICAL_BLOCK(cs_vNodes)
961 BOOST_FOREACH(CNode* pnode, vNodes)
962 pnode->PushInventory(inv);
966 void RelayMessage(const CInv& inv, const T& a)
968 CDataStream ss(SER_NETWORK);
971 RelayMessage(inv, ss);
975 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
977 CRITICAL_BLOCK(cs_mapRelay)
979 // Expire old relay messages
980 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
982 mapRelay.erase(vRelayExpiration.front().second);
983 vRelayExpiration.pop_front();
986 // Save original serialized message so newer versions are preserved
988 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
1002 // Templates for the publish and subscription system.
1003 // The object being published as T& obj needs to have:
1004 // a set<unsigned int> setSources member
1005 // specializations of AdvertInsert and AdvertErase
1006 // Currently implemented for CTable and CProduct.
1009 template<typename T>
1010 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1013 obj.setSources.insert(pfrom->addr.ip);
1015 if (!AdvertInsert(obj))
1019 CRITICAL_BLOCK(cs_vNodes)
1020 BOOST_FOREACH(CNode* pnode, vNodes)
1021 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1022 pnode->PushMessage("publish", nChannel, nHops, obj);
1025 template<typename T>
1026 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1028 uint256 hash = obj.GetHash();
1030 CRITICAL_BLOCK(cs_vNodes)
1031 BOOST_FOREACH(CNode* pnode, vNodes)
1032 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
1033 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
1038 template<typename T>
1039 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
1042 obj.setSources.erase(pfrom->addr.ip);
1044 // If no longer supported by any sources, cancel it
1045 if (obj.setSources.empty())
1046 AdvertStopPublish(pfrom, nChannel, nHops, obj);