1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2014 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
12 #include "limitedmap.h"
19 #include "utilstrencodings.h"
25 #include <arpa/inet.h>
28 #include <boost/filesystem/path.hpp>
29 #include <boost/foreach.hpp>
30 #include <boost/signals2/signal.hpp>
40 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
41 static const int PING_INTERVAL = 2 * 60;
42 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
43 static const int TIMEOUT_INTERVAL = 20 * 60;
44 /** The maximum number of entries in an 'inv' protocol message */
45 static const unsigned int MAX_INV_SZ = 50000;
46 /** -listen default */
47 static const bool DEFAULT_LISTEN = true;
50 static const bool DEFAULT_UPNP = USE_UPNP;
52 static const bool DEFAULT_UPNP = false;
54 /** The maximum number of entries in mapAskFor */
55 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
57 unsigned int ReceiveFloodSize();
58 unsigned int SendBufferSize();
60 void AddOneShot(std::string strDest);
61 bool RecvLine(SOCKET hSocket, std::string& strLine);
62 bool GetMyExternalIP(CNetAddr& ipRet);
63 void AddressCurrentlyConnected(const CService& addr);
64 CNode* FindNode(const CNetAddr& ip);
65 CNode* FindNode(const std::string& addrName);
66 CNode* FindNode(const CService& ip);
67 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
68 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
69 void MapPort(bool fUseUPnP);
70 unsigned short GetListenPort();
71 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
72 void StartNode(boost::thread_group& threadGroup);
74 void SocketSendData(CNode *pnode);
78 // Signals for message handling
81 boost::signals2::signal<int ()> GetHeight;
82 boost::signals2::signal<bool (CNode*)> ProcessMessages;
83 boost::signals2::signal<bool (CNode*, bool)> SendMessages;
84 boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
85 boost::signals2::signal<void (NodeId)> FinalizeNode;
89 CNodeSignals& GetNodeSignals();
94 LOCAL_NONE, // unknown
95 LOCAL_IF, // address a local interface listens on
96 LOCAL_BIND, // address explicit bound to
97 LOCAL_UPNP, // address reported by UPnP
98 LOCAL_HTTP, // address reported by whatismyip.com and similar
99 LOCAL_MANUAL, // address explicitly specified (-externalip=)
104 void SetLimited(enum Network net, bool fLimited = true);
105 bool IsLimited(enum Network net);
106 bool IsLimited(const CNetAddr& addr);
107 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
108 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
109 bool SeenLocal(const CService& addr);
110 bool IsLocal(const CService& addr);
111 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
112 bool IsReachable(enum Network net);
113 bool IsReachable(const CNetAddr &addr);
114 void SetReachable(enum Network net, bool fFlag = true);
115 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
118 extern bool fDiscover;
120 extern uint64_t nLocalServices;
121 extern uint64_t nLocalHostNonce;
122 extern CAddrMan addrman;
123 extern int nMaxConnections;
125 extern std::vector<CNode*> vNodes;
126 extern CCriticalSection cs_vNodes;
127 extern std::map<CInv, CDataStream> mapRelay;
128 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
129 extern CCriticalSection cs_mapRelay;
130 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
132 extern std::vector<std::string> vAddedNodes;
133 extern CCriticalSection cs_vAddedNodes;
135 extern NodeId nLastNodeId;
136 extern CCriticalSection cs_nLastNodeId;
138 struct LocalServiceInfo {
143 extern CCriticalSection cs_mapLocalHost;
144 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
153 int64_t nTimeConnected;
154 std::string addrName;
156 std::string cleanSubVer;
165 std::string addrLocal;
173 bool in_data; // parsing header (false) or data (true)
175 CDataStream hdrbuf; // partially received header
176 CMessageHeader hdr; // complete header
177 unsigned int nHdrPos;
179 CDataStream vRecv; // received message data
180 unsigned int nDataPos;
182 int64_t nTime; // time (in microseconds) of message receipt.
184 CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
192 bool complete() const
196 return (hdr.nMessageSize == nDataPos);
199 void SetVersion(int nVersionIn)
201 hdrbuf.SetVersion(nVersionIn);
202 vRecv.SetVersion(nVersionIn);
205 int readHeader(const char *pch, unsigned int nBytes);
206 int readData(const char *pch, unsigned int nBytes);
213 /** Information about a peer */
221 size_t nSendSize; // total size of all vSendMsg entries
222 size_t nSendOffset; // offset inside the first vSendMsg already sent
224 std::deque<CSerializeData> vSendMsg;
225 CCriticalSection cs_vSend;
227 std::deque<CInv> vRecvGetData;
228 std::deque<CNetMessage> vRecvMsg;
229 CCriticalSection cs_vRecvMsg;
235 int64_t nTimeConnected;
237 std::string addrName;
240 // strSubVer is whatever byte array we read from the wire. However, this field is intended
241 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
242 // store the sanitized version in cleanSubVer. The original should be used when dealing with
243 // the network or wire types and the cleaned string used when displayed or logged.
244 std::string strSubVer, cleanSubVer;
245 bool fWhitelisted; // This peer can bypass DoS banning.
250 bool fSuccessfullyConnected;
252 // We use fRelayTxes for two purposes -
253 // a) it allows us to not relay tx invs before receiving the peer's version message
254 // b) the peer may tell us in their version message that we should not relay tx invs
255 // until they have initialized their bloom filter.
257 CSemaphoreGrant grantOutbound;
258 CCriticalSection cs_filter;
259 CBloomFilter* pfilter;
264 // Denial-of-service detection/prevention
265 // Key is IP address, value is banned-until-time
266 static std::map<CNetAddr, int64_t> setBanned;
267 static CCriticalSection cs_setBanned;
269 // Whitelisted ranges. Any node connecting from these is automatically
270 // whitelisted (as well as those connecting to whitelisted binds).
271 static std::vector<CSubNet> vWhitelistedRange;
272 static CCriticalSection cs_vWhitelistedRange;
274 // Basic fuzz-testing
275 void Fuzz(int nChance); // modifies ssSend
278 uint256 hashContinue;
279 CBlockIndex* pindexLastGetBlocksBegin;
280 uint256 hashLastGetBlocksEnd;
285 std::vector<CAddress> vAddrToSend;
286 mruset<CAddress> setAddrKnown;
288 std::set<uint256> setKnown;
290 // inventory based relay
291 mruset<CInv> setInventoryKnown;
292 std::vector<CInv> vInventoryToSend;
293 CCriticalSection cs_inventory;
294 std::multimap<int64_t, CInv> mapAskFor;
296 // Ping time measurement:
297 // The pong reply we're expecting, or 0 if no pong expected.
298 uint64_t nPingNonceSent;
299 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
300 int64_t nPingUsecStart;
301 // Last measured round-trip time.
302 int64_t nPingUsecTime;
303 // Whether a ping is requested.
306 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false);
310 // Network usage totals
311 static CCriticalSection cs_totalBytesRecv;
312 static CCriticalSection cs_totalBytesSent;
313 static uint64_t nTotalBytesRecv;
314 static uint64_t nTotalBytesSent;
317 void operator=(const CNode&);
321 NodeId GetId() const {
327 assert(nRefCount >= 0);
331 // requires LOCK(cs_vRecvMsg)
332 unsigned int GetTotalRecvSize()
334 unsigned int total = 0;
335 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
336 total += msg.vRecv.size() + 24;
340 // requires LOCK(cs_vRecvMsg)
341 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
343 // requires LOCK(cs_vRecvMsg)
344 void SetRecvVersion(int nVersionIn)
346 nRecvVersion = nVersionIn;
347 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
348 msg.SetVersion(nVersionIn);
364 void AddAddressKnown(const CAddress& addr)
366 setAddrKnown.insert(addr);
369 void PushAddress(const CAddress& addr)
371 // Known checking here is only to save space from duplicates.
372 // SendMessages will filter it again for knowns that were added
373 // after addresses were pushed.
374 if (addr.IsValid() && !setAddrKnown.count(addr))
375 vAddrToSend.push_back(addr);
379 void AddInventoryKnown(const CInv& inv)
383 setInventoryKnown.insert(inv);
387 void PushInventory(const CInv& inv)
391 if (!setInventoryKnown.count(inv))
392 vInventoryToSend.push_back(inv);
396 void AskFor(const CInv& inv);
398 // TODO: Document the postcondition of this function. Is cs_vSend locked?
399 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
401 // TODO: Document the precondition of this function. Is cs_vSend locked?
402 void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
404 // TODO: Document the precondition of this function. Is cs_vSend locked?
405 void EndMessage() UNLOCK_FUNCTION(cs_vSend);
410 void PushMessage(const char* pszCommand)
414 BeginMessage(pszCommand);
424 template<typename T1>
425 void PushMessage(const char* pszCommand, const T1& a1)
429 BeginMessage(pszCommand);
440 template<typename T1, typename T2>
441 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
445 BeginMessage(pszCommand);
456 template<typename T1, typename T2, typename T3>
457 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
461 BeginMessage(pszCommand);
462 ssSend << a1 << a2 << a3;
472 template<typename T1, typename T2, typename T3, typename T4>
473 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
477 BeginMessage(pszCommand);
478 ssSend << a1 << a2 << a3 << a4;
488 template<typename T1, typename T2, typename T3, typename T4, typename T5>
489 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
493 BeginMessage(pszCommand);
494 ssSend << a1 << a2 << a3 << a4 << a5;
504 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
505 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
509 BeginMessage(pszCommand);
510 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
520 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
521 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)
525 BeginMessage(pszCommand);
526 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
536 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
537 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)
541 BeginMessage(pszCommand);
542 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
552 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
553 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)
557 BeginMessage(pszCommand);
558 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
568 bool IsSubscribed(unsigned int nChannel);
569 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
570 void CancelSubscribe(unsigned int nChannel);
571 void CloseSocketDisconnect();
573 // Denial-of-service detection/prevention
574 // The idea is to detect peers that are behaving
575 // badly and disconnect/ban them, but do it in a
576 // one-coding-mistake-won't-shatter-the-entire-network
578 // IMPORTANT: There should be nothing I can give a
579 // node that it will forward on that will make that
580 // node's peers drop it. If there is, an attacker
581 // can isolate a node and/or try to split the network.
582 // Dropping a node for sending stuff that is invalid
583 // now but might be valid in a later version is also
584 // dangerous, because it can cause a network split
585 // between nodes running old code and nodes running
587 static void ClearBanned(); // needed for unit testing
588 static bool IsBanned(CNetAddr ip);
589 static bool Ban(const CNetAddr &ip);
590 void copyStats(CNodeStats &stats);
592 static bool IsWhitelistedRange(const CNetAddr &ip);
593 static void AddWhitelistedRange(const CSubNet &subnet);
596 static void RecordBytesRecv(uint64_t bytes);
597 static void RecordBytesSent(uint64_t bytes);
599 static uint64_t GetTotalBytesRecv();
600 static uint64_t GetTotalBytesSent();
606 void RelayTransaction(const CTransaction& tx);
607 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
609 /** Access to the (IP) address database (peers.dat) */
613 boost::filesystem::path pathAddr;
616 bool Write(const CAddrMan& addr);
617 bool Read(CAddrMan& addr);
620 #endif // BITCOIN_NET_H