1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
12 #include "limitedmap.h"
20 #include "utilstrencodings.h"
26 #include <arpa/inet.h>
29 #include <boost/filesystem/path.hpp>
30 #include <boost/foreach.hpp>
31 #include <boost/signals2/signal.hpp>
42 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
43 static const int PING_INTERVAL = 2 * 60;
44 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
45 static const int TIMEOUT_INTERVAL = 20 * 60;
46 /** The maximum number of entries in an 'inv' protocol message */
47 static const unsigned int MAX_INV_SZ = 50000;
48 /** The maximum number of new addresses to accumulate before announcing. */
49 static const unsigned int MAX_ADDR_TO_SEND = 1000;
50 /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */
51 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024;
52 /** -listen default */
53 static const bool DEFAULT_LISTEN = true;
56 static const bool DEFAULT_UPNP = USE_UPNP;
58 static const bool DEFAULT_UPNP = false;
60 /** The maximum number of entries in mapAskFor */
61 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
62 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
63 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
65 unsigned int ReceiveFloodSize();
66 unsigned int SendBufferSize();
68 void AddOneShot(std::string strDest);
69 void AddressCurrentlyConnected(const CService& addr);
70 CNode* FindNode(const CNetAddr& ip);
71 CNode* FindNode(const CSubNet& subNet);
72 CNode* FindNode(const std::string& addrName);
73 CNode* FindNode(const CService& ip);
74 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
75 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
76 void MapPort(bool fUseUPnP);
77 unsigned short GetListenPort();
78 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
79 void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler);
81 void SocketSendData(CNode *pnode);
87 typedef bool result_type;
90 bool operator()(I first, I last) const
92 while (first != last) {
93 if (!(*first)) return false;
100 // Signals for message handling
103 boost::signals2::signal<int ()> GetHeight;
104 boost::signals2::signal<bool (CNode*), CombinerAll> ProcessMessages;
105 boost::signals2::signal<bool (CNode*, bool), CombinerAll> SendMessages;
106 boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
107 boost::signals2::signal<void (NodeId)> FinalizeNode;
111 CNodeSignals& GetNodeSignals();
116 LOCAL_NONE, // unknown
117 LOCAL_IF, // address a local interface listens on
118 LOCAL_BIND, // address explicit bound to
119 LOCAL_UPNP, // address reported by UPnP
120 LOCAL_MANUAL, // address explicitly specified (-externalip=)
125 bool IsPeerAddrLocalGood(CNode *pnode);
126 void AdvertizeLocal(CNode *pnode);
127 void SetLimited(enum Network net, bool fLimited = true);
128 bool IsLimited(enum Network net);
129 bool IsLimited(const CNetAddr& addr);
130 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
131 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
132 bool SeenLocal(const CService& addr);
133 bool IsLocal(const CService& addr);
134 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
135 bool IsReachable(enum Network net);
136 bool IsReachable(const CNetAddr &addr);
137 void SetReachable(enum Network net, bool fFlag = true);
138 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
141 extern bool fDiscover;
143 extern uint64_t nLocalServices;
144 extern uint64_t nLocalHostNonce;
145 extern CAddrMan addrman;
146 /** Maximum number of connections to simultaneously allow (aka connection slots) */
147 extern int nMaxConnections;
149 extern std::vector<CNode*> vNodes;
150 extern CCriticalSection cs_vNodes;
151 extern std::map<CInv, CDataStream> mapRelay;
152 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
153 extern CCriticalSection cs_mapRelay;
154 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
156 extern std::vector<std::string> vAddedNodes;
157 extern CCriticalSection cs_vAddedNodes;
159 extern NodeId nLastNodeId;
160 extern CCriticalSection cs_nLastNodeId;
162 struct LocalServiceInfo {
167 extern CCriticalSection cs_mapLocalHost;
168 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
177 int64_t nTimeConnected;
179 std::string addrName;
181 std::string cleanSubVer;
189 std::string addrLocal;
197 bool in_data; // parsing header (false) or data (true)
199 CDataStream hdrbuf; // partially received header
200 CMessageHeader hdr; // complete header
201 unsigned int nHdrPos;
203 CDataStream vRecv; // received message data
204 unsigned int nDataPos;
206 int64_t nTime; // time (in microseconds) of message receipt.
208 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
216 bool complete() const
220 return (hdr.nMessageSize == nDataPos);
223 void SetVersion(int nVersionIn)
225 hdrbuf.SetVersion(nVersionIn);
226 vRecv.SetVersion(nVersionIn);
229 int readHeader(const char *pch, unsigned int nBytes);
230 int readData(const char *pch, unsigned int nBytes);
237 /** Information about a peer */
245 size_t nSendSize; // total size of all vSendMsg entries
246 size_t nSendOffset; // offset inside the first vSendMsg already sent
248 std::deque<CSerializeData> vSendMsg;
249 CCriticalSection cs_vSend;
251 std::deque<CInv> vRecvGetData;
252 std::deque<CNetMessage> vRecvMsg;
253 CCriticalSection cs_vRecvMsg;
259 int64_t nTimeConnected;
262 std::string addrName;
265 // strSubVer is whatever byte array we read from the wire. However, this field is intended
266 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
267 // store the sanitized version in cleanSubVer. The original should be used when dealing with
268 // the network or wire types and the cleaned string used when displayed or logged.
269 std::string strSubVer, cleanSubVer;
270 bool fWhitelisted; // This peer can bypass DoS banning.
275 bool fSuccessfullyConnected;
277 // We use fRelayTxes for two purposes -
278 // a) it allows us to not relay tx invs before receiving the peer's version message
279 // b) the peer may tell us in its version message that we should not relay tx invs
280 // until it has initialized its bloom filter.
283 CSemaphoreGrant grantOutbound;
284 CCriticalSection cs_filter;
285 CBloomFilter* pfilter;
290 // Denial-of-service detection/prevention
291 // Key is IP address, value is banned-until-time
292 static std::map<CSubNet, int64_t> setBanned;
293 static CCriticalSection cs_setBanned;
295 // Whitelisted ranges. Any node connecting from these is automatically
296 // whitelisted (as well as those connecting to whitelisted binds).
297 static std::vector<CSubNet> vWhitelistedRange;
298 static CCriticalSection cs_vWhitelistedRange;
300 // Basic fuzz-testing
301 void Fuzz(int nChance); // modifies ssSend
304 uint256 hashContinue;
308 std::vector<CAddress> vAddrToSend;
309 CRollingBloomFilter addrKnown;
311 std::set<uint256> setKnown;
313 // inventory based relay
314 mruset<CInv> setInventoryKnown;
315 std::vector<CInv> vInventoryToSend;
316 CCriticalSection cs_inventory;
317 std::set<uint256> setAskFor;
318 std::multimap<int64_t, CInv> mapAskFor;
320 // Ping time measurement:
321 // The pong reply we're expecting, or 0 if no pong expected.
322 uint64_t nPingNonceSent;
323 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
324 int64_t nPingUsecStart;
325 // Last measured round-trip time.
326 int64_t nPingUsecTime;
327 // Best measured round-trip time.
328 int64_t nMinPingUsecTime;
329 // Whether a ping is requested.
332 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false);
336 // Network usage totals
337 static CCriticalSection cs_totalBytesRecv;
338 static CCriticalSection cs_totalBytesSent;
339 static uint64_t nTotalBytesRecv;
340 static uint64_t nTotalBytesSent;
343 void operator=(const CNode&);
347 NodeId GetId() const {
353 assert(nRefCount >= 0);
357 // requires LOCK(cs_vRecvMsg)
358 unsigned int GetTotalRecvSize()
360 unsigned int total = 0;
361 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
362 total += msg.vRecv.size() + 24;
366 // requires LOCK(cs_vRecvMsg)
367 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
369 // requires LOCK(cs_vRecvMsg)
370 void SetRecvVersion(int nVersionIn)
372 nRecvVersion = nVersionIn;
373 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
374 msg.SetVersion(nVersionIn);
390 void AddAddressKnown(const CAddress& addr)
392 addrKnown.insert(addr.GetKey());
395 void PushAddress(const CAddress& addr)
397 // Known checking here is only to save space from duplicates.
398 // SendMessages will filter it again for knowns that were added
399 // after addresses were pushed.
400 if (addr.IsValid() && !addrKnown.contains(addr.GetKey())) {
401 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
402 vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr;
404 vAddrToSend.push_back(addr);
410 void AddInventoryKnown(const CInv& inv)
414 setInventoryKnown.insert(inv);
418 void PushInventory(const CInv& inv)
422 if (!setInventoryKnown.count(inv))
423 vInventoryToSend.push_back(inv);
427 void AskFor(const CInv& inv);
429 // TODO: Document the postcondition of this function. Is cs_vSend locked?
430 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
432 // TODO: Document the precondition of this function. Is cs_vSend locked?
433 void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
435 // TODO: Document the precondition of this function. Is cs_vSend locked?
436 void EndMessage() UNLOCK_FUNCTION(cs_vSend);
441 void PushMessage(const char* pszCommand)
445 BeginMessage(pszCommand);
455 template<typename T1>
456 void PushMessage(const char* pszCommand, const T1& a1)
460 BeginMessage(pszCommand);
471 template<typename T1, typename T2>
472 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
476 BeginMessage(pszCommand);
487 template<typename T1, typename T2, typename T3>
488 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
492 BeginMessage(pszCommand);
493 ssSend << a1 << a2 << a3;
503 template<typename T1, typename T2, typename T3, typename T4>
504 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
508 BeginMessage(pszCommand);
509 ssSend << a1 << a2 << a3 << a4;
519 template<typename T1, typename T2, typename T3, typename T4, typename T5>
520 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
524 BeginMessage(pszCommand);
525 ssSend << a1 << a2 << a3 << a4 << a5;
535 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
536 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
540 BeginMessage(pszCommand);
541 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
551 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
552 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)
556 BeginMessage(pszCommand);
557 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
567 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
568 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)
572 BeginMessage(pszCommand);
573 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
583 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
584 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)
588 BeginMessage(pszCommand);
589 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
599 void CloseSocketDisconnect();
601 // Denial-of-service detection/prevention
602 // The idea is to detect peers that are behaving
603 // badly and disconnect/ban them, but do it in a
604 // one-coding-mistake-won't-shatter-the-entire-network
606 // IMPORTANT: There should be nothing I can give a
607 // node that it will forward on that will make that
608 // node's peers drop it. If there is, an attacker
609 // can isolate a node and/or try to split the network.
610 // Dropping a node for sending stuff that is invalid
611 // now but might be valid in a later version is also
612 // dangerous, because it can cause a network split
613 // between nodes running old code and nodes running
615 static void ClearBanned(); // needed for unit testing
616 static bool IsBanned(CNetAddr ip);
617 static bool IsBanned(CSubNet subnet);
618 static void Ban(const CNetAddr &ip, int64_t bantimeoffset = 0);
619 static void Ban(const CSubNet &subNet, int64_t bantimeoffset = 0);
620 static bool Unban(const CNetAddr &ip);
621 static bool Unban(const CSubNet &ip);
622 static void GetBanned(std::map<CSubNet, int64_t> &banmap);
624 void copyStats(CNodeStats &stats);
626 static bool IsWhitelistedRange(const CNetAddr &ip);
627 static void AddWhitelistedRange(const CSubNet &subnet);
630 static void RecordBytesRecv(uint64_t bytes);
631 static void RecordBytesSent(uint64_t bytes);
633 static uint64_t GetTotalBytesRecv();
634 static uint64_t GetTotalBytesSent();
640 void RelayTransaction(const CTransaction& tx);
641 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
643 /** Access to the (IP) address database (peers.dat) */
647 boost::filesystem::path pathAddr;
650 bool Write(const CAddrMan& addr);
651 bool Read(CAddrMan& addr);
654 #endif // BITCOIN_NET_H