Record nMinPingUsecTime
[bitcoinplatinum.git] / src / net.h
blobde2955732337adfb5907158725f42b34d5d2f4fb
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.
6 #ifndef BITCOIN_NET_H
7 #define BITCOIN_NET_H
9 #include "bloom.h"
10 #include "compat.h"
11 #include "limitedmap.h"
12 #include "mruset.h"
13 #include "netbase.h"
14 #include "protocol.h"
15 #include "random.h"
16 #include "streams.h"
17 #include "sync.h"
18 #include "uint256.h"
20 #include <deque>
21 #include <stdint.h>
23 #ifndef WIN32
24 #include <arpa/inet.h>
25 #endif
27 #include <boost/filesystem/path.hpp>
28 #include <boost/foreach.hpp>
29 #include <boost/signals2/signal.hpp>
31 class CAddrMan;
32 class CScheduler;
33 class CNode;
35 namespace boost {
36 class thread_group;
37 } // namespace boost
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 /** The maximum number of new addresses to accumulate before announcing. */
46 static const unsigned int MAX_ADDR_TO_SEND = 1000;
47 /** Maximum length of incoming protocol messages (no message over 2 MiB is currently acceptable). */
48 static const unsigned int MAX_PROTOCOL_MESSAGE_LENGTH = 2 * 1024 * 1024;
49 /** Maximum length of strSubVer in `version` message */
50 static const unsigned int MAX_SUBVERSION_LENGTH = 256;
51 /** -listen default */
52 static const bool DEFAULT_LISTEN = true;
53 /** -upnp default */
54 #ifdef USE_UPNP
55 static const bool DEFAULT_UPNP = USE_UPNP;
56 #else
57 static const bool DEFAULT_UPNP = false;
58 #endif
59 /** The maximum number of entries in mapAskFor */
60 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
61 /** The maximum number of peer connections to maintain. */
62 static const unsigned int DEFAULT_MAX_PEER_CONNECTIONS = 125;
64 unsigned int ReceiveFloodSize();
65 unsigned int SendBufferSize();
67 void AddOneShot(const std::string& strDest);
68 void AddressCurrentlyConnected(const CService& addr);
69 CNode* FindNode(const CNetAddr& ip);
70 CNode* FindNode(const CSubNet& subNet);
71 CNode* FindNode(const std::string& addrName);
72 CNode* FindNode(const CService& ip);
73 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
74 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
75 void MapPort(bool fUseUPnP);
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);
79 bool StopNode();
80 void SocketSendData(CNode *pnode);
82 typedef int NodeId;
84 struct CombinerAll
86 typedef bool result_type;
88 template<typename I>
89 bool operator()(I first, I last) const
91 while (first != last) {
92 if (!(*first)) return false;
93 ++first;
95 return true;
99 // Signals for message handling
100 struct CNodeSignals
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();
113 enum
115 LOCAL_NONE, // unknown
116 LOCAL_IF, // address a local interface listens on
117 LOCAL_BIND, // address explicit bound to
118 LOCAL_UPNP, // address reported by UPnP
119 LOCAL_MANUAL, // address explicitly specified (-externalip=)
121 LOCAL_MAX
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 SeenLocal(const CService& addr);
132 bool IsLocal(const CService& addr);
133 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
134 bool IsReachable(enum Network net);
135 bool IsReachable(const CNetAddr &addr);
136 void SetReachable(enum Network net, bool fFlag = true);
137 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
140 extern bool fDiscover;
141 extern bool fListen;
142 extern uint64_t nLocalServices;
143 extern uint64_t nLocalHostNonce;
144 extern CAddrMan addrman;
146 // The allocation of connections against the maximum allowed (nMaxConnections)
147 // is prioritized as follows:
148 // 1st: Outbound connections (MAX_OUTBOUND_CONNECTIONS)
149 // 2nd: Inbound connections from whitelisted peers (nWhiteConnections)
150 // 3rd: Inbound connections from non-whitelisted peers
151 // Thus, the number of connection slots for the general public to use is:
152 // nMaxConnections - (MAX_OUTBOUND_CONNECTIONS + nWhiteConnections)
153 // Any additional inbound connections beyond limits will be immediately closed
155 /** Maximum number of connections to simultaneously allow (aka connection slots) */
156 extern int nMaxConnections;
157 /** Number of connection slots to reserve for inbound from whitelisted peers */
158 extern int nWhiteConnections;
160 extern std::vector<CNode*> vNodes;
161 extern CCriticalSection cs_vNodes;
162 extern std::map<CInv, CDataStream> mapRelay;
163 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
164 extern CCriticalSection cs_mapRelay;
165 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
167 extern std::vector<std::string> vAddedNodes;
168 extern CCriticalSection cs_vAddedNodes;
170 extern NodeId nLastNodeId;
171 extern CCriticalSection cs_nLastNodeId;
173 /** Subversion as sent to the P2P network in `version` messages */
174 extern std::string strSubVersion;
176 struct LocalServiceInfo {
177 int nScore;
178 int nPort;
181 extern CCriticalSection cs_mapLocalHost;
182 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
184 class CNodeStats
186 public:
187 NodeId nodeid;
188 uint64_t nServices;
189 int64_t nLastSend;
190 int64_t nLastRecv;
191 int64_t nTimeConnected;
192 int64_t nTimeOffset;
193 std::string addrName;
194 int nVersion;
195 std::string cleanSubVer;
196 bool fInbound;
197 int nStartingHeight;
198 uint64_t nSendBytes;
199 uint64_t nRecvBytes;
200 bool fWhitelisted;
201 double dPingTime;
202 double dPingWait;
203 std::string addrLocal;
209 class CNetMessage {
210 public:
211 bool in_data; // parsing header (false) or data (true)
213 CDataStream hdrbuf; // partially received header
214 CMessageHeader hdr; // complete header
215 unsigned int nHdrPos;
217 CDataStream vRecv; // received message data
218 unsigned int nDataPos;
220 int64_t nTime; // time (in microseconds) of message receipt.
222 CNetMessage(const CMessageHeader::MessageStartChars& pchMessageStartIn, int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), hdr(pchMessageStartIn), vRecv(nTypeIn, nVersionIn) {
223 hdrbuf.resize(24);
224 in_data = false;
225 nHdrPos = 0;
226 nDataPos = 0;
227 nTime = 0;
230 bool complete() const
232 if (!in_data)
233 return false;
234 return (hdr.nMessageSize == nDataPos);
237 void SetVersion(int nVersionIn)
239 hdrbuf.SetVersion(nVersionIn);
240 vRecv.SetVersion(nVersionIn);
243 int readHeader(const char *pch, unsigned int nBytes);
244 int readData(const char *pch, unsigned int nBytes);
248 typedef enum BanReason
250 BanReasonUnknown = 0,
251 BanReasonNodeMisbehaving = 1,
252 BanReasonManuallyAdded = 2
253 } BanReason;
255 class CBanEntry
257 public:
258 static const int CURRENT_VERSION=1;
259 int nVersion;
260 int64_t nCreateTime;
261 int64_t nBanUntil;
262 uint8_t banReason;
264 CBanEntry()
266 SetNull();
269 CBanEntry(int64_t nCreateTimeIn)
271 SetNull();
272 nCreateTime = nCreateTimeIn;
275 ADD_SERIALIZE_METHODS;
277 template <typename Stream, typename Operation>
278 inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
279 READWRITE(this->nVersion);
280 nVersion = this->nVersion;
281 READWRITE(nCreateTime);
282 READWRITE(nBanUntil);
283 READWRITE(banReason);
286 void SetNull()
288 nVersion = CBanEntry::CURRENT_VERSION;
289 nCreateTime = 0;
290 nBanUntil = 0;
291 banReason = BanReasonUnknown;
294 std::string banReasonToString()
296 switch (banReason) {
297 case BanReasonNodeMisbehaving:
298 return "node misbehabing";
299 case BanReasonManuallyAdded:
300 return "manually added";
301 default:
302 return "unknown";
307 typedef std::map<CSubNet, CBanEntry> banmap_t;
309 /** Information about a peer */
310 class CNode
312 public:
313 // socket
314 uint64_t nServices;
315 SOCKET hSocket;
316 CDataStream ssSend;
317 size_t nSendSize; // total size of all vSendMsg entries
318 size_t nSendOffset; // offset inside the first vSendMsg already sent
319 uint64_t nSendBytes;
320 std::deque<CSerializeData> vSendMsg;
321 CCriticalSection cs_vSend;
323 std::deque<CInv> vRecvGetData;
324 std::deque<CNetMessage> vRecvMsg;
325 CCriticalSection cs_vRecvMsg;
326 uint64_t nRecvBytes;
327 int nRecvVersion;
329 int64_t nLastSend;
330 int64_t nLastRecv;
331 int64_t nTimeConnected;
332 int64_t nTimeOffset;
333 CAddress addr;
334 std::string addrName;
335 CService addrLocal;
336 int nVersion;
337 // strSubVer is whatever byte array we read from the wire. However, this field is intended
338 // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
339 // store the sanitized version in cleanSubVer. The original should be used when dealing with
340 // the network or wire types and the cleaned string used when displayed or logged.
341 std::string strSubVer, cleanSubVer;
342 bool fWhitelisted; // This peer can bypass DoS banning.
343 bool fOneShot;
344 bool fClient;
345 bool fInbound;
346 bool fNetworkNode;
347 bool fSuccessfullyConnected;
348 bool fDisconnect;
349 // We use fRelayTxes for two purposes -
350 // a) it allows us to not relay tx invs before receiving the peer's version message
351 // b) the peer may tell us in its version message that we should not relay tx invs
352 // until it has initialized its bloom filter.
353 bool fRelayTxes;
354 CSemaphoreGrant grantOutbound;
355 CCriticalSection cs_filter;
356 CBloomFilter* pfilter;
357 int nRefCount;
358 NodeId id;
359 protected:
361 // Denial-of-service detection/prevention
362 // Key is IP address, value is banned-until-time
363 static banmap_t setBanned;
364 static CCriticalSection cs_setBanned;
365 static bool setBannedIsDirty;
367 // Whitelisted ranges. Any node connecting from these is automatically
368 // whitelisted (as well as those connecting to whitelisted binds).
369 static std::vector<CSubNet> vWhitelistedRange;
370 static CCriticalSection cs_vWhitelistedRange;
372 // Basic fuzz-testing
373 void Fuzz(int nChance); // modifies ssSend
375 public:
376 uint256 hashContinue;
377 int nStartingHeight;
379 // flood relay
380 std::vector<CAddress> vAddrToSend;
381 CRollingBloomFilter addrKnown;
382 bool fGetAddr;
383 std::set<uint256> setKnown;
385 // inventory based relay
386 mruset<CInv> setInventoryKnown;
387 std::vector<CInv> vInventoryToSend;
388 CCriticalSection cs_inventory;
389 std::multimap<int64_t, CInv> mapAskFor;
391 // Ping time measurement:
392 // The pong reply we're expecting, or 0 if no pong expected.
393 uint64_t nPingNonceSent;
394 // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
395 int64_t nPingUsecStart;
396 // Last measured round-trip time.
397 int64_t nPingUsecTime;
398 // Best measured round-trip time.
399 int64_t nMinPingUsecTime;
400 // Whether a ping is requested.
401 bool fPingQueued;
403 CNode(SOCKET hSocketIn, const CAddress &addrIn, const std::string &addrNameIn = "", bool fInboundIn = false);
404 ~CNode();
406 private:
407 // Network usage totals
408 static CCriticalSection cs_totalBytesRecv;
409 static CCriticalSection cs_totalBytesSent;
410 static uint64_t nTotalBytesRecv;
411 static uint64_t nTotalBytesSent;
413 CNode(const CNode&);
414 void operator=(const CNode&);
416 public:
418 NodeId GetId() const {
419 return id;
422 int GetRefCount()
424 assert(nRefCount >= 0);
425 return nRefCount;
428 // requires LOCK(cs_vRecvMsg)
429 unsigned int GetTotalRecvSize()
431 unsigned int total = 0;
432 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
433 total += msg.vRecv.size() + 24;
434 return total;
437 // requires LOCK(cs_vRecvMsg)
438 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
440 // requires LOCK(cs_vRecvMsg)
441 void SetRecvVersion(int nVersionIn)
443 nRecvVersion = nVersionIn;
444 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
445 msg.SetVersion(nVersionIn);
448 CNode* AddRef()
450 nRefCount++;
451 return this;
454 void Release()
456 nRefCount--;
461 void AddAddressKnown(const CAddress& addr)
463 addrKnown.insert(addr.GetKey());
466 void PushAddress(const CAddress& addr)
468 // Known checking here is only to save space from duplicates.
469 // SendMessages will filter it again for knowns that were added
470 // after addresses were pushed.
471 if (addr.IsValid() && !addrKnown.contains(addr.GetKey())) {
472 if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
473 vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr;
474 } else {
475 vAddrToSend.push_back(addr);
481 void AddInventoryKnown(const CInv& inv)
484 LOCK(cs_inventory);
485 setInventoryKnown.insert(inv);
489 void PushInventory(const CInv& inv)
492 LOCK(cs_inventory);
493 if (!setInventoryKnown.count(inv))
494 vInventoryToSend.push_back(inv);
498 void AskFor(const CInv& inv);
500 // TODO: Document the postcondition of this function. Is cs_vSend locked?
501 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
503 // TODO: Document the precondition of this function. Is cs_vSend locked?
504 void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
506 // TODO: Document the precondition of this function. Is cs_vSend locked?
507 void EndMessage() UNLOCK_FUNCTION(cs_vSend);
509 void PushVersion();
512 void PushMessage(const char* pszCommand)
516 BeginMessage(pszCommand);
517 EndMessage();
519 catch (...)
521 AbortMessage();
522 throw;
526 template<typename T1>
527 void PushMessage(const char* pszCommand, const T1& a1)
531 BeginMessage(pszCommand);
532 ssSend << a1;
533 EndMessage();
535 catch (...)
537 AbortMessage();
538 throw;
542 template<typename T1, typename T2>
543 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
547 BeginMessage(pszCommand);
548 ssSend << a1 << a2;
549 EndMessage();
551 catch (...)
553 AbortMessage();
554 throw;
558 template<typename T1, typename T2, typename T3>
559 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
563 BeginMessage(pszCommand);
564 ssSend << a1 << a2 << a3;
565 EndMessage();
567 catch (...)
569 AbortMessage();
570 throw;
574 template<typename T1, typename T2, typename T3, typename T4>
575 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
579 BeginMessage(pszCommand);
580 ssSend << a1 << a2 << a3 << a4;
581 EndMessage();
583 catch (...)
585 AbortMessage();
586 throw;
590 template<typename T1, typename T2, typename T3, typename T4, typename T5>
591 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
595 BeginMessage(pszCommand);
596 ssSend << a1 << a2 << a3 << a4 << a5;
597 EndMessage();
599 catch (...)
601 AbortMessage();
602 throw;
606 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
607 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
611 BeginMessage(pszCommand);
612 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
613 EndMessage();
615 catch (...)
617 AbortMessage();
618 throw;
622 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
623 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)
627 BeginMessage(pszCommand);
628 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
629 EndMessage();
631 catch (...)
633 AbortMessage();
634 throw;
638 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
639 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)
643 BeginMessage(pszCommand);
644 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
645 EndMessage();
647 catch (...)
649 AbortMessage();
650 throw;
654 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
655 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)
659 BeginMessage(pszCommand);
660 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
661 EndMessage();
663 catch (...)
665 AbortMessage();
666 throw;
670 void CloseSocketDisconnect();
672 // Denial-of-service detection/prevention
673 // The idea is to detect peers that are behaving
674 // badly and disconnect/ban them, but do it in a
675 // one-coding-mistake-won't-shatter-the-entire-network
676 // way.
677 // IMPORTANT: There should be nothing I can give a
678 // node that it will forward on that will make that
679 // node's peers drop it. If there is, an attacker
680 // can isolate a node and/or try to split the network.
681 // Dropping a node for sending stuff that is invalid
682 // now but might be valid in a later version is also
683 // dangerous, because it can cause a network split
684 // between nodes running old code and nodes running
685 // new code.
686 static void ClearBanned(); // needed for unit testing
687 static bool IsBanned(CNetAddr ip);
688 static bool IsBanned(CSubNet subnet);
689 static void Ban(const CNetAddr &ip, const BanReason &banReason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
690 static void Ban(const CSubNet &subNet, const BanReason &banReason, int64_t bantimeoffset = 0, bool sinceUnixEpoch = false);
691 static bool Unban(const CNetAddr &ip);
692 static bool Unban(const CSubNet &ip);
693 static void GetBanned(banmap_t &banmap);
694 static void SetBanned(const banmap_t &banmap);
696 //!check is the banlist has unwritten changes
697 static bool BannedSetIsDirty();
698 //!set the "dirty" flag for the banlist
699 static void SetBannedSetDirty(bool dirty=true);
700 //!clean unused entries (if bantime has expired)
701 static void SweepBanned();
703 void copyStats(CNodeStats &stats);
705 static bool IsWhitelistedRange(const CNetAddr &ip);
706 static void AddWhitelistedRange(const CSubNet &subnet);
708 // Network stats
709 static void RecordBytesRecv(uint64_t bytes);
710 static void RecordBytesSent(uint64_t bytes);
712 static uint64_t GetTotalBytesRecv();
713 static uint64_t GetTotalBytesSent();
718 class CTransaction;
719 void RelayTransaction(const CTransaction& tx);
720 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
722 /** Access to the (IP) address database (peers.dat) */
723 class CAddrDB
725 private:
726 boost::filesystem::path pathAddr;
727 public:
728 CAddrDB();
729 bool Write(const CAddrMan& addr);
730 bool Read(CAddrMan& addr);
733 /** Access to the banlist database (banlist.dat) */
734 class CBanDB
736 private:
737 boost::filesystem::path pathBanlist;
738 public:
739 CBanDB();
740 bool Write(const banmap_t& banSet);
741 bool Read(banmap_t& banSet);
744 void DumpBanlist();
746 #endif // BITCOIN_NET_H