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;
54 /** The maximum number of entries in mapAskFor */
55 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
56 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
57 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
58 /** The maximum number of peer connections to maintain. */
59 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
60 /** The period before a network upgrade activates, where connections to upgrading peers are preferred (in blocks). */
61 static const int NETWORK_UPGRADE_PEER_PREFERENCE_BLOCK_PERIOD = 24 * 24 * 3;
63 unsigned int ReceiveFloodSize();
64 unsigned int SendBufferSize();
66 void AddOneShot(const std::string& strDest);
67 void AddressCurrentlyConnected(const CService& addr);
68 CNode* FindNode(const CNetAddr& ip);
69 CNode* FindNode(const CSubNet& subNet);
70 CNode* FindNode(const std::string& addrName);
71 CNode* FindNode(const CService& ip);
72 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
73 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
74 unsigned short GetListenPort();
75 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
76 void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler);
78 void SocketSendData(CNode *pnode);
84 typedef bool result_type;
87 bool operator()(I first, I last) const
89 while (first != last) {
90 if (!(*first)) return false;
97 // Signals for message handling
100 boost::signals2::signal<int ()> GetHeight;
101 boost::signals2::signal<bool (CNode*), CombinerAll> ProcessMessages;
102 boost::signals2::signal<bool (CNode*, bool), CombinerAll> SendMessages;
103 boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
104 boost::signals2::signal<void (NodeId)> FinalizeNode;
108 CNodeSignals& GetNodeSignals();
113 LOCAL_NONE, // unknown
114 LOCAL_IF, // address a local interface listens on
115 LOCAL_BIND, // address explicit bound to
116 LOCAL_UPNP, // unused (was: address reported by UPnP)
117 LOCAL_MANUAL, // address explicitly specified (-externalip=)
122 bool IsPeerAddrLocalGood(CNode *pnode);
123 void AdvertizeLocal(CNode *pnode);
124 void SetLimited(enum Network net, bool fLimited = true);
125 bool IsLimited(enum Network net);
126 bool IsLimited(const CNetAddr& addr);
127 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
128 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
129 bool RemoveLocal(const CService& addr);
130 bool SeenLocal(const CService& addr);
131 bool IsLocal(const CService& addr);
132 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
133 bool IsReachable(enum Network net);
134 bool IsReachable(const CNetAddr &addr);
135 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
138 extern bool fDiscover;
140 extern uint64_t nLocalServices;
141 extern uint64_t nLocalHostNonce;
142 extern CAddrMan addrman;
143 /** Maximum number of connections to simultaneously allow (aka connection slots) */
144 extern int nMaxConnections;
146 extern std::vector<CNode*> vNodes;
147 extern CCriticalSection cs_vNodes;
148 extern std::map<CInv, CDataStream> mapRelay;
149 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
150 extern CCriticalSection cs_mapRelay;
151 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
153 extern std::vector<std::string> vAddedNodes;
154 extern CCriticalSection cs_vAddedNodes;
156 extern NodeId nLastNodeId;
157 extern CCriticalSection cs_nLastNodeId;
159 struct LocalServiceInfo {
164 extern CCriticalSection cs_mapLocalHost;
165 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
174 int64_t nTimeConnected;
176 std::string addrName;
178 std::string cleanSubVer;
186 std::string addrLocal;
194 bool in_data; // parsing header (false) or data (true)
196 CDataStream hdrbuf; // partially received header
197 CMessageHeader hdr; // complete header
198 unsigned int nHdrPos;
200 CDataStream vRecv; // received message data
201 unsigned int nDataPos;
203 int64_t nTime; // time (in microseconds) of message receipt.
205 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
213 bool complete() const
217 return (hdr.nMessageSize == nDataPos);
220 void SetVersion(int nVersionIn)
222 hdrbuf.SetVersion(nVersionIn);
223 vRecv.SetVersion(nVersionIn);
226 int readHeader(const char *pch, unsigned int nBytes);
227 int readData(const char *pch, unsigned int nBytes);
234 /** Information about a peer */
242 size_t nSendSize; // total size of all vSendMsg entries
243 size_t nSendOffset; // offset inside the first vSendMsg already sent
245 std::deque<CSerializeData> vSendMsg;
246 CCriticalSection cs_vSend;
248 std::deque<CInv> vRecvGetData;
249 std::deque<CNetMessage> vRecvMsg;
250 CCriticalSection cs_vRecvMsg;
256 int64_t nTimeConnected;
259 std::string addrName;
262 // strSubVer is whatever byte array we read from the wire. However, this field is intended
263 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
264 // store the sanitized version in cleanSubVer. The original should be used when dealing with
265 // the network or wire types and the cleaned string used when displayed or logged.
266 std::string strSubVer, cleanSubVer;
267 bool fWhitelisted; // This peer can bypass DoS banning.
272 bool fSuccessfullyConnected;
274 // We use fRelayTxes for two purposes -
275 // a) it allows us to not relay tx invs before receiving the peer's version message
276 // b) the peer may tell us in its version message that we should not relay tx invs
277 // until it has initialized its bloom filter.
280 CSemaphoreGrant grantOutbound;
281 CCriticalSection cs_filter;
282 CBloomFilter* pfilter;
287 // Denial-of-service detection/prevention
288 // Key is IP address, value is banned-until-time
289 static std::map<CSubNet, int64_t> setBanned;
290 static CCriticalSection cs_setBanned;
292 // Whitelisted ranges. Any node connecting from these is automatically
293 // whitelisted (as well as those connecting to whitelisted binds).
294 static std::vector<CSubNet> vWhitelistedRange;
295 static CCriticalSection cs_vWhitelistedRange;
297 // Basic fuzz-testing
298 void Fuzz(int nChance); // modifies ssSend
301 uint256 hashContinue;
305 std::vector<CAddress> vAddrToSend;
306 CRollingBloomFilter addrKnown;
308 std::set<uint256> setKnown;
310 // inventory based relay
311 mruset<CInv> setInventoryKnown;
312 std::vector<CInv> vInventoryToSend;
313 CCriticalSection cs_inventory;
314 std::set<uint256> setAskFor;
315 std::multimap<int64_t, CInv> mapAskFor;
317 // Ping time measurement:
318 // The pong reply we're expecting, or 0 if no pong expected.
319 uint64_t nPingNonceSent;
320 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
321 int64_t nPingUsecStart;
322 // Last measured round-trip time.
323 int64_t nPingUsecTime;
324 // Best measured round-trip time.
325 int64_t nMinPingUsecTime;
326 // Whether a ping is requested.
329 CNode(SOCKET hSocketIn, const CAddress &addrIn, const std::string &addrNameIn = "", bool fInboundIn = false);
333 // Network usage totals
334 static CCriticalSection cs_totalBytesRecv;
335 static CCriticalSection cs_totalBytesSent;
336 static uint64_t nTotalBytesRecv;
337 static uint64_t nTotalBytesSent;
340 void operator=(const CNode&);
344 NodeId GetId() const {
350 assert(nRefCount >= 0);
354 // requires LOCK(cs_vRecvMsg)
355 unsigned int GetTotalRecvSize()
357 unsigned int total = 0;
358 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
359 total += msg.vRecv.size() + 24;
363 // requires LOCK(cs_vRecvMsg)
364 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
366 // requires LOCK(cs_vRecvMsg)
367 void SetRecvVersion(int nVersionIn)
369 nRecvVersion = nVersionIn;
370 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
371 msg.SetVersion(nVersionIn);
387 void AddAddressKnown(const CAddress& addr)
389 addrKnown.insert(addr.GetKey());
392 void PushAddress(const CAddress& addr)
394 // Known checking here is only to save space from duplicates.
395 // SendMessages will filter it again for knowns that were added
396 // after addresses were pushed.
397 if (addr.IsValid() && !addrKnown.contains(addr.GetKey())) {
398 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
399 vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr;
401 vAddrToSend.push_back(addr);
407 void AddInventoryKnown(const CInv& inv)
411 setInventoryKnown.insert(inv);
415 void PushInventory(const CInv& inv)
419 if (!setInventoryKnown.count(inv))
420 vInventoryToSend.push_back(inv);
424 void AskFor(const CInv& inv);
426 // TODO: Document the postcondition of this function. Is cs_vSend locked?
427 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
429 // TODO: Document the precondition of this function. Is cs_vSend locked?
430 void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
432 // TODO: Document the precondition of this function. Is cs_vSend locked?
433 void EndMessage() UNLOCK_FUNCTION(cs_vSend);
438 void PushMessage(const char* pszCommand)
442 BeginMessage(pszCommand);
452 template<typename T1>
453 void PushMessage(const char* pszCommand, const T1& a1)
457 BeginMessage(pszCommand);
468 template<typename T1, typename T2>
469 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
473 BeginMessage(pszCommand);
484 template<typename T1, typename T2, typename T3>
485 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
489 BeginMessage(pszCommand);
490 ssSend << a1 << a2 << a3;
500 template<typename T1, typename T2, typename T3, typename T4>
501 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
505 BeginMessage(pszCommand);
506 ssSend << a1 << a2 << a3 << a4;
516 template<typename T1, typename T2, typename T3, typename T4, typename T5>
517 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
521 BeginMessage(pszCommand);
522 ssSend << a1 << a2 << a3 << a4 << a5;
532 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
533 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
537 BeginMessage(pszCommand);
538 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
548 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
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)
553 BeginMessage(pszCommand);
554 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
564 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
565 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)
569 BeginMessage(pszCommand);
570 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
580 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
581 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)
585 BeginMessage(pszCommand);
586 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
596 void CloseSocketDisconnect();
598 // Denial-of-service detection/prevention
599 // The idea is to detect peers that are behaving
600 // badly and disconnect/ban them, but do it in a
601 // one-coding-mistake-won't-shatter-the-entire-network
603 // IMPORTANT: There should be nothing I can give a
604 // node that it will forward on that will make that
605 // node's peers drop it. If there is, an attacker
606 // can isolate a node and/or try to split the network.
607 // Dropping a node for sending stuff that is invalid
608 // now but might be valid in a later version is also
609 // dangerous, because it can cause a network split
610 // between nodes running old code and nodes running
612 static void ClearBanned(); // needed for unit testing
613 static bool IsBanned(CNetAddr ip);
614 static bool IsBanned(CSubNet subnet);
615 static void Ban(const CNetAddr &ip, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
616 static void Ban(const CSubNet &subNet, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
617 static bool Unban(const CNetAddr &ip);
618 static bool Unban(const CSubNet &ip);
619 static void GetBanned(std::map<CSubNet, int64_t> &banmap);
621 void copyStats(CNodeStats &stats);
623 static bool IsWhitelistedRange(const CNetAddr &ip);
624 static void AddWhitelistedRange(const CSubNet &subnet);
627 static void RecordBytesRecv(uint64_t bytes);
628 static void RecordBytesSent(uint64_t bytes);
630 static uint64_t GetTotalBytesRecv();
631 static uint64_t GetTotalBytesSent();
637 void RelayTransaction(const CTransaction& tx);
638 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
640 /** Access to the (IP) address database (peers.dat) */
644 boost::filesystem::path pathAddr;
647 bool Write(const CAddrMan& addr);
648 bool Read(CAddrMan& addr);
651 #endif // BITCOIN_NET_H