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>
22 class CRequestTracker;
25 extern int nBestHeight;
29 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
30 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
32 void AddOneShot(std::string strDest);
33 bool RecvLine(SOCKET hSocket, std::string& strLine);
34 bool GetMyExternalIP(CNetAddr& ipRet);
35 void AddressCurrentlyConnected(const CService& addr);
36 CNode* FindNode(const CNetAddr& ip);
37 CNode* FindNode(const CService& ip);
38 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64 nTimeout=0);
40 unsigned short GetListenPort();
41 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
42 void StartNode(void* parg);
47 LOCAL_NONE, // unknown
48 LOCAL_IF, // address a local interface listens on
49 LOCAL_BIND, // address explicit bound to
50 LOCAL_UPNP, // address reported by UPnP
51 LOCAL_IRC, // address reported by IRC (deprecated)
52 LOCAL_HTTP, // address reported by whatismyip.com and similar
53 LOCAL_MANUAL, // address explicitly specified (-externalip=)
58 void SetLimited(enum Network net, bool fLimited = true);
59 bool IsLimited(enum Network net);
60 bool IsLimited(const CNetAddr& addr);
61 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
62 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
63 bool SeenLocal(const CService& addr);
64 bool IsLocal(const CService& addr);
65 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
66 bool IsReachable(const CNetAddr &addr);
67 void SetReachable(enum Network net, bool fFlag = true);
68 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
80 void (*fn)(void*, CDataStream&);
83 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
100 THREAD_OPENCONNECTIONS,
101 THREAD_MESSAGEHANDLER,
106 THREAD_ADDEDCONNECTIONS,
115 extern bool fDiscover;
116 extern bool fUseUPnP;
117 extern uint64 nLocalServices;
118 extern uint64 nLocalHostNonce;
119 extern CAddress addrSeenByPeer;
120 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
121 extern CAddrMan addrman;
123 extern std::vector<CNode*> vNodes;
124 extern CCriticalSection cs_vNodes;
125 extern std::map<CInv, CDataStream> mapRelay;
126 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
127 extern CCriticalSection cs_mapRelay;
128 extern std::map<CInv, int64> mapAlreadyAskedFor;
139 int64 nTimeConnected;
140 std::string addrName;
142 std::string strSubVer;
153 /** Information about a peer */
162 CCriticalSection cs_vSend;
163 CCriticalSection cs_vRecv;
166 int64 nLastSendEmpty;
167 int64 nTimeConnected;
169 unsigned int nMessageStart;
171 std::string addrName;
174 std::string strSubVer;
179 bool fSuccessfullyConnected;
181 CSemaphoreGrant grantOutbound;
185 // Denial-of-service detection/prevention
186 // Key is IP address, value is banned-until-time
187 static std::map<CNetAddr, int64> setBanned;
188 static CCriticalSection cs_setBanned;
193 std::map<uint256, CRequestTracker> mapRequests;
194 CCriticalSection cs_mapRequests;
195 uint256 hashContinue;
196 CBlockIndex* pindexLastGetBlocksBegin;
197 uint256 hashLastGetBlocksEnd;
201 std::vector<CAddress> vAddrToSend;
202 std::set<CAddress> setAddrKnown;
204 std::set<uint256> setKnown;
205 uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
207 // inventory based relay
208 mruset<CInv> setInventoryKnown;
209 std::vector<CInv> vInventoryToSend;
210 CCriticalSection cs_inventory;
211 std::multimap<int64, CInv> mapAskFor;
213 CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
219 nLastSendEmpty = GetTime();
220 nTimeConnected = GetTime();
224 addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
228 fClient = false; // set by version message
229 fInbound = fInboundIn;
230 fNetworkNode = false;
231 fSuccessfullyConnected = false;
236 pindexLastGetBlocksBegin = 0;
237 hashLastGetBlocksEnd = 0;
238 nStartingHeight = -1;
241 hashCheckpointKnown = 0;
242 setInventoryKnown.max_size(SendBufferSize() / 1000);
244 // Be shy and don't send version until we hear
251 if (hSocket != INVALID_SOCKET)
253 closesocket(hSocket);
254 hSocket = INVALID_SOCKET;
260 void operator=(const CNode&);
266 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
269 CNode* AddRef(int64 nTimeout=0)
272 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
285 void AddAddressKnown(const CAddress& addr)
287 setAddrKnown.insert(addr);
290 void PushAddress(const CAddress& addr)
292 // Known checking here is only to save space from duplicates.
293 // SendMessages will filter it again for knowns that were added
294 // after addresses were pushed.
295 if (addr.IsValid() && !setAddrKnown.count(addr))
296 vAddrToSend.push_back(addr);
300 void AddInventoryKnown(const CInv& inv)
304 setInventoryKnown.insert(inv);
308 void PushInventory(const CInv& inv)
312 if (!setInventoryKnown.count(inv))
313 vInventoryToSend.push_back(inv);
317 void AskFor(const CInv& inv)
319 // We're using mapAskFor as a priority queue,
320 // the key is the earliest time the request can be sent
321 int64& nRequestTime = mapAlreadyAskedFor[inv];
323 printf("askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
325 // Make sure not to reuse time indexes to keep things in the same order
326 int64 nNow = (GetTime() - 1) * 1000000;
327 static int64 nLastTime;
329 nNow = std::max(nNow, nLastTime);
332 // Each retry is 2 minutes after the last
333 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
334 mapAskFor.insert(std::make_pair(nRequestTime, inv));
339 void BeginMessage(const char* pszCommand)
341 ENTER_CRITICAL_SECTION(cs_vSend);
342 if (nHeaderStart != -1)
344 nHeaderStart = vSend.size();
345 vSend << CMessageHeader(pszCommand, 0);
346 nMessageStart = vSend.size();
348 printf("sending: %s ", pszCommand);
353 if (nHeaderStart < 0)
355 vSend.resize(nHeaderStart);
358 LEAVE_CRITICAL_SECTION(cs_vSend);
361 printf("(aborted)\n");
366 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
368 printf("dropmessages DROPPING SEND MESSAGE\n");
373 if (nHeaderStart < 0)
377 unsigned int nSize = vSend.size() - nMessageStart;
378 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
381 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
382 unsigned int nChecksum = 0;
383 memcpy(&nChecksum, &hash, sizeof(nChecksum));
384 assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
385 memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
388 printf("(%d bytes)\n", nSize);
393 LEAVE_CRITICAL_SECTION(cs_vSend);
396 void EndMessageAbortIfEmpty()
398 if (nHeaderStart < 0)
400 int nSize = vSend.size() - nMessageStart;
412 void PushMessage(const char* pszCommand)
416 BeginMessage(pszCommand);
426 template<typename T1>
427 void PushMessage(const char* pszCommand, const T1& a1)
431 BeginMessage(pszCommand);
442 template<typename T1, typename T2>
443 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
447 BeginMessage(pszCommand);
458 template<typename T1, typename T2, typename T3>
459 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
463 BeginMessage(pszCommand);
464 vSend << a1 << a2 << a3;
474 template<typename T1, typename T2, typename T3, typename T4>
475 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
479 BeginMessage(pszCommand);
480 vSend << a1 << a2 << a3 << a4;
490 template<typename T1, typename T2, typename T3, typename T4, typename T5>
491 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
495 BeginMessage(pszCommand);
496 vSend << a1 << a2 << a3 << a4 << a5;
506 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
507 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
511 BeginMessage(pszCommand);
512 vSend << a1 << a2 << a3 << a4 << a5 << a6;
522 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
523 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)
527 BeginMessage(pszCommand);
528 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
538 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
539 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)
543 BeginMessage(pszCommand);
544 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
554 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
555 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)
559 BeginMessage(pszCommand);
560 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
571 void PushRequest(const char* pszCommand,
572 void (*fn)(void*, CDataStream&), void* param1)
575 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
578 LOCK(cs_mapRequests);
579 mapRequests[hashReply] = CRequestTracker(fn, param1);
582 PushMessage(pszCommand, hashReply);
585 template<typename T1>
586 void PushRequest(const char* pszCommand, const T1& a1,
587 void (*fn)(void*, CDataStream&), void* param1)
590 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
593 LOCK(cs_mapRequests);
594 mapRequests[hashReply] = CRequestTracker(fn, param1);
597 PushMessage(pszCommand, hashReply, a1);
600 template<typename T1, typename T2>
601 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
602 void (*fn)(void*, CDataStream&), void* param1)
605 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
608 LOCK(cs_mapRequests);
609 mapRequests[hashReply] = CRequestTracker(fn, param1);
612 PushMessage(pszCommand, hashReply, a1, a2);
617 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
618 bool IsSubscribed(unsigned int nChannel);
619 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
620 void CancelSubscribe(unsigned int nChannel);
621 void CloseSocketDisconnect();
625 // Denial-of-service detection/prevention
626 // The idea is to detect peers that are behaving
627 // badly and disconnect/ban them, but do it in a
628 // one-coding-mistake-won't-shatter-the-entire-network
630 // IMPORTANT: There should be nothing I can give a
631 // node that it will forward on that will make that
632 // node's peers drop it. If there is, an attacker
633 // can isolate a node and/or try to split the network.
634 // Dropping a node for sending stuff that is invalid
635 // now but might be valid in a later version is also
636 // dangerous, because it can cause a network split
637 // between nodes running old code and nodes running
639 static void ClearBanned(); // needed for unit testing
640 static bool IsBanned(CNetAddr ip);
641 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
642 void copyStats(CNodeStats &stats);
654 inline void RelayInventory(const CInv& inv)
656 // Put on lists to offer to the other nodes
659 BOOST_FOREACH(CNode* pnode, vNodes)
660 pnode->PushInventory(inv);
665 void RelayMessage(const CInv& inv, const T& a)
667 CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
670 RelayMessage(inv, ss);
674 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
678 // Expire old relay messages
679 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
681 mapRelay.erase(vRelayExpiration.front().second);
682 vRelayExpiration.pop_front();
685 // Save original serialized message so newer versions are preserved
686 mapRelay.insert(std::make_pair(inv, ss));
687 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));