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;
34 inline unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
35 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
37 void AddOneShot(std::string strDest);
38 bool RecvLine(SOCKET hSocket, std::string& strLine);
39 bool GetMyExternalIP(CNetAddr& ipRet);
40 void AddressCurrentlyConnected(const CService& addr);
41 CNode* FindNode(const CNetAddr& ip);
42 CNode* FindNode(const CService& ip);
43 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL);
44 void MapPort(bool fUseUPnP);
45 unsigned short GetListenPort();
46 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
47 void StartNode(boost::thread_group& threadGroup);
49 void SocketSendData(CNode *pnode);
51 // Signals for message handling
54 boost::signals2::signal<int ()> GetHeight;
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;
131 bool in_data; // parsing header (false) or data (true)
133 CDataStream hdrbuf; // partially received header
134 CMessageHeader hdr; // complete header
135 unsigned int nHdrPos;
137 CDataStream vRecv; // received message data
138 unsigned int nDataPos;
140 CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
147 bool complete() const
151 return (hdr.nMessageSize == nDataPos);
154 void SetVersion(int nVersionIn)
156 hdrbuf.SetVersion(nVersionIn);
157 vRecv.SetVersion(nVersionIn);
160 int readHeader(const char *pch, unsigned int nBytes);
161 int readData(const char *pch, unsigned int nBytes);
168 /** Information about a peer */
176 size_t nSendSize; // total size of all vSendMsg entries
177 size_t nSendOffset; // offset inside the first vSendMsg already sent
179 std::deque<CSerializeData> vSendMsg;
180 CCriticalSection cs_vSend;
182 std::deque<CInv> vRecvGetData;
183 std::deque<CNetMessage> vRecvMsg;
184 CCriticalSection cs_vRecvMsg;
190 int64 nLastSendEmpty;
191 int64 nTimeConnected;
193 std::string addrName;
196 std::string strSubVer;
201 bool fSuccessfullyConnected;
203 // We use fRelayTxes for two purposes -
204 // a) it allows us to not relay tx invs before receiving the peer's version message
205 // b) the peer may tell us in their version message that we should not relay tx invs
206 // until they have initialized their bloom filter.
208 CSemaphoreGrant grantOutbound;
209 CCriticalSection cs_filter;
210 CBloomFilter* pfilter;
214 // Denial-of-service detection/prevention
215 // Key is IP address, value is banned-until-time
216 static std::map<CNetAddr, int64> setBanned;
217 static CCriticalSection cs_setBanned;
221 uint256 hashContinue;
222 CBlockIndex* pindexLastGetBlocksBegin;
223 uint256 hashLastGetBlocksEnd;
228 std::vector<CAddress> vAddrToSend;
229 std::set<CAddress> setAddrKnown;
231 std::set<uint256> setKnown;
233 // inventory based relay
234 mruset<CInv> setInventoryKnown;
235 std::vector<CInv> vInventoryToSend;
236 CCriticalSection cs_inventory;
237 std::multimap<int64, CInv> mapAskFor;
239 // Ping time measurement
240 uint64 nPingNonceSent;
241 int64 nPingUsecStart;
245 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : ssSend(SER_NETWORK, MIN_PROTO_VERSION)
249 nRecvVersion = MIN_PROTO_VERSION;
254 nLastSendEmpty = GetTime();
255 nTimeConnected = GetTime();
257 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
261 fClient = false; // set by version message
262 fInbound = fInboundIn;
263 fNetworkNode = false;
264 fSuccessfullyConnected = false;
270 pindexLastGetBlocksBegin = 0;
271 hashLastGetBlocksEnd = 0;
272 nStartingHeight = -1;
277 setInventoryKnown.max_size(SendBufferSize() / 1000);
278 pfilter = new CBloomFilter();
284 // Be shy and don't send version until we hear
285 if (hSocket != INVALID_SOCKET && !fInbound)
291 if (hSocket != INVALID_SOCKET)
293 closesocket(hSocket);
294 hSocket = INVALID_SOCKET;
301 // Network usage totals
302 static CCriticalSection cs_totalBytesRecv;
303 static CCriticalSection cs_totalBytesSent;
304 static uint64 nTotalBytesRecv;
305 static uint64 nTotalBytesSent;
308 void operator=(const CNode&);
315 assert(nRefCount >= 0);
319 // requires LOCK(cs_vRecvMsg)
320 unsigned int GetTotalRecvSize()
322 unsigned int total = 0;
323 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
324 total += msg.vRecv.size() + 24;
328 // requires LOCK(cs_vRecvMsg)
329 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
331 // requires LOCK(cs_vRecvMsg)
332 void SetRecvVersion(int nVersionIn)
334 nRecvVersion = nVersionIn;
335 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
336 msg.SetVersion(nVersionIn);
352 void AddAddressKnown(const CAddress& addr)
354 setAddrKnown.insert(addr);
357 void PushAddress(const CAddress& addr)
359 // Known checking here is only to save space from duplicates.
360 // SendMessages will filter it again for knowns that were added
361 // after addresses were pushed.
362 if (addr.IsValid() && !setAddrKnown.count(addr))
363 vAddrToSend.push_back(addr);
367 void AddInventoryKnown(const CInv& inv)
371 setInventoryKnown.insert(inv);
375 void PushInventory(const CInv& inv)
379 if (!setInventoryKnown.count(inv))
380 vInventoryToSend.push_back(inv);
384 void AskFor(const CInv& inv)
386 // We're using mapAskFor as a priority queue,
387 // the key is the earliest time the request can be sent
389 limitedmap<CInv, int64>::const_iterator it = mapAlreadyAskedFor.find(inv);
390 if (it != mapAlreadyAskedFor.end())
391 nRequestTime = it->second;
394 LogPrint("net", "askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
396 // Make sure not to reuse time indexes to keep things in the same order
397 int64 nNow = (GetTime() - 1) * 1000000;
398 static int64 nLastTime;
400 nNow = std::max(nNow, nLastTime);
403 // Each retry is 2 minutes after the last
404 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
405 if (it != mapAlreadyAskedFor.end())
406 mapAlreadyAskedFor.update(it, nRequestTime);
408 mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
409 mapAskFor.insert(std::make_pair(nRequestTime, inv));
414 // TODO: Document the postcondition of this function. Is cs_vSend locked?
415 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
417 ENTER_CRITICAL_SECTION(cs_vSend);
418 assert(ssSend.size() == 0);
419 ssSend << CMessageHeader(pszCommand, 0);
420 LogPrint("net", "sending: %s ", pszCommand);
423 // TODO: Document the precondition of this function. Is cs_vSend locked?
424 void AbortMessage() UNLOCK_FUNCTION(cs_vSend)
428 LEAVE_CRITICAL_SECTION(cs_vSend);
430 LogPrint("net", "(aborted)\n");
433 // TODO: Document the precondition of this function. Is cs_vSend locked?
434 void EndMessage() UNLOCK_FUNCTION(cs_vSend)
436 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
438 LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
443 if (ssSend.size() == 0)
447 unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
448 memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
451 uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
452 unsigned int nChecksum = 0;
453 memcpy(&nChecksum, &hash, sizeof(nChecksum));
454 assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
455 memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
457 LogPrint("net", "(%d bytes)\n", nSize);
459 std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
460 ssSend.GetAndClear(*it);
461 nSendSize += (*it).size();
463 // If write queue empty, attempt "optimistic write"
464 if (it == vSendMsg.begin())
465 SocketSendData(this);
467 LEAVE_CRITICAL_SECTION(cs_vSend);
473 void PushMessage(const char* pszCommand)
477 BeginMessage(pszCommand);
487 template<typename T1>
488 void PushMessage(const char* pszCommand, const T1& a1)
492 BeginMessage(pszCommand);
503 template<typename T1, typename T2>
504 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
508 BeginMessage(pszCommand);
519 template<typename T1, typename T2, typename T3>
520 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
524 BeginMessage(pszCommand);
525 ssSend << a1 << a2 << a3;
535 template<typename T1, typename T2, typename T3, typename T4>
536 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
540 BeginMessage(pszCommand);
541 ssSend << a1 << a2 << a3 << a4;
551 template<typename T1, typename T2, typename T3, typename T4, typename T5>
552 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
556 BeginMessage(pszCommand);
557 ssSend << a1 << a2 << a3 << a4 << a5;
567 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
568 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
572 BeginMessage(pszCommand);
573 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
583 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
584 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)
588 BeginMessage(pszCommand);
589 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
599 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
600 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)
604 BeginMessage(pszCommand);
605 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
615 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
616 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)
620 BeginMessage(pszCommand);
621 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
631 bool IsSubscribed(unsigned int nChannel);
632 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
633 void CancelSubscribe(unsigned int nChannel);
634 void CloseSocketDisconnect();
638 // Denial-of-service detection/prevention
639 // The idea is to detect peers that are behaving
640 // badly and disconnect/ban them, but do it in a
641 // one-coding-mistake-won't-shatter-the-entire-network
643 // IMPORTANT: There should be nothing I can give a
644 // node that it will forward on that will make that
645 // node's peers drop it. If there is, an attacker
646 // can isolate a node and/or try to split the network.
647 // Dropping a node for sending stuff that is invalid
648 // now but might be valid in a later version is also
649 // dangerous, because it can cause a network split
650 // between nodes running old code and nodes running
652 static void ClearBanned(); // needed for unit testing
653 static bool IsBanned(CNetAddr ip);
654 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
655 void copyStats(CNodeStats &stats);
658 static void RecordBytesRecv(uint64 bytes);
659 static void RecordBytesSent(uint64 bytes);
661 static uint64 GetTotalBytesRecv();
662 static uint64 GetTotalBytesSent();
668 void RelayTransaction(const CTransaction& tx, const uint256& hash);
669 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);