1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
9 #include <boost/array.hpp>
10 #include <boost/foreach.hpp>
11 #include <boost/signals2/signal.hpp>
12 #include <openssl/rand.h>
15 #include <arpa/inet.h>
19 #include "limitedmap.h"
26 /** The maximum number of entries in an 'inv' protocol message */
27 static const unsigned int MAX_INV_SZ = 50000;
31 extern int nBestHeight;
35 inline unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
36 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
38 void AddOneShot(std::string strDest);
39 bool RecvLine(SOCKET hSocket, std::string& strLine);
40 bool GetMyExternalIP(CNetAddr& ipRet);
41 void AddressCurrentlyConnected(const CService& addr);
42 CNode* FindNode(const CNetAddr& ip);
43 CNode* FindNode(const CService& ip);
44 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL);
45 void MapPort(bool fUseUPnP);
46 unsigned short GetListenPort();
47 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
48 void StartNode(boost::thread_group& threadGroup);
50 void SocketSendData(CNode *pnode);
52 // Signals for message handling
55 boost::signals2::signal<bool (CNode*)> ProcessMessages;
56 boost::signals2::signal<bool (CNode*, bool)> SendMessages;
59 CNodeSignals& GetNodeSignals();
64 LOCAL_NONE, // unknown
65 LOCAL_IF, // address a local interface listens on
66 LOCAL_BIND, // address explicit bound to
67 LOCAL_UPNP, // address reported by UPnP
68 LOCAL_HTTP, // address reported by whatismyip.com and similar
69 LOCAL_MANUAL, // address explicitly specified (-externalip=)
74 void SetLimited(enum Network net, bool fLimited = true);
75 bool IsLimited(enum Network net);
76 bool IsLimited(const CNetAddr& addr);
77 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
78 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
79 bool SeenLocal(const CService& addr);
80 bool IsLocal(const CService& addr);
81 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
82 bool IsReachable(const CNetAddr &addr);
83 void SetReachable(enum Network net, bool fFlag = true);
84 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
87 extern bool fDiscover;
88 extern uint64 nLocalServices;
89 extern uint64 nLocalHostNonce;
90 extern CAddrMan addrman;
91 extern int nMaxConnections;
93 extern std::vector<CNode*> vNodes;
94 extern CCriticalSection cs_vNodes;
95 extern std::map<CInv, CDataStream> mapRelay;
96 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
97 extern CCriticalSection cs_mapRelay;
98 extern limitedmap<CInv, int64> mapAlreadyAskedFor;
100 extern std::vector<std::string> vAddedNodes;
101 extern CCriticalSection cs_vAddedNodes;
112 int64 nTimeConnected;
113 std::string addrName;
115 std::string strSubVer;
129 bool in_data; // parsing header (false) or data (true)
131 CDataStream hdrbuf; // partially received header
132 CMessageHeader hdr; // complete header
133 unsigned int nHdrPos;
135 CDataStream vRecv; // received message data
136 unsigned int nDataPos;
138 CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
145 bool complete() const
149 return (hdr.nMessageSize == nDataPos);
152 void SetVersion(int nVersionIn)
154 hdrbuf.SetVersion(nVersionIn);
155 vRecv.SetVersion(nVersionIn);
158 int readHeader(const char *pch, unsigned int nBytes);
159 int readData(const char *pch, unsigned int nBytes);
166 /** Information about a peer */
174 size_t nSendSize; // total size of all vSendMsg entries
175 size_t nSendOffset; // offset inside the first vSendMsg already sent
177 std::deque<CSerializeData> vSendMsg;
178 CCriticalSection cs_vSend;
180 std::deque<CInv> vRecvGetData;
181 std::deque<CNetMessage> vRecvMsg;
182 CCriticalSection cs_vRecvMsg;
188 int64 nLastSendEmpty;
189 int64 nTimeConnected;
191 std::string addrName;
194 std::string strSubVer;
199 bool fSuccessfullyConnected;
201 // We use fRelayTxes for two purposes -
202 // a) it allows us to not relay tx invs before receiving the peer's version message
203 // b) the peer may tell us in their version message that we should not relay tx invs
204 // until they have initialized their bloom filter.
206 CSemaphoreGrant grantOutbound;
207 CCriticalSection cs_filter;
208 CBloomFilter* pfilter;
212 // Denial-of-service detection/prevention
213 // Key is IP address, value is banned-until-time
214 static std::map<CNetAddr, int64> setBanned;
215 static CCriticalSection cs_setBanned;
219 uint256 hashContinue;
220 CBlockIndex* pindexLastGetBlocksBegin;
221 uint256 hashLastGetBlocksEnd;
226 std::vector<CAddress> vAddrToSend;
227 std::set<CAddress> setAddrKnown;
229 std::set<uint256> setKnown;
231 // inventory based relay
232 mruset<CInv> setInventoryKnown;
233 std::vector<CInv> vInventoryToSend;
234 CCriticalSection cs_inventory;
235 std::multimap<int64, CInv> mapAskFor;
237 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : ssSend(SER_NETWORK, MIN_PROTO_VERSION)
241 nRecvVersion = MIN_PROTO_VERSION;
246 nLastSendEmpty = GetTime();
247 nTimeConnected = GetTime();
249 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
253 fClient = false; // set by version message
254 fInbound = fInboundIn;
255 fNetworkNode = false;
256 fSuccessfullyConnected = false;
262 pindexLastGetBlocksBegin = 0;
263 hashLastGetBlocksEnd = 0;
264 nStartingHeight = -1;
269 setInventoryKnown.max_size(SendBufferSize() / 1000);
270 pfilter = new CBloomFilter();
272 // Be shy and don't send version until we hear
273 if (hSocket != INVALID_SOCKET && !fInbound)
279 if (hSocket != INVALID_SOCKET)
281 closesocket(hSocket);
282 hSocket = INVALID_SOCKET;
290 void operator=(const CNode&);
296 assert(nRefCount >= 0);
300 // requires LOCK(cs_vRecvMsg)
301 unsigned int GetTotalRecvSize()
303 unsigned int total = 0;
304 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
305 total += msg.vRecv.size() + 24;
309 // requires LOCK(cs_vRecvMsg)
310 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
312 // requires LOCK(cs_vRecvMsg)
313 void SetRecvVersion(int nVersionIn)
315 nRecvVersion = nVersionIn;
316 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
317 msg.SetVersion(nVersionIn);
333 void AddAddressKnown(const CAddress& addr)
335 setAddrKnown.insert(addr);
338 void PushAddress(const CAddress& addr)
340 // Known checking here is only to save space from duplicates.
341 // SendMessages will filter it again for knowns that were added
342 // after addresses were pushed.
343 if (addr.IsValid() && !setAddrKnown.count(addr))
344 vAddrToSend.push_back(addr);
348 void AddInventoryKnown(const CInv& inv)
352 setInventoryKnown.insert(inv);
356 void PushInventory(const CInv& inv)
360 if (!setInventoryKnown.count(inv))
361 vInventoryToSend.push_back(inv);
365 void AskFor(const CInv& inv)
367 // We're using mapAskFor as a priority queue,
368 // the key is the earliest time the request can be sent
370 limitedmap<CInv, int64>::const_iterator it = mapAlreadyAskedFor.find(inv);
371 if (it != mapAlreadyAskedFor.end())
372 nRequestTime = it->second;
375 LogPrint("net", "askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
377 // Make sure not to reuse time indexes to keep things in the same order
378 int64 nNow = (GetTime() - 1) * 1000000;
379 static int64 nLastTime;
381 nNow = std::max(nNow, nLastTime);
384 // Each retry is 2 minutes after the last
385 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
386 if (it != mapAlreadyAskedFor.end())
387 mapAlreadyAskedFor.update(it, nRequestTime);
389 mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
390 mapAskFor.insert(std::make_pair(nRequestTime, inv));
395 // TODO: Document the postcondition of this function. Is cs_vSend locked?
396 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
398 ENTER_CRITICAL_SECTION(cs_vSend);
399 assert(ssSend.size() == 0);
400 ssSend << CMessageHeader(pszCommand, 0);
401 LogPrint("net", "sending: %s ", pszCommand);
404 // TODO: Document the precondition of this function. Is cs_vSend locked?
405 void AbortMessage() UNLOCK_FUNCTION(cs_vSend)
409 LEAVE_CRITICAL_SECTION(cs_vSend);
411 LogPrint("net", "(aborted)\n");
414 // TODO: Document the precondition of this function. Is cs_vSend locked?
415 void EndMessage() UNLOCK_FUNCTION(cs_vSend)
417 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
419 LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
424 if (ssSend.size() == 0)
428 unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
429 memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
432 uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
433 unsigned int nChecksum = 0;
434 memcpy(&nChecksum, &hash, sizeof(nChecksum));
435 assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
436 memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
438 LogPrint("net", "(%d bytes)\n", nSize);
440 std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
441 ssSend.GetAndClear(*it);
442 nSendSize += (*it).size();
444 // If write queue empty, attempt "optimistic write"
445 if (it == vSendMsg.begin())
446 SocketSendData(this);
448 LEAVE_CRITICAL_SECTION(cs_vSend);
454 void PushMessage(const char* pszCommand)
458 BeginMessage(pszCommand);
468 template<typename T1>
469 void PushMessage(const char* pszCommand, const T1& a1)
473 BeginMessage(pszCommand);
484 template<typename T1, typename T2>
485 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
489 BeginMessage(pszCommand);
500 template<typename T1, typename T2, typename T3>
501 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
505 BeginMessage(pszCommand);
506 ssSend << a1 << a2 << a3;
516 template<typename T1, typename T2, typename T3, typename T4>
517 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
521 BeginMessage(pszCommand);
522 ssSend << a1 << a2 << a3 << a4;
532 template<typename T1, typename T2, typename T3, typename T4, typename T5>
533 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
537 BeginMessage(pszCommand);
538 ssSend << a1 << a2 << a3 << a4 << a5;
548 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
549 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
553 BeginMessage(pszCommand);
554 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
564 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
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)
569 BeginMessage(pszCommand);
570 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
580 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
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)
585 BeginMessage(pszCommand);
586 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
596 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
597 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)
601 BeginMessage(pszCommand);
602 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
612 bool IsSubscribed(unsigned int nChannel);
613 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
614 void CancelSubscribe(unsigned int nChannel);
615 void CloseSocketDisconnect();
619 // Denial-of-service detection/prevention
620 // The idea is to detect peers that are behaving
621 // badly and disconnect/ban them, but do it in a
622 // one-coding-mistake-won't-shatter-the-entire-network
624 // IMPORTANT: There should be nothing I can give a
625 // node that it will forward on that will make that
626 // node's peers drop it. If there is, an attacker
627 // can isolate a node and/or try to split the network.
628 // Dropping a node for sending stuff that is invalid
629 // now but might be valid in a later version is also
630 // dangerous, because it can cause a network split
631 // between nodes running old code and nodes running
633 static void ClearBanned(); // needed for unit testing
634 static bool IsBanned(CNetAddr ip);
635 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
636 void copyStats(CNodeStats &stats);
642 void RelayTransaction(const CTransaction& tx, const uint256& hash);
643 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);