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;
56 static const bool DEFAULT_UPNP = USE_UPNP;
58 static const bool DEFAULT_UPNP = false;
60 /** The maximum number of entries in mapAskFor */
61 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
62 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
63 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
64 /** The maximum number of peer connections to maintain. */
65 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
67 unsigned int ReceiveFloodSize();
68 unsigned int SendBufferSize();
70 void AddOneShot(const std::string& strDest);
71 void AddressCurrentlyConnected(const CService& addr);
72 CNode* FindNode(const CNetAddr& ip);
73 CNode* FindNode(const CSubNet& subNet);
74 CNode* FindNode(const std::string& addrName);
75 CNode* FindNode(const CService& ip);
76 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
77 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
78 void MapPort(bool fUseUPnP);
79 unsigned short GetListenPort();
80 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
81 void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler);
83 void SocketSendData(CNode *pnode);
89 typedef bool result_type;
92 bool operator()(I first, I last) const
94 while (first != last) {
95 if (!(*first)) return false;
102 // Signals for message handling
105 boost::signals2::signal<int ()> GetHeight;
106 boost::signals2::signal<bool (CNode*), CombinerAll> ProcessMessages;
107 boost::signals2::signal<bool (CNode*, bool), CombinerAll> SendMessages;
108 boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
109 boost::signals2::signal<void (NodeId)> FinalizeNode;
113 CNodeSignals& GetNodeSignals();
118 LOCAL_NONE, // unknown
119 LOCAL_IF, // address a local interface listens on
120 LOCAL_BIND, // address explicit bound to
121 LOCAL_UPNP, // address reported by UPnP
122 LOCAL_MANUAL, // address explicitly specified (-externalip=)
127 bool IsPeerAddrLocalGood(CNode *pnode);
128 void AdvertizeLocal(CNode *pnode);
129 void SetLimited(enum Network net, bool fLimited = true);
130 bool IsLimited(enum Network net);
131 bool IsLimited(const CNetAddr& addr);
132 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
133 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
134 bool RemoveLocal(const CService& addr);
135 bool SeenLocal(const CService& addr);
136 bool IsLocal(const CService& addr);
137 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
138 bool IsReachable(enum Network net);
139 bool IsReachable(const CNetAddr &addr);
140 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
143 extern bool fDiscover;
145 extern uint64_t nLocalServices;
146 extern uint64_t nLocalHostNonce;
147 extern CAddrMan addrman;
148 /** Maximum number of connections to simultaneously allow (aka connection slots) */
149 extern int nMaxConnections;
151 extern std::vector<CNode*> vNodes;
152 extern CCriticalSection cs_vNodes;
153 extern std::map<CInv, CDataStream> mapRelay;
154 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
155 extern CCriticalSection cs_mapRelay;
156 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
158 extern std::vector<std::string> vAddedNodes;
159 extern CCriticalSection cs_vAddedNodes;
161 extern NodeId nLastNodeId;
162 extern CCriticalSection cs_nLastNodeId;
164 struct LocalServiceInfo {
169 extern CCriticalSection cs_mapLocalHost;
170 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
179 int64_t nTimeConnected;
181 std::string addrName;
183 std::string cleanSubVer;
191 std::string addrLocal;
199 bool in_data; // parsing header (false) or data (true)
201 CDataStream hdrbuf; // partially received header
202 CMessageHeader hdr; // complete header
203 unsigned int nHdrPos;
205 CDataStream vRecv; // received message data
206 unsigned int nDataPos;
208 int64_t nTime; // time (in microseconds) of message receipt.
210 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
218 bool complete() const
222 return (hdr.nMessageSize == nDataPos);
225 void SetVersion(int nVersionIn)
227 hdrbuf.SetVersion(nVersionIn);
228 vRecv.SetVersion(nVersionIn);
231 int readHeader(const char *pch, unsigned int nBytes);
232 int readData(const char *pch, unsigned int nBytes);
239 /** Information about a peer */
247 size_t nSendSize; // total size of all vSendMsg entries
248 size_t nSendOffset; // offset inside the first vSendMsg already sent
250 std::deque<CSerializeData> vSendMsg;
251 CCriticalSection cs_vSend;
253 std::deque<CInv> vRecvGetData;
254 std::deque<CNetMessage> vRecvMsg;
255 CCriticalSection cs_vRecvMsg;
261 int64_t nTimeConnected;
264 std::string addrName;
267 int lasthdrsreq,sendhdrsreq;
268 // strSubVer is whatever byte array we read from the wire. However, this field is intended
269 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
270 // store the sanitized version in cleanSubVer. The original should be used when dealing with
271 // the network or wire types and the cleaned string used when displayed or logged.
272 std::string strSubVer, cleanSubVer;
273 bool fWhitelisted; // This peer can bypass DoS banning.
278 bool fSuccessfullyConnected;
280 // We use fRelayTxes for two purposes -
281 // a) it allows us to not relay tx invs before receiving the peer's version message
282 // b) the peer may tell us in its version message that we should not relay tx invs
283 // until it has initialized its bloom filter.
286 CSemaphoreGrant grantOutbound;
287 CCriticalSection cs_filter;
288 CBloomFilter* pfilter;
293 // Denial-of-service detection/prevention
294 // Key is IP address, value is banned-until-time
295 static std::map<CSubNet, int64_t> setBanned;
296 static CCriticalSection cs_setBanned;
298 // Whitelisted ranges. Any node connecting from these is automatically
299 // whitelisted (as well as those connecting to whitelisted binds).
300 static std::vector<CSubNet> vWhitelistedRange;
301 static CCriticalSection cs_vWhitelistedRange;
303 // Basic fuzz-testing
304 void Fuzz(int nChance); // modifies ssSend
307 uint256 hashContinue;
311 std::vector<CAddress> vAddrToSend;
312 CRollingBloomFilter addrKnown;
314 std::set<uint256> setKnown;
316 // inventory based relay
317 mruset<CInv> setInventoryKnown;
318 std::vector<CInv> vInventoryToSend;
319 CCriticalSection cs_inventory;
320 std::set<uint256> setAskFor;
321 std::multimap<int64_t, CInv> mapAskFor;
323 // Ping time measurement:
324 // The pong reply we're expecting, or 0 if no pong expected.
325 uint64_t nPingNonceSent;
326 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
327 int64_t nPingUsecStart;
328 // Last measured round-trip time.
329 int64_t nPingUsecTime;
330 // Best measured round-trip time.
331 int64_t nMinPingUsecTime;
332 // Whether a ping is requested.
335 CNode(SOCKET hSocketIn, const CAddress &addrIn, const std::string &addrNameIn = "", bool fInboundIn = false);
339 // Network usage totals
340 static CCriticalSection cs_totalBytesRecv;
341 static CCriticalSection cs_totalBytesSent;
342 static uint64_t nTotalBytesRecv;
343 static uint64_t nTotalBytesSent;
346 void operator=(const CNode&);
350 NodeId GetId() const {
356 assert(nRefCount >= 0);
360 // requires LOCK(cs_vRecvMsg)
361 unsigned int GetTotalRecvSize()
363 unsigned int total = 0;
364 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
365 total += msg.vRecv.size() + 24;
369 // requires LOCK(cs_vRecvMsg)
370 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
372 // requires LOCK(cs_vRecvMsg)
373 void SetRecvVersion(int nVersionIn)
375 nRecvVersion = nVersionIn;
376 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
377 msg.SetVersion(nVersionIn);
393 void AddAddressKnown(const CAddress& addr)
395 addrKnown.insert(addr.GetKey());
398 void PushAddress(const CAddress& addr)
400 // Known checking here is only to save space from duplicates.
401 // SendMessages will filter it again for knowns that were added
402 // after addresses were pushed.
403 if (addr.IsValid() && !addrKnown.contains(addr.GetKey())) {
404 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
405 vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr;
407 vAddrToSend.push_back(addr);
413 void AddInventoryKnown(const CInv& inv)
417 setInventoryKnown.insert(inv);
421 void PushInventory(const CInv& inv)
425 if (!setInventoryKnown.count(inv))
426 vInventoryToSend.push_back(inv);
430 void AskFor(const CInv& inv);
432 // TODO: Document the postcondition of this function. Is cs_vSend locked?
433 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
435 // TODO: Document the precondition of this function. Is cs_vSend locked?
436 void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
438 // TODO: Document the precondition of this function. Is cs_vSend locked?
439 void EndMessage() UNLOCK_FUNCTION(cs_vSend);
444 void PushMessage(const char* pszCommand)
448 BeginMessage(pszCommand);
458 template<typename T1>
459 void PushMessage(const char* pszCommand, const T1& a1)
463 BeginMessage(pszCommand);
474 template<typename T1, typename T2>
475 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
479 BeginMessage(pszCommand);
490 template<typename T1, typename T2, typename T3>
491 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
495 BeginMessage(pszCommand);
496 ssSend << a1 << a2 << a3;
506 template<typename T1, typename T2, typename T3, typename T4>
507 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
511 BeginMessage(pszCommand);
512 ssSend << a1 << a2 << a3 << a4;
522 template<typename T1, typename T2, typename T3, typename T4, typename T5>
523 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
527 BeginMessage(pszCommand);
528 ssSend << a1 << a2 << a3 << a4 << a5;
538 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
539 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
543 BeginMessage(pszCommand);
544 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
554 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
555 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)
559 BeginMessage(pszCommand);
560 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
570 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
571 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)
575 BeginMessage(pszCommand);
576 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
586 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
587 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)
591 BeginMessage(pszCommand);
592 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
602 void CloseSocketDisconnect();
604 // Denial-of-service detection/prevention
605 // The idea is to detect peers that are behaving
606 // badly and disconnect/ban them, but do it in a
607 // one-coding-mistake-won't-shatter-the-entire-network
609 // IMPORTANT: There should be nothing I can give a
610 // node that it will forward on that will make that
611 // node's peers drop it. If there is, an attacker
612 // can isolate a node and/or try to split the network.
613 // Dropping a node for sending stuff that is invalid
614 // now but might be valid in a later version is also
615 // dangerous, because it can cause a network split
616 // between nodes running old code and nodes running
618 static void ClearBanned(); // needed for unit testing
619 static bool IsBanned(CNetAddr ip);
620 static bool IsBanned(CSubNet subnet);
621 static void Ban(const CNetAddr &ip, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
622 static void Ban(const CSubNet &subNet, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
623 static bool Unban(const CNetAddr &ip);
624 static bool Unban(const CSubNet &ip);
625 static void GetBanned(std::map<CSubNet, int64_t> &banmap);
627 void copyStats(CNodeStats &stats);
629 static bool IsWhitelistedRange(const CNetAddr &ip);
630 static void AddWhitelistedRange(const CSubNet &subnet);
633 static void RecordBytesRecv(uint64_t bytes);
634 static void RecordBytesSent(uint64_t bytes);
636 static uint64_t GetTotalBytesRecv();
637 static uint64_t GetTotalBytesSent();
643 void RelayTransaction(const CTransaction& tx);
644 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
646 /** Access to the (IP) address database (peers.dat) */
650 boost::filesystem::path pathAddr;
653 bool Write(const CAddrMan& addr);
654 bool Read(CAddrMan& addr);
657 #endif // BITCOIN_NET_H