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"
25 #include <arpa/inet.h>
28 #include <boost/foreach.hpp>
29 #include <boost/signals2/signal.hpp>
39 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
40 static const int PING_INTERVAL = 2 * 60;
41 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
42 static const int TIMEOUT_INTERVAL = 20 * 60;
43 /** The maximum number of entries in an 'inv' protocol message */
44 static const unsigned int MAX_INV_SZ = 50000;
45 /** -listen default */
46 static const bool DEFAULT_LISTEN = true;
49 static const bool DEFAULT_UPNP = USE_UPNP;
51 static const bool DEFAULT_UPNP = false;
54 unsigned int ReceiveFloodSize();
55 unsigned int SendBufferSize();
57 void AddOneShot(std::string strDest);
58 bool RecvLine(SOCKET hSocket, std::string& strLine);
59 bool GetMyExternalIP(CNetAddr& ipRet);
60 void AddressCurrentlyConnected(const CService& addr);
61 CNode* FindNode(const CNetAddr& ip);
62 CNode* FindNode(const std::string& addrName);
63 CNode* FindNode(const CService& ip);
64 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
65 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
66 void MapPort(bool fUseUPnP);
67 unsigned short GetListenPort();
68 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
69 void StartNode(boost::thread_group& threadGroup);
71 void SocketSendData(CNode *pnode);
75 // Signals for message handling
78 boost::signals2::signal<int ()> GetHeight;
79 boost::signals2::signal<bool (CNode*)> ProcessMessages;
80 boost::signals2::signal<bool (CNode*, bool)> SendMessages;
81 boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
82 boost::signals2::signal<void (NodeId)> FinalizeNode;
86 CNodeSignals& GetNodeSignals();
91 LOCAL_NONE, // unknown
92 LOCAL_IF, // address a local interface listens on
93 LOCAL_BIND, // address explicit bound to
94 LOCAL_UPNP, // address reported by UPnP
95 LOCAL_HTTP, // address reported by whatismyip.com and similar
96 LOCAL_MANUAL, // address explicitly specified (-externalip=)
101 void SetLimited(enum Network net, bool fLimited = true);
102 bool IsLimited(enum Network net);
103 bool IsLimited(const CNetAddr& addr);
104 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
105 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
106 bool SeenLocal(const CService& addr);
107 bool IsLocal(const CService& addr);
108 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
109 bool IsReachable(enum Network net);
110 bool IsReachable(const CNetAddr &addr);
111 void SetReachable(enum Network net, bool fFlag = true);
112 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
115 extern bool fDiscover;
117 extern uint64_t nLocalServices;
118 extern uint64_t nLocalHostNonce;
119 extern CAddrMan addrman;
120 extern int nMaxConnections;
122 extern std::vector<CNode*> vNodes;
123 extern CCriticalSection cs_vNodes;
124 extern std::map<CInv, CDataStream> mapRelay;
125 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
126 extern CCriticalSection cs_mapRelay;
127 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
129 extern std::vector<std::string> vAddedNodes;
130 extern CCriticalSection cs_vAddedNodes;
132 extern NodeId nLastNodeId;
133 extern CCriticalSection cs_nLastNodeId;
135 struct LocalServiceInfo {
140 extern CCriticalSection cs_mapLocalHost;
141 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
150 int64_t nTimeConnected;
151 std::string addrName;
153 std::string cleanSubVer;
162 std::string addrLocal;
170 bool in_data; // parsing header (false) or data (true)
172 CDataStream hdrbuf; // partially received header
173 CMessageHeader hdr; // complete header
174 unsigned int nHdrPos;
176 CDataStream vRecv; // received message data
177 unsigned int nDataPos;
179 int64_t nTime; // time (in microseconds) of message receipt.
181 CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
189 bool complete() const
193 return (hdr.nMessageSize == nDataPos);
196 void SetVersion(int nVersionIn)
198 hdrbuf.SetVersion(nVersionIn);
199 vRecv.SetVersion(nVersionIn);
202 int readHeader(const char *pch, unsigned int nBytes);
203 int readData(const char *pch, unsigned int nBytes);
210 /** Information about a peer */
218 size_t nSendSize; // total size of all vSendMsg entries
219 size_t nSendOffset; // offset inside the first vSendMsg already sent
221 std::deque<CSerializeData> vSendMsg;
222 CCriticalSection cs_vSend;
224 std::deque<CInv> vRecvGetData;
225 std::deque<CNetMessage> vRecvMsg;
226 CCriticalSection cs_vRecvMsg;
232 int64_t nTimeConnected;
234 std::string addrName;
237 // strSubVer is whatever byte array we read from the wire. However, this field is intended
238 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
239 // store the sanitized version in cleanSubVer. The original should be used when dealing with
240 // the network or wire types and the cleaned string used when displayed or logged.
241 std::string strSubVer, cleanSubVer;
242 bool fWhitelisted; // This peer can bypass DoS banning.
247 bool fSuccessfullyConnected;
249 // We use fRelayTxes for two purposes -
250 // a) it allows us to not relay tx invs before receiving the peer's version message
251 // b) the peer may tell us in their version message that we should not relay tx invs
252 // until they have initialized their bloom filter.
254 CSemaphoreGrant grantOutbound;
255 CCriticalSection cs_filter;
256 CBloomFilter* pfilter;
261 // Denial-of-service detection/prevention
262 // Key is IP address, value is banned-until-time
263 static std::map<CNetAddr, int64_t> setBanned;
264 static CCriticalSection cs_setBanned;
266 // Whitelisted ranges. Any node connecting from these is automatically
267 // whitelisted (as well as those connecting to whitelisted binds).
268 static std::vector<CSubNet> vWhitelistedRange;
269 static CCriticalSection cs_vWhitelistedRange;
271 // Basic fuzz-testing
272 void Fuzz(int nChance); // modifies ssSend
275 uint256 hashContinue;
276 CBlockIndex* pindexLastGetBlocksBegin;
277 uint256 hashLastGetBlocksEnd;
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);