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 <openssl/rand.h>
14 #include <arpa/inet.h>
23 class CRequestTracker;
26 extern int nBestHeight;
30 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
31 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
33 void AddOneShot(std::string strDest);
34 bool RecvLine(SOCKET hSocket, std::string& strLine);
35 bool GetMyExternalIP(CNetAddr& ipRet);
36 void AddressCurrentlyConnected(const CService& addr);
37 CNode* FindNode(const CNetAddr& ip);
38 CNode* FindNode(const CService& ip);
39 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64 nTimeout=0);
41 unsigned short GetListenPort();
42 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
43 void StartNode(void* parg);
48 LOCAL_NONE, // unknown
49 LOCAL_IF, // address a local interface listens on
50 LOCAL_BIND, // address explicit bound to
51 LOCAL_UPNP, // address reported by UPnP
52 LOCAL_IRC, // address reported by IRC (deprecated)
53 LOCAL_HTTP, // address reported by whatismyip.com and similar
54 LOCAL_MANUAL, // address explicitly specified (-externalip=)
59 void SetLimited(enum Network net, bool fLimited = true);
60 bool IsLimited(enum Network net);
61 bool IsLimited(const CNetAddr& addr);
62 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
63 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
64 bool SeenLocal(const CService& addr);
65 bool IsLocal(const CService& addr);
66 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
67 bool IsReachable(const CNetAddr &addr);
68 void SetReachable(enum Network net, bool fFlag = true);
69 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
81 void (*fn)(void*, CDataStream&);
84 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
100 THREAD_SOCKETHANDLER,
101 THREAD_OPENCONNECTIONS,
102 THREAD_MESSAGEHANDLER,
106 THREAD_ADDEDCONNECTIONS,
116 extern bool fDiscover;
117 extern bool fUseUPnP;
118 extern uint64 nLocalServices;
119 extern uint64 nLocalHostNonce;
120 extern CAddress addrSeenByPeer;
121 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
122 extern CAddrMan addrman;
124 extern std::vector<CNode*> vNodes;
125 extern CCriticalSection cs_vNodes;
126 extern std::map<CInv, CDataStream> mapRelay;
127 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
128 extern CCriticalSection cs_mapRelay;
129 extern std::map<CInv, int64> mapAlreadyAskedFor;
140 int64 nTimeConnected;
141 std::string addrName;
143 std::string strSubVer;
157 /** Information about a peer */
168 CCriticalSection cs_vSend;
169 CCriticalSection cs_vRecv;
172 int64 nLastSendEmpty;
173 int64 nTimeConnected;
175 unsigned int nMessageStart;
177 std::string addrName;
180 std::string strSubVer;
185 bool fSuccessfullyConnected;
187 CSemaphoreGrant grantOutbound;
191 // Denial-of-service detection/prevention
192 // Key is IP address, value is banned-until-time
193 static std::map<CNetAddr, int64> setBanned;
194 static CCriticalSection cs_setBanned;
199 std::map<uint256, CRequestTracker> mapRequests;
200 CCriticalSection cs_mapRequests;
201 uint256 hashContinue;
202 CBlockIndex* pindexLastGetBlocksBegin;
203 uint256 hashLastGetBlocksEnd;
208 std::vector<CAddress> vAddrToSend;
209 std::set<CAddress> setAddrKnown;
211 std::set<uint256> setKnown;
212 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
214 // inventory based relay
215 mruset<CInv> setInventoryKnown;
216 std::vector<CInv> vInventoryToSend;
217 CCriticalSection cs_inventory;
218 std::multimap<int64, CInv> mapAskFor;
220 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
228 nLastSendEmpty = GetTime();
229 nTimeConnected = GetTime();
233 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
237 fClient = false; // set by version message
238 fInbound = fInboundIn;
239 fNetworkNode = false;
240 fSuccessfullyConnected = false;
245 pindexLastGetBlocksBegin = 0;
246 hashLastGetBlocksEnd = 0;
247 nStartingHeight = -1;
251 hashCheckpointKnown = 0;
252 setInventoryKnown.max_size(SendBufferSize() / 1000);
254 // Be shy and don't send version until we hear
255 if (hSocket != INVALID_SOCKET && !fInbound)
261 if (hSocket != INVALID_SOCKET)
263 closesocket(hSocket);
264 hSocket = INVALID_SOCKET;
270 void operator=(const CNode&);
276 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
279 CNode* AddRef(int64 nTimeout=0)
282 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
295 void AddAddressKnown(const CAddress& addr)
297 setAddrKnown.insert(addr);
300 void PushAddress(const CAddress& addr)
302 // Known checking here is only to save space from duplicates.
303 // SendMessages will filter it again for knowns that were added
304 // after addresses were pushed.
305 if (addr.IsValid() && !setAddrKnown.count(addr))
306 vAddrToSend.push_back(addr);
310 void AddInventoryKnown(const CInv& inv)
314 setInventoryKnown.insert(inv);
318 void PushInventory(const CInv& inv)
322 if (!setInventoryKnown.count(inv))
323 vInventoryToSend.push_back(inv);
327 void AskFor(const CInv& inv)
329 // We're using mapAskFor as a priority queue,
330 // the key is the earliest time the request can be sent
331 int64& nRequestTime = mapAlreadyAskedFor[inv];
333 printf("askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
335 // Make sure not to reuse time indexes to keep things in the same order
336 int64 nNow = (GetTime() - 1) * 1000000;
337 static int64 nLastTime;
339 nNow = std::max(nNow, nLastTime);
342 // Each retry is 2 minutes after the last
343 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
344 mapAskFor.insert(std::make_pair(nRequestTime, inv));
349 void BeginMessage(const char* pszCommand)
351 ENTER_CRITICAL_SECTION(cs_vSend);
352 if (nHeaderStart != -1)
354 nHeaderStart = vSend.size();
355 vSend << CMessageHeader(pszCommand, 0);
356 nMessageStart = vSend.size();
358 printf("sending: %s ", pszCommand);
363 if (nHeaderStart < 0)
365 vSend.resize(nHeaderStart);
368 LEAVE_CRITICAL_SECTION(cs_vSend);
371 printf("(aborted)\n");
376 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
378 printf("dropmessages DROPPING SEND MESSAGE\n");
383 if (nHeaderStart < 0)
387 unsigned int nSize = vSend.size() - nMessageStart;
388 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
391 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
392 unsigned int nChecksum = 0;
393 memcpy(&nChecksum, &hash, sizeof(nChecksum));
394 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
395 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
398 printf("(%d bytes)\n", nSize);
403 LEAVE_CRITICAL_SECTION(cs_vSend);
406 void EndMessageAbortIfEmpty()
408 if (nHeaderStart < 0)
410 int nSize = vSend.size() - nMessageStart;
422 void PushMessage(const char* pszCommand)
426 BeginMessage(pszCommand);
436 template<typename T1>
437 void PushMessage(const char* pszCommand, const T1& a1)
441 BeginMessage(pszCommand);
452 template<typename T1, typename T2>
453 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
457 BeginMessage(pszCommand);
468 template<typename T1, typename T2, typename T3>
469 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
473 BeginMessage(pszCommand);
474 vSend << a1 << a2 << a3;
484 template<typename T1, typename T2, typename T3, typename T4>
485 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
489 BeginMessage(pszCommand);
490 vSend << a1 << a2 << a3 << a4;
500 template<typename T1, typename T2, typename T3, typename T4, typename T5>
501 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
505 BeginMessage(pszCommand);
506 vSend << a1 << a2 << a3 << a4 << a5;
516 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
517 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
521 BeginMessage(pszCommand);
522 vSend << a1 << a2 << a3 << a4 << a5 << a6;
532 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
533 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)
537 BeginMessage(pszCommand);
538 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
548 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
549 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)
553 BeginMessage(pszCommand);
554 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
564 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
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, const T8& a8, const T9& a9)
569 BeginMessage(pszCommand);
570 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
581 void PushRequest(const char* pszCommand,
582 void (*fn)(void*, CDataStream&), void* param1)
585 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
588 LOCK(cs_mapRequests);
589 mapRequests[hashReply] = CRequestTracker(fn, param1);
592 PushMessage(pszCommand, hashReply);
595 template<typename T1>
596 void PushRequest(const char* pszCommand, const T1& a1,
597 void (*fn)(void*, CDataStream&), void* param1)
600 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
603 LOCK(cs_mapRequests);
604 mapRequests[hashReply] = CRequestTracker(fn, param1);
607 PushMessage(pszCommand, hashReply, a1);
610 template<typename T1, typename T2>
611 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
612 void (*fn)(void*, CDataStream&), void* param1)
615 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
618 LOCK(cs_mapRequests);
619 mapRequests[hashReply] = CRequestTracker(fn, param1);
622 PushMessage(pszCommand, hashReply, a1, a2);
627 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
628 bool IsSubscribed(unsigned int nChannel);
629 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
630 void CancelSubscribe(unsigned int nChannel);
631 void CloseSocketDisconnect();
635 // Denial-of-service detection/prevention
636 // The idea is to detect peers that are behaving
637 // badly and disconnect/ban them, but do it in a
638 // one-coding-mistake-won't-shatter-the-entire-network
640 // IMPORTANT: There should be nothing I can give a
641 // node that it will forward on that will make that
642 // node's peers drop it. If there is, an attacker
643 // can isolate a node and/or try to split the network.
644 // Dropping a node for sending stuff that is invalid
645 // now but might be valid in a later version is also
646 // dangerous, because it can cause a network split
647 // between nodes running old code and nodes running
649 static void ClearBanned(); // needed for unit testing
650 static bool IsBanned(CNetAddr ip);
651 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
652 void copyStats(CNodeStats &stats);
655 inline void RelayInventory(const CInv& inv)
657 // Put on lists to offer to the other nodes
660 BOOST_FOREACH(CNode* pnode, vNodes)
661 pnode->PushInventory(inv);
666 void RelayTransaction(const CTransaction& tx, const uint256& hash);
667 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);