1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 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;
124 std::string addrLocal;
132 bool in_data; // parsing header (false) or data (true)
134 CDataStream hdrbuf; // partially received header
135 CMessageHeader hdr; // complete header
136 unsigned int nHdrPos;
138 CDataStream vRecv; // received message data
139 unsigned int nDataPos;
141 CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
148 bool complete() const
152 return (hdr.nMessageSize == nDataPos);
155 void SetVersion(int nVersionIn)
157 hdrbuf.SetVersion(nVersionIn);
158 vRecv.SetVersion(nVersionIn);
161 int readHeader(const char *pch, unsigned int nBytes);
162 int readData(const char *pch, unsigned int nBytes);
169 /** Information about a peer */
177 size_t nSendSize; // total size of all vSendMsg entries
178 size_t nSendOffset; // offset inside the first vSendMsg already sent
180 std::deque<CSerializeData> vSendMsg;
181 CCriticalSection cs_vSend;
183 std::deque<CInv> vRecvGetData;
184 std::deque<CNetMessage> vRecvMsg;
185 CCriticalSection cs_vRecvMsg;
191 int64 nLastSendEmpty;
192 int64 nTimeConnected;
194 std::string addrName;
197 std::string strSubVer;
202 bool fSuccessfullyConnected;
204 // We use fRelayTxes for two purposes -
205 // a) it allows us to not relay tx invs before receiving the peer's version message
206 // b) the peer may tell us in their version message that we should not relay tx invs
207 // until they have initialized their bloom filter.
209 CSemaphoreGrant grantOutbound;
210 CCriticalSection cs_filter;
211 CBloomFilter* pfilter;
215 // Denial-of-service detection/prevention
216 // Key is IP address, value is banned-until-time
217 static std::map<CNetAddr, int64> setBanned;
218 static CCriticalSection cs_setBanned;
221 // Basic fuzz-testing
222 void Fuzz(int nChance); // modifies ssSend
225 uint256 hashContinue;
226 CBlockIndex* pindexLastGetBlocksBegin;
227 uint256 hashLastGetBlocksEnd;
232 std::vector<CAddress> vAddrToSend;
233 std::set<CAddress> setAddrKnown;
235 std::set<uint256> setKnown;
237 // inventory based relay
238 mruset<CInv> setInventoryKnown;
239 std::vector<CInv> vInventoryToSend;
240 CCriticalSection cs_inventory;
241 std::multimap<int64, CInv> mapAskFor;
243 // Ping time measurement
244 uint64 nPingNonceSent;
245 int64 nPingUsecStart;
249 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : ssSend(SER_NETWORK, MIN_PROTO_VERSION)
253 nRecvVersion = MIN_PROTO_VERSION;
258 nLastSendEmpty = GetTime();
259 nTimeConnected = GetTime();
261 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
265 fClient = false; // set by version message
266 fInbound = fInboundIn;
267 fNetworkNode = false;
268 fSuccessfullyConnected = false;
274 pindexLastGetBlocksBegin = 0;
275 hashLastGetBlocksEnd = 0;
276 nStartingHeight = -1;
281 setInventoryKnown.max_size(SendBufferSize() / 1000);
282 pfilter = new CBloomFilter();
288 // Be shy and don't send version until we hear
289 if (hSocket != INVALID_SOCKET && !fInbound)
295 if (hSocket != INVALID_SOCKET)
297 closesocket(hSocket);
298 hSocket = INVALID_SOCKET;
305 // Network usage totals
306 static CCriticalSection cs_totalBytesRecv;
307 static CCriticalSection cs_totalBytesSent;
308 static uint64 nTotalBytesRecv;
309 static uint64 nTotalBytesSent;
312 void operator=(const CNode&);
319 assert(nRefCount >= 0);
323 // requires LOCK(cs_vRecvMsg)
324 unsigned int GetTotalRecvSize()
326 unsigned int total = 0;
327 BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
328 total += msg.vRecv.size() + 24;
332 // requires LOCK(cs_vRecvMsg)
333 bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
335 // requires LOCK(cs_vRecvMsg)
336 void SetRecvVersion(int nVersionIn)
338 nRecvVersion = nVersionIn;
339 BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
340 msg.SetVersion(nVersionIn);
356 void AddAddressKnown(const CAddress& addr)
358 setAddrKnown.insert(addr);
361 void PushAddress(const CAddress& addr)
363 // Known checking here is only to save space from duplicates.
364 // SendMessages will filter it again for knowns that were added
365 // after addresses were pushed.
366 if (addr.IsValid() && !setAddrKnown.count(addr))
367 vAddrToSend.push_back(addr);
371 void AddInventoryKnown(const CInv& inv)
375 setInventoryKnown.insert(inv);
379 void PushInventory(const CInv& inv)
383 if (!setInventoryKnown.count(inv))
384 vInventoryToSend.push_back(inv);
388 void AskFor(const CInv& inv)
390 // We're using mapAskFor as a priority queue,
391 // the key is the earliest time the request can be sent
393 limitedmap<CInv, int64>::const_iterator it = mapAlreadyAskedFor.find(inv);
394 if (it != mapAlreadyAskedFor.end())
395 nRequestTime = it->second;
398 LogPrint("net", "askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
400 // Make sure not to reuse time indexes to keep things in the same order
401 int64 nNow = (GetTime() - 1) * 1000000;
402 static int64 nLastTime;
404 nNow = std::max(nNow, nLastTime);
407 // Each retry is 2 minutes after the last
408 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
409 if (it != mapAlreadyAskedFor.end())
410 mapAlreadyAskedFor.update(it, nRequestTime);
412 mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
413 mapAskFor.insert(std::make_pair(nRequestTime, inv));
418 // TODO: Document the postcondition of this function. Is cs_vSend locked?
419 void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
421 ENTER_CRITICAL_SECTION(cs_vSend);
422 assert(ssSend.size() == 0);
423 ssSend << CMessageHeader(pszCommand, 0);
424 LogPrint("net", "sending: %s ", pszCommand);
427 // TODO: Document the precondition of this function. Is cs_vSend locked?
428 void AbortMessage() UNLOCK_FUNCTION(cs_vSend)
432 LEAVE_CRITICAL_SECTION(cs_vSend);
434 LogPrint("net", "(aborted)\n");
437 // TODO: Document the precondition of this function. Is cs_vSend locked?
438 void EndMessage() UNLOCK_FUNCTION(cs_vSend)
440 // The -*messagestest options are intentionally not documented in the help message,
441 // since they are only used during development to debug the networking code and are
442 // not intended for end-users.
443 if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0)
445 LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
449 if (mapArgs.count("-fuzzmessagestest"))
450 Fuzz(GetArg("-fuzzmessagestest", 10));
452 if (ssSend.size() == 0)
456 unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
457 memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
460 uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
461 unsigned int nChecksum = 0;
462 memcpy(&nChecksum, &hash, sizeof(nChecksum));
463 assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
464 memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
466 LogPrint("net", "(%d bytes)\n", nSize);
468 std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
469 ssSend.GetAndClear(*it);
470 nSendSize += (*it).size();
472 // If write queue empty, attempt "optimistic write"
473 if (it == vSendMsg.begin())
474 SocketSendData(this);
476 LEAVE_CRITICAL_SECTION(cs_vSend);
482 void PushMessage(const char* pszCommand)
486 BeginMessage(pszCommand);
496 template<typename T1>
497 void PushMessage(const char* pszCommand, const T1& a1)
501 BeginMessage(pszCommand);
512 template<typename T1, typename T2>
513 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
517 BeginMessage(pszCommand);
528 template<typename T1, typename T2, typename T3>
529 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
533 BeginMessage(pszCommand);
534 ssSend << a1 << a2 << a3;
544 template<typename T1, typename T2, typename T3, typename T4>
545 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
549 BeginMessage(pszCommand);
550 ssSend << a1 << a2 << a3 << a4;
560 template<typename T1, typename T2, typename T3, typename T4, typename T5>
561 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
565 BeginMessage(pszCommand);
566 ssSend << a1 << a2 << a3 << a4 << a5;
576 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
577 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
581 BeginMessage(pszCommand);
582 ssSend << a1 << a2 << a3 << a4 << a5 << a6;
592 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
593 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)
597 BeginMessage(pszCommand);
598 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
608 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
609 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)
613 BeginMessage(pszCommand);
614 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
624 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
625 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)
629 BeginMessage(pszCommand);
630 ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
640 bool IsSubscribed(unsigned int nChannel);
641 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
642 void CancelSubscribe(unsigned int nChannel);
643 void CloseSocketDisconnect();
647 // Denial-of-service detection/prevention
648 // The idea is to detect peers that are behaving
649 // badly and disconnect/ban them, but do it in a
650 // one-coding-mistake-won't-shatter-the-entire-network
652 // IMPORTANT: There should be nothing I can give a
653 // node that it will forward on that will make that
654 // node's peers drop it. If there is, an attacker
655 // can isolate a node and/or try to split the network.
656 // Dropping a node for sending stuff that is invalid
657 // now but might be valid in a later version is also
658 // dangerous, because it can cause a network split
659 // between nodes running old code and nodes running
661 static void ClearBanned(); // needed for unit testing
662 static bool IsBanned(CNetAddr ip);
663 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
664 void copyStats(CNodeStats &stats);
667 static void RecordBytesRecv(uint64 bytes);
668 static void RecordBytesSent(uint64 bytes);
670 static uint64 GetTotalBytesRecv();
671 static uint64 GetTotalBytesSent();
677 void RelayTransaction(const CTransaction& tx, const uint256& hash);
678 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);