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"
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>
41 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
42 static const int PING_INTERVAL = 2 * 60;
43 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
44 static const int TIMEOUT_INTERVAL = 20 * 60;
45 /** The maximum number of entries in an 'inv' protocol message */
46 static const unsigned int MAX_INV_SZ = 50000;
47 /** -listen default */
48 static const bool DEFAULT_LISTEN = true;
51 static const bool DEFAULT_UPNP = USE_UPNP;
53 static const bool DEFAULT_UPNP = false;
55 /** The maximum number of entries in mapAskFor */
56 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
58 unsigned int ReceiveFloodSize();
59 unsigned int SendBufferSize();
61 void AddOneShot(std::string strDest);
62 bool RecvLine(SOCKET hSocket, std::string& strLine);
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_MANUAL, // address explicitly specified (-externalip=)
103 bool IsPeerAddrLocalGood(CNode *pnode);
104 void AdvertizeLocal(CNode *pnode);
105 void SetLimited(enum Network net, bool fLimited = true);
106 bool IsLimited(enum Network net);
107 bool IsLimited(const CNetAddr& addr);
108 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
109 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
110 bool SeenLocal(const CService& addr);
111 bool IsLocal(const CService& addr);
112 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
113 bool IsReachable(enum Network net);
114 bool IsReachable(const CNetAddr &addr);
115 void SetReachable(enum Network net, bool fFlag = true);
116 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
119 extern bool fDiscover;
121 extern uint64_t nLocalServices;
122 extern uint64_t nLocalHostNonce;
123 extern CAddrMan addrman;
124 extern int nMaxConnections;
126 extern std::vector<CNode*> vNodes;
127 extern CCriticalSection cs_vNodes;
128 extern std::map<CInv, CDataStream> mapRelay;
129 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
130 extern CCriticalSection cs_mapRelay;
131 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
133 extern std::vector<std::string> vAddedNodes;
134 extern CCriticalSection cs_vAddedNodes;
136 extern NodeId nLastNodeId;
137 extern CCriticalSection cs_nLastNodeId;
139 struct LocalServiceInfo {
144 extern CCriticalSection cs_mapLocalHost;
145 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
154 int64_t nTimeConnected;
155 std::string addrName;
157 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;
282 std::vector<CAddress> vAddrToSend;
283 mruset<CAddress> setAddrKnown;
285 std::set<uint256> setKnown;
287 // inventory based relay
288 mruset<CInv> setInventoryKnown;
289 std::vector<CInv> vInventoryToSend;
290 CCriticalSection cs_inventory;
291 std::multimap<int64_t, CInv> mapAskFor;
293 // Ping time measurement:
294 // The pong reply we're expecting, or 0 if no pong expected.
295 uint64_t nPingNonceSent;
296 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
297 int64_t nPingUsecStart;
298 // Last measured round-trip time.
299 int64_t nPingUsecTime;
300 // Whether a ping is requested.
303 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false);
307 // Network usage totals
308 static CCriticalSection cs_totalBytesRecv;
309 static CCriticalSection cs_totalBytesSent;
310 static uint64_t nTotalBytesRecv;
311 static uint64_t nTotalBytesSent;
314 void operator=(const CNode&);
318 NodeId GetId() const {
324 assert(nRefCount >= 0);
328 // requires LOCK(cs_vRecvMsg)
329 unsigned int GetTotalRecvSize()
331 unsigned int total = 0;
332 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
333 total += msg.vRecv.size() + 24;
337 // requires LOCK(cs_vRecvMsg)
338 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
340 // requires LOCK(cs_vRecvMsg)
341 void SetRecvVersion(int nVersionIn)
343 nRecvVersion = nVersionIn;
344 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
345 msg.SetVersion(nVersionIn);
361 void AddAddressKnown(const CAddress& addr)
363 setAddrKnown.insert(addr);
366 void PushAddress(const CAddress& addr)
368 // Known checking here is only to save space from duplicates.
369 // SendMessages will filter it again for knowns that were added
370 // after addresses were pushed.
371 if (addr.IsValid() && !setAddrKnown.count(addr))
372 vAddrToSend.push_back(addr);
376 void AddInventoryKnown(const CInv& inv)
380 setInventoryKnown.insert(inv);
384 void PushInventory(const CInv& inv)
388 if (!setInventoryKnown.count(inv))
389 vInventoryToSend.push_back(inv);
393 void AskFor(const CInv& inv);
395 // TODO: Document the postcondition of this function. Is cs_vSend locked?
396 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
398 // TODO: Document the precondition of this function. Is cs_vSend locked?
399 void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
401 // TODO: Document the precondition of this function. Is cs_vSend locked?
402 void EndMessage() UNLOCK_FUNCTION(cs_vSend);
407 void PushMessage(const char* pszCommand)
411 BeginMessage(pszCommand);
421 template<typename T1>
422 void PushMessage(const char* pszCommand, const T1& a1)
426 BeginMessage(pszCommand);
437 template<typename T1, typename T2>
438 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
442 BeginMessage(pszCommand);
453 template<typename T1, typename T2, typename T3>
454 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
458 BeginMessage(pszCommand);
459 ssSend << a1 << a2 << a3;
469 template<typename T1, typename T2, typename T3, typename T4>
470 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
474 BeginMessage(pszCommand);
475 ssSend << a1 << a2 << a3 << a4;
485 template<typename T1, typename T2, typename T3, typename T4, typename T5>
486 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
490 BeginMessage(pszCommand);
491 ssSend << a1 << a2 << a3 << a4 << a5;
501 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
502 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
506 BeginMessage(pszCommand);
507 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
517 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
518 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)
522 BeginMessage(pszCommand);
523 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
533 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
534 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)
538 BeginMessage(pszCommand);
539 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
549 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
550 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)
554 BeginMessage(pszCommand);
555 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
565 bool IsSubscribed(unsigned int nChannel);
566 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
567 void CancelSubscribe(unsigned int nChannel);
568 void CloseSocketDisconnect();
570 // Denial-of-service detection/prevention
571 // The idea is to detect peers that are behaving
572 // badly and disconnect/ban them, but do it in a
573 // one-coding-mistake-won't-shatter-the-entire-network
575 // IMPORTANT: There should be nothing I can give a
576 // node that it will forward on that will make that
577 // node's peers drop it. If there is, an attacker
578 // can isolate a node and/or try to split the network.
579 // Dropping a node for sending stuff that is invalid
580 // now but might be valid in a later version is also
581 // dangerous, because it can cause a network split
582 // between nodes running old code and nodes running
584 static void ClearBanned(); // needed for unit testing
585 static bool IsBanned(CNetAddr ip);
586 static bool Ban(const CNetAddr &ip);
587 void copyStats(CNodeStats &stats);
589 static bool IsWhitelistedRange(const CNetAddr &ip);
590 static void AddWhitelistedRange(const CSubNet &subnet);
593 static void RecordBytesRecv(uint64_t bytes);
594 static void RecordBytesSent(uint64_t bytes);
596 static uint64_t GetTotalBytesRecv();
597 static uint64_t GetTotalBytesSent();
603 void RelayTransaction(const CTransaction& tx);
604 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
606 /** Access to the (IP) address database (peers.dat) */
610 boost::filesystem::path pathAddr;
613 bool Write(const CAddrMan& addr);
614 bool Read(CAddrMan& addr);
617 #endif // BITCOIN_NET_H