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;
154 /** Information about a peer */
163 CCriticalSection cs_vSend;
164 CCriticalSection cs_vRecv;
167 int64 nLastSendEmpty;
168 int64 nTimeConnected;
170 unsigned int nMessageStart;
172 std::string addrName;
175 std::string strSubVer;
180 bool fSuccessfullyConnected;
182 CSemaphoreGrant grantOutbound;
186 // Denial-of-service detection/prevention
187 // Key is IP address, value is banned-until-time
188 static std::map<CNetAddr, int64> setBanned;
189 static CCriticalSection cs_setBanned;
194 std::map<uint256, CRequestTracker> mapRequests;
195 CCriticalSection cs_mapRequests;
196 uint256 hashContinue;
197 CBlockIndex* pindexLastGetBlocksBegin;
198 uint256 hashLastGetBlocksEnd;
202 std::vector<CAddress> vAddrToSend;
203 std::set<CAddress> setAddrKnown;
205 std::set<uint256> setKnown;
206 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
208 // inventory based relay
209 mruset<CInv> setInventoryKnown;
210 std::vector<CInv> vInventoryToSend;
211 CCriticalSection cs_inventory;
212 std::multimap<int64, CInv> mapAskFor;
214 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
220 nLastSendEmpty = GetTime();
221 nTimeConnected = GetTime();
225 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
229 fClient = false; // set by version message
230 fInbound = fInboundIn;
231 fNetworkNode = false;
232 fSuccessfullyConnected = false;
237 pindexLastGetBlocksBegin = 0;
238 hashLastGetBlocksEnd = 0;
239 nStartingHeight = -1;
242 hashCheckpointKnown = 0;
243 setInventoryKnown.max_size(SendBufferSize() / 1000);
245 // Be shy and don't send version until we hear
246 if (hSocket != INVALID_SOCKET && !fInbound)
252 if (hSocket != INVALID_SOCKET)
254 closesocket(hSocket);
255 hSocket = INVALID_SOCKET;
261 void operator=(const CNode&);
267 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
270 CNode* AddRef(int64 nTimeout=0)
273 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
286 void AddAddressKnown(const CAddress& addr)
288 setAddrKnown.insert(addr);
291 void PushAddress(const CAddress& addr)
293 // Known checking here is only to save space from duplicates.
294 // SendMessages will filter it again for knowns that were added
295 // after addresses were pushed.
296 if (addr.IsValid() && !setAddrKnown.count(addr))
297 vAddrToSend.push_back(addr);
301 void AddInventoryKnown(const CInv& inv)
305 setInventoryKnown.insert(inv);
309 void PushInventory(const CInv& inv)
313 if (!setInventoryKnown.count(inv))
314 vInventoryToSend.push_back(inv);
318 void AskFor(const CInv& inv)
320 // We're using mapAskFor as a priority queue,
321 // the key is the earliest time the request can be sent
322 int64& nRequestTime = mapAlreadyAskedFor[inv];
324 printf("askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
326 // Make sure not to reuse time indexes to keep things in the same order
327 int64 nNow = (GetTime() - 1) * 1000000;
328 static int64 nLastTime;
330 nNow = std::max(nNow, nLastTime);
333 // Each retry is 2 minutes after the last
334 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
335 mapAskFor.insert(std::make_pair(nRequestTime, inv));
340 void BeginMessage(const char* pszCommand)
342 ENTER_CRITICAL_SECTION(cs_vSend);
343 if (nHeaderStart != -1)
345 nHeaderStart = vSend.size();
346 vSend << CMessageHeader(pszCommand, 0);
347 nMessageStart = vSend.size();
349 printf("sending: %s ", pszCommand);
354 if (nHeaderStart < 0)
356 vSend.resize(nHeaderStart);
359 LEAVE_CRITICAL_SECTION(cs_vSend);
362 printf("(aborted)\n");
367 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
369 printf("dropmessages DROPPING SEND MESSAGE\n");
374 if (nHeaderStart < 0)
378 unsigned int nSize = vSend.size() - nMessageStart;
379 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
382 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
383 unsigned int nChecksum = 0;
384 memcpy(&nChecksum, &hash, sizeof(nChecksum));
385 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
386 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
389 printf("(%d bytes)\n", nSize);
394 LEAVE_CRITICAL_SECTION(cs_vSend);
397 void EndMessageAbortIfEmpty()
399 if (nHeaderStart < 0)
401 int nSize = vSend.size() - nMessageStart;
413 void PushMessage(const char* pszCommand)
417 BeginMessage(pszCommand);
427 template<typename T1>
428 void PushMessage(const char* pszCommand, const T1& a1)
432 BeginMessage(pszCommand);
443 template<typename T1, typename T2>
444 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
448 BeginMessage(pszCommand);
459 template<typename T1, typename T2, typename T3>
460 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
464 BeginMessage(pszCommand);
465 vSend << a1 << a2 << a3;
475 template<typename T1, typename T2, typename T3, typename T4>
476 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
480 BeginMessage(pszCommand);
481 vSend << a1 << a2 << a3 << a4;
491 template<typename T1, typename T2, typename T3, typename T4, typename T5>
492 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
496 BeginMessage(pszCommand);
497 vSend << a1 << a2 << a3 << a4 << a5;
507 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
508 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
512 BeginMessage(pszCommand);
513 vSend << a1 << a2 << a3 << a4 << a5 << a6;
523 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
524 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)
528 BeginMessage(pszCommand);
529 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
539 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
540 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)
544 BeginMessage(pszCommand);
545 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
555 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
556 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)
560 BeginMessage(pszCommand);
561 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
572 void PushRequest(const char* pszCommand,
573 void (*fn)(void*, CDataStream&), void* param1)
576 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
579 LOCK(cs_mapRequests);
580 mapRequests[hashReply] = CRequestTracker(fn, param1);
583 PushMessage(pszCommand, hashReply);
586 template<typename T1>
587 void PushRequest(const char* pszCommand, const T1& a1,
588 void (*fn)(void*, CDataStream&), void* param1)
591 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
594 LOCK(cs_mapRequests);
595 mapRequests[hashReply] = CRequestTracker(fn, param1);
598 PushMessage(pszCommand, hashReply, a1);
601 template<typename T1, typename T2>
602 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
603 void (*fn)(void*, CDataStream&), void* param1)
606 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
609 LOCK(cs_mapRequests);
610 mapRequests[hashReply] = CRequestTracker(fn, param1);
613 PushMessage(pszCommand, hashReply, a1, a2);
618 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
619 bool IsSubscribed(unsigned int nChannel);
620 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
621 void CancelSubscribe(unsigned int nChannel);
622 void CloseSocketDisconnect();
626 // Denial-of-service detection/prevention
627 // The idea is to detect peers that are behaving
628 // badly and disconnect/ban them, but do it in a
629 // one-coding-mistake-won't-shatter-the-entire-network
631 // IMPORTANT: There should be nothing I can give a
632 // node that it will forward on that will make that
633 // node's peers drop it. If there is, an attacker
634 // can isolate a node and/or try to split the network.
635 // Dropping a node for sending stuff that is invalid
636 // now but might be valid in a later version is also
637 // dangerous, because it can cause a network split
638 // between nodes running old code and nodes running
640 static void ClearBanned(); // needed for unit testing
641 static bool IsBanned(CNetAddr ip);
642 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
643 void copyStats(CNodeStats &stats);
646 inline void RelayInventory(const CInv& inv)
648 // Put on lists to offer to the other nodes
651 BOOST_FOREACH(CNode* pnode, vNodes)
652 pnode->PushInventory(inv);
657 void RelayTransaction(const CTransaction& tx, const uint256& hash);
658 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);