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;
164 std::string addrLocal;
172 bool in_data; // parsing header (false) or data (true)
174 CDataStream hdrbuf; // partially received header
175 CMessageHeader hdr; // complete header
176 unsigned int nHdrPos;
178 CDataStream vRecv; // received message data
179 unsigned int nDataPos;
181 int64_t nTime; // time (in microseconds) of message receipt.
183 CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
191 bool complete() const
195 return (hdr.nMessageSize == nDataPos);
198 void SetVersion(int nVersionIn)
200 hdrbuf.SetVersion(nVersionIn);
201 vRecv.SetVersion(nVersionIn);
204 int readHeader(const char *pch, unsigned int nBytes);
205 int readData(const char *pch, unsigned int nBytes);
212 /** Information about a peer */
220 size_t nSendSize; // total size of all vSendMsg entries
221 size_t nSendOffset; // offset inside the first vSendMsg already sent
223 std::deque<CSerializeData> vSendMsg;
224 CCriticalSection cs_vSend;
226 std::deque<CInv> vRecvGetData;
227 std::deque<CNetMessage> vRecvMsg;
228 CCriticalSection cs_vRecvMsg;
234 int64_t nTimeConnected;
236 std::string addrName;
239 // strSubVer is whatever byte array we read from the wire. However, this field is intended
240 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
241 // store the sanitized version in cleanSubVer. The original should be used when dealing with
242 // the network or wire types and the cleaned string used when displayed or logged.
243 std::string strSubVer, cleanSubVer;
244 bool fWhitelisted; // This peer can bypass DoS banning.
249 bool fSuccessfullyConnected;
251 // We use fRelayTxes for two purposes -
252 // a) it allows us to not relay tx invs before receiving the peer's version message
253 // b) the peer may tell us in their version message that we should not relay tx invs
254 // until they have initialized their bloom filter.
256 CSemaphoreGrant grantOutbound;
257 CCriticalSection cs_filter;
258 CBloomFilter* pfilter;
263 // Denial-of-service detection/prevention
264 // Key is IP address, value is banned-until-time
265 static std::map<CNetAddr, int64_t> setBanned;
266 static CCriticalSection cs_setBanned;
268 // Whitelisted ranges. Any node connecting from these is automatically
269 // whitelisted (as well as those connecting to whitelisted binds).
270 static std::vector<CSubNet> vWhitelistedRange;
271 static CCriticalSection cs_vWhitelistedRange;
273 // Basic fuzz-testing
274 void Fuzz(int nChance); // modifies ssSend
277 uint256 hashContinue;
281 std::vector<CAddress> vAddrToSend;
282 mruset<CAddress> setAddrKnown;
284 std::set<uint256> setKnown;
286 // inventory based relay
287 mruset<CInv> setInventoryKnown;
288 std::vector<CInv> vInventoryToSend;
289 CCriticalSection cs_inventory;
290 std::multimap<int64_t, CInv> mapAskFor;
292 // Ping time measurement:
293 // The pong reply we're expecting, or 0 if no pong expected.
294 uint64_t nPingNonceSent;
295 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
296 int64_t nPingUsecStart;
297 // Last measured round-trip time.
298 int64_t nPingUsecTime;
299 // Whether a ping is requested.
302 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false);
306 // Network usage totals
307 static CCriticalSection cs_totalBytesRecv;
308 static CCriticalSection cs_totalBytesSent;
309 static uint64_t nTotalBytesRecv;
310 static uint64_t nTotalBytesSent;
313 void operator=(const CNode&);
317 NodeId GetId() const {
323 assert(nRefCount >= 0);
327 // requires LOCK(cs_vRecvMsg)
328 unsigned int GetTotalRecvSize()
330 unsigned int total = 0;
331 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
332 total += msg.vRecv.size() + 24;
336 // requires LOCK(cs_vRecvMsg)
337 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
339 // requires LOCK(cs_vRecvMsg)
340 void SetRecvVersion(int nVersionIn)
342 nRecvVersion = nVersionIn;
343 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
344 msg.SetVersion(nVersionIn);
360 void AddAddressKnown(const CAddress& addr)
362 setAddrKnown.insert(addr);
365 void PushAddress(const CAddress& addr)
367 // Known checking here is only to save space from duplicates.
368 // SendMessages will filter it again for knowns that were added
369 // after addresses were pushed.
370 if (addr.IsValid() && !setAddrKnown.count(addr))
371 vAddrToSend.push_back(addr);
375 void AddInventoryKnown(const CInv& inv)
379 setInventoryKnown.insert(inv);
383 void PushInventory(const CInv& inv)
387 if (!setInventoryKnown.count(inv))
388 vInventoryToSend.push_back(inv);
392 void AskFor(const CInv& inv);
394 // TODO: Document the postcondition of this function. Is cs_vSend locked?
395 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
397 // TODO: Document the precondition of this function. Is cs_vSend locked?
398 void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
400 // TODO: Document the precondition of this function. Is cs_vSend locked?
401 void EndMessage() UNLOCK_FUNCTION(cs_vSend);
406 void PushMessage(const char* pszCommand)
410 BeginMessage(pszCommand);
420 template<typename T1>
421 void PushMessage(const char* pszCommand, const T1& a1)
425 BeginMessage(pszCommand);
436 template<typename T1, typename T2>
437 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
441 BeginMessage(pszCommand);
452 template<typename T1, typename T2, typename T3>
453 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
457 BeginMessage(pszCommand);
458 ssSend << a1 << a2 << a3;
468 template<typename T1, typename T2, typename T3, typename T4>
469 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
473 BeginMessage(pszCommand);
474 ssSend << a1 << a2 << a3 << a4;
484 template<typename T1, typename T2, typename T3, typename T4, typename T5>
485 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
489 BeginMessage(pszCommand);
490 ssSend << a1 << a2 << a3 << a4 << a5;
500 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
501 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
505 BeginMessage(pszCommand);
506 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
516 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
517 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)
521 BeginMessage(pszCommand);
522 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
532 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
533 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)
537 BeginMessage(pszCommand);
538 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
548 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
549 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)
553 BeginMessage(pszCommand);
554 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
564 bool IsSubscribed(unsigned int nChannel);
565 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
566 void CancelSubscribe(unsigned int nChannel);
567 void CloseSocketDisconnect();
569 // Denial-of-service detection/prevention
570 // The idea is to detect peers that are behaving
571 // badly and disconnect/ban them, but do it in a
572 // one-coding-mistake-won't-shatter-the-entire-network
574 // IMPORTANT: There should be nothing I can give a
575 // node that it will forward on that will make that
576 // node's peers drop it. If there is, an attacker
577 // can isolate a node and/or try to split the network.
578 // Dropping a node for sending stuff that is invalid
579 // now but might be valid in a later version is also
580 // dangerous, because it can cause a network split
581 // between nodes running old code and nodes running
583 static void ClearBanned(); // needed for unit testing
584 static bool IsBanned(CNetAddr ip);
585 static bool Ban(const CNetAddr &ip);
586 void copyStats(CNodeStats &stats);
588 static bool IsWhitelistedRange(const CNetAddr &ip);
589 static void AddWhitelistedRange(const CSubNet &subnet);
592 static void RecordBytesRecv(uint64_t bytes);
593 static void RecordBytesSent(uint64_t bytes);
595 static uint64_t GetTotalBytesRecv();
596 static uint64_t GetTotalBytesSent();
602 void RelayTransaction(const CTransaction& tx);
603 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
605 /** Access to the (IP) address database (peers.dat) */
609 boost::filesystem::path pathAddr;
612 bool Write(const CAddrMan& addr);
613 bool Read(CAddrMan& addr);
616 #endif // BITCOIN_NET_H