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.
11 #include "limitedmap.h"
24 #include <arpa/inet.h>
27 #include <boost/filesystem/path.hpp>
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 /** 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;
55 static const bool DEFAULT_UPNP
= USE_UPNP
;
57 static const bool DEFAULT_UPNP
= false;
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
);
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
, // 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 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
;
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
{
181 extern CCriticalSection cs_mapLocalHost
;
182 extern std::map
<CNetAddr
, LocalServiceInfo
> mapLocalHost
;
191 int64_t nTimeConnected
;
193 std::string addrName
;
195 std::string cleanSubVer
;
203 std::string addrLocal
;
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
) {
230 bool complete() const
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
258 static const int CURRENT_VERSION
=1;
269 CBanEntry(int64_t nCreateTimeIn
)
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
);
288 nVersion
= CBanEntry::CURRENT_VERSION
;
291 banReason
= BanReasonUnknown
;
294 std::string
banReasonToString()
297 case BanReasonNodeMisbehaving
:
298 return "node misbehabing";
299 case BanReasonManuallyAdded
:
300 return "manually added";
307 typedef std::map
<CSubNet
, CBanEntry
> banmap_t
;
309 /** Information about a peer */
317 size_t nSendSize
; // total size of all vSendMsg entries
318 size_t nSendOffset
; // offset inside the first vSendMsg already sent
320 std::deque
<CSerializeData
> vSendMsg
;
321 CCriticalSection cs_vSend
;
323 std::deque
<CInv
> vRecvGetData
;
324 std::deque
<CNetMessage
> vRecvMsg
;
325 CCriticalSection cs_vRecvMsg
;
331 int64_t nTimeConnected
;
334 std::string addrName
;
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.
347 bool fSuccessfullyConnected
;
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.
354 CSemaphoreGrant grantOutbound
;
355 CCriticalSection cs_filter
;
356 CBloomFilter
* pfilter
;
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
376 uint256 hashContinue
;
380 std::vector
<CAddress
> vAddrToSend
;
381 CRollingBloomFilter addrKnown
;
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.
403 CNode(SOCKET hSocketIn
, const CAddress
&addrIn
, const std::string
&addrNameIn
= "", bool fInboundIn
= false);
407 // Network usage totals
408 static CCriticalSection cs_totalBytesRecv
;
409 static CCriticalSection cs_totalBytesSent
;
410 static uint64_t nTotalBytesRecv
;
411 static uint64_t nTotalBytesSent
;
414 void operator=(const CNode
&);
418 NodeId
GetId() const {
424 assert(nRefCount
>= 0);
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;
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
);
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
;
475 vAddrToSend
.push_back(addr
);
481 void AddInventoryKnown(const CInv
& inv
)
485 setInventoryKnown
.insert(inv
);
489 void PushInventory(const CInv
& inv
)
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
);
512 void PushMessage(const char* pszCommand
)
516 BeginMessage(pszCommand
);
526 template<typename T1
>
527 void PushMessage(const char* pszCommand
, const T1
& a1
)
531 BeginMessage(pszCommand
);
542 template<typename T1
, typename T2
>
543 void PushMessage(const char* pszCommand
, const T1
& a1
, const T2
& a2
)
547 BeginMessage(pszCommand
);
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
;
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
;
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
;
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
;
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
;
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
;
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
;
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
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
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
);
709 static void RecordBytesRecv(uint64_t bytes
);
710 static void RecordBytesSent(uint64_t bytes
);
712 static uint64_t GetTotalBytesRecv();
713 static uint64_t GetTotalBytesSent();
719 void RelayTransaction(const CTransaction
& tx
);
720 void RelayTransaction(const CTransaction
& tx
, const CDataStream
& ss
);
722 /** Access to the (IP) address database (peers.dat) */
726 boost::filesystem::path pathAddr
;
729 bool Write(const CAddrMan
& addr
);
730 bool Read(CAddrMan
& addr
);
733 /** Access to the banlist database (banlist.dat) */
737 boost::filesystem::path pathBanlist
;
740 bool Write(const banmap_t
& banSet
);
741 bool Read(banmap_t
& banSet
);
746 #endif // BITCOIN_NET_H