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 /** Maximum length of strSubVer in `version` message */
53 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
54 /** -listen default */
55 static const bool DEFAULT_LISTEN = true;
56 /** The maximum number of entries in mapAskFor */
57 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
58 /** The maximum number of entries in setAskFor (larger due to getdata latency)*/
59 static const size_t SETASKFOR_MAX_SZ = 2 * MAX_INV_SZ;
60 /** The maximum number of peer connections to maintain. */
61 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 384;
62 /** The period before a network upgrade activates, where connections to upgrading peers are preferred (in blocks). */
63 static const int NETWORK_UPGRADE_PEER_PREFERENCE_BLOCK_PERIOD = 24 * 24 * 3;
65 unsigned int ReceiveFloodSize();
66 unsigned int SendBufferSize();
68 void AddOneShot(const std::string& strDest);
69 void AddressCurrentlyConnected(const CService& addr);
70 CNode* FindNode(const CNetAddr& ip);
71 CNode* FindNode(const CSubNet& subNet);
72 CNode* FindNode(const std::string& addrName);
73 CNode* FindNode(const CService& ip);
74 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
75 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
76 unsigned short GetListenPort();
77 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
78 void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler);
80 void SocketSendData(CNode *pnode);
86 typedef bool result_type;
89 bool operator()(I first, I last) const
91 while (first != last) {
92 if (!(*first)) return false;
99 // Signals for message handling
102 boost::signals2::signal<int ()> GetHeight;
103 boost::signals2::signal<bool (CNode*), CombinerAll> ProcessMessages;
104 boost::signals2::signal<bool (CNode*, bool), CombinerAll> SendMessages;
105 boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
106 boost::signals2::signal<void (NodeId)> FinalizeNode;
110 CNodeSignals& GetNodeSignals();
115 LOCAL_NONE, // unknown
116 LOCAL_IF, // address a local interface listens on
117 LOCAL_BIND, // address explicit bound to
118 LOCAL_UPNP, // unused (was: address reported by UPnP)
119 LOCAL_MANUAL, // address explicitly specified (-externalip=)
124 bool IsPeerAddrLocalGood(CNode *pnode);
125 void AdvertizeLocal(CNode *pnode);
126 void SetLimited(enum Network net, bool fLimited = true);
127 bool IsLimited(enum Network net);
128 bool IsLimited(const CNetAddr& addr);
129 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
130 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
131 bool RemoveLocal(const CService& addr);
132 bool SeenLocal(const CService& addr);
133 bool IsLocal(const CService& addr);
134 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
135 bool IsReachable(enum Network net);
136 bool IsReachable(const CNetAddr &addr);
137 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
140 extern bool fDiscover;
142 extern uint64_t nLocalServices;
143 extern uint64_t nLocalHostNonce;
144 extern CAddrMan addrman;
145 /** Maximum number of connections to simultaneously allow (aka connection slots) */
146 extern int nMaxConnections;
148 extern std::vector<CNode*> vNodes;
149 extern CCriticalSection cs_vNodes;
150 extern std::map<CInv, CDataStream> mapRelay;
151 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
152 extern CCriticalSection cs_mapRelay;
153 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
155 extern std::vector<std::string> vAddedNodes;
156 extern CCriticalSection cs_vAddedNodes;
158 extern NodeId nLastNodeId;
159 extern CCriticalSection cs_nLastNodeId;
161 /** Subversion as sent to the P2P network in `version` messages */
162 extern std::string strSubVersion;
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;
294 // Denial-of-service detection/prevention
295 // Key is IP address, value is banned-until-time
296 static std::map<CSubNet, int64_t> setBanned;
297 static CCriticalSection cs_setBanned;
299 // Whitelisted ranges. Any node connecting from these is automatically
300 // whitelisted (as well as those connecting to whitelisted binds).
301 static std::vector<CSubNet> vWhitelistedRange;
302 static CCriticalSection cs_vWhitelistedRange;
304 // Basic fuzz-testing
305 void Fuzz(int nChance); // modifies ssSend
308 // for PBaaS nodes, each node may be associated with the hash of a pubkey as a payment address to receive rewards for supporting a
310 uint160 hashPaymentAddress;
312 uint256 hashContinue;
316 std::vector<CAddress> vAddrToSend;
317 CRollingBloomFilter addrKnown;
319 std::set<uint256> setKnown;
321 // inventory based relay
322 mruset<CInv> setInventoryKnown;
323 std::vector<CInv> vInventoryToSend;
324 CCriticalSection cs_inventory;
325 std::set<uint256> setAskFor;
326 std::multimap<int64_t, CInv> mapAskFor;
328 // Ping time measurement:
329 // The pong reply we're expecting, or 0 if no pong expected.
330 uint64_t nPingNonceSent;
331 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
332 int64_t nPingUsecStart;
333 // Last measured round-trip time.
334 int64_t nPingUsecTime;
335 // Best measured round-trip time.
336 int64_t nMinPingUsecTime;
337 // Whether a ping is requested.
340 CNode(SOCKET hSocketIn, const CAddress &addrIn, const std::string &addrNameIn = "", bool fInboundIn = false);
344 // Network usage totals
345 static CCriticalSection cs_totalBytesRecv;
346 static CCriticalSection cs_totalBytesSent;
347 static uint64_t nTotalBytesRecv;
348 static uint64_t nTotalBytesSent;
351 void operator=(const CNode&);
355 NodeId GetId() const {
361 assert(nRefCount >= 0);
365 // requires LOCK(cs_vRecvMsg)
366 unsigned int GetTotalRecvSize()
368 unsigned int total = 0;
369 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
370 total += msg.vRecv.size() + 24;
374 // requires LOCK(cs_vRecvMsg)
375 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
377 // requires LOCK(cs_vRecvMsg)
378 void SetRecvVersion(int nVersionIn)
380 nRecvVersion = nVersionIn;
381 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
382 msg.SetVersion(nVersionIn);
398 void AddAddressKnown(const CAddress& addr)
400 addrKnown.insert(addr.GetKey());
403 void PushAddress(const CAddress& addr)
405 // Known checking here is only to save space from duplicates.
406 // SendMessages will filter it again for knowns that were added
407 // after addresses were pushed.
408 if (addr.IsValid() && !addrKnown.contains(addr.GetKey())) {
409 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
410 vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr;
412 vAddrToSend.push_back(addr);
418 void AddInventoryKnown(const CInv& inv)
422 setInventoryKnown.insert(inv);
426 void PushInventory(const CInv& inv)
430 if (!setInventoryKnown.count(inv))
431 vInventoryToSend.push_back(inv);
435 void AskFor(const CInv& inv);
437 // TODO: Document the postcondition of this function. Is cs_vSend locked?
438 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
440 // TODO: Document the precondition of this function. Is cs_vSend locked?
441 void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
443 // TODO: Document the precondition of this function. Is cs_vSend locked?
444 void EndMessage() UNLOCK_FUNCTION(cs_vSend);
449 void PushMessage(const char* pszCommand)
453 BeginMessage(pszCommand);
463 template<typename T1>
464 void PushMessage(const char* pszCommand, const T1& a1)
468 BeginMessage(pszCommand);
479 template<typename T1, typename T2>
480 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
484 BeginMessage(pszCommand);
495 template<typename T1, typename T2, typename T3>
496 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
500 BeginMessage(pszCommand);
501 ssSend << a1 << a2 << a3;
511 template<typename T1, typename T2, typename T3, typename T4>
512 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
516 BeginMessage(pszCommand);
517 ssSend << a1 << a2 << a3 << a4;
527 template<typename T1, typename T2, typename T3, typename T4, typename T5>
528 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
532 BeginMessage(pszCommand);
533 ssSend << a1 << a2 << a3 << a4 << a5;
543 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
544 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
548 BeginMessage(pszCommand);
549 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
559 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
560 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)
564 BeginMessage(pszCommand);
565 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
575 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
576 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)
580 BeginMessage(pszCommand);
581 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
591 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
592 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)
596 BeginMessage(pszCommand);
597 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
607 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9, typename T10>
608 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, const T10& a10)
612 BeginMessage(pszCommand);
613 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10;
623 void CloseSocketDisconnect();
625 // Denial-of-service detection/prevention
626 // The idea is to detect peers that are behaving
627 // badly and disconnect/ban them, but do it in a
628 // one-coding-mistake-won't-shatter-the-entire-network
630 // IMPORTANT: There should be nothing I can give a
631 // node that it will forward on that will make that
632 // node's peers drop it. If there is, an attacker
633 // can isolate a node and/or try to split the network.
634 // Dropping a node for sending stuff that is invalid
635 // now but might be valid in a later version is also
636 // dangerous, because it can cause a network split
637 // between nodes running old code and nodes running
639 static void ClearBanned(); // needed for unit testing
640 static bool IsBanned(CNetAddr ip);
641 static bool IsBanned(CSubNet subnet);
642 static void Ban(const CNetAddr &ip, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
643 static void Ban(const CSubNet &subNet, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
644 static bool Unban(const CNetAddr &ip);
645 static bool Unban(const CSubNet &ip);
646 static void GetBanned(std::map<CSubNet, int64_t> &banmap);
648 void copyStats(CNodeStats &stats);
650 static bool IsWhitelistedRange(const CNetAddr &ip);
651 static void AddWhitelistedRange(const CSubNet &subnet);
654 static void RecordBytesRecv(uint64_t bytes);
655 static void RecordBytesSent(uint64_t bytes);
657 static uint64_t GetTotalBytesRecv();
658 static uint64_t GetTotalBytesSent();
664 void RelayTransaction(const CTransaction& tx);
665 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
667 /** Access to the (IP) address database (peers.dat) */
671 boost::filesystem::path pathAddr;
674 bool Write(const CAddrMan& addr);
675 bool Read(CAddrMan& addr);
678 #endif // BITCOIN_NET_H