]> Git Repo - VerusCoin.git/blob - src/net.h
Merge pull request #2791 from sipa/proveprune
[VerusCoin.git] / src / net.h
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.
5 #ifndef BITCOIN_NET_H
6 #define BITCOIN_NET_H
7
8 #include <deque>
9 #include <boost/array.hpp>
10 #include <boost/foreach.hpp>
11 #include <boost/signals2/signal.hpp>
12 #include <openssl/rand.h>
13
14 #ifndef WIN32
15 #include <arpa/inet.h>
16 #endif
17
18 #include "mruset.h"
19 #include "limitedmap.h"
20 #include "netbase.h"
21 #include "protocol.h"
22 #include "addrman.h"
23 #include "hash.h"
24 #include "bloom.h"
25
26 /** The maximum number of entries in an 'inv' protocol message */
27 static const unsigned int MAX_INV_SZ = 50000;
28
29 class CNode;
30 class CBlockIndex;
31 extern int nBestHeight;
32
33
34
35 inline unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
36 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
37
38 void AddOneShot(std::string strDest);
39 bool RecvLine(SOCKET hSocket, std::string& strLine);
40 bool GetMyExternalIP(CNetAddr& ipRet);
41 void AddressCurrentlyConnected(const CService& addr);
42 CNode* FindNode(const CNetAddr& ip);
43 CNode* FindNode(const CService& ip);
44 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL);
45 void MapPort(bool fUseUPnP);
46 unsigned short GetListenPort();
47 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
48 void StartNode(boost::thread_group& threadGroup);
49 bool StopNode();
50 void SocketSendData(CNode *pnode);
51
52 // Signals for message handling
53 struct CNodeSignals
54 {
55     boost::signals2::signal<bool (CNode*)> ProcessMessages;
56     boost::signals2::signal<bool (CNode*, bool)> SendMessages;
57 };
58
59 CNodeSignals& GetNodeSignals();
60
61
62 enum
63 {
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=)
70
71     LOCAL_MAX
72 };
73
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);
85
86
87 extern bool fDiscover;
88 extern uint64 nLocalServices;
89 extern uint64 nLocalHostNonce;
90 extern CAddrMan addrman;
91 extern int nMaxConnections;
92
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;
99
100 extern std::vector<std::string> vAddedNodes;
101 extern CCriticalSection cs_vAddedNodes;
102
103
104
105
106 class CNodeStats
107 {
108 public:
109     uint64 nServices;
110     int64 nLastSend;
111     int64 nLastRecv;
112     int64 nTimeConnected;
113     std::string addrName;
114     int nVersion;
115     std::string strSubVer;
116     bool fInbound;
117     int nStartingHeight;
118     int nMisbehavior;
119     uint64 nSendBytes;
120     uint64 nRecvBytes;
121     bool fSyncNode;
122 };
123
124
125
126
127 class CNetMessage {
128 public:
129     bool in_data;                   // parsing header (false) or data (true)
130
131     CDataStream hdrbuf;             // partially received header
132     CMessageHeader hdr;             // complete header
133     unsigned int nHdrPos;
134
135     CDataStream vRecv;              // received message data
136     unsigned int nDataPos;
137
138     CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
139         hdrbuf.resize(24);
140         in_data = false;
141         nHdrPos = 0;
142         nDataPos = 0;
143     }
144
145     bool complete() const
146     {
147         if (!in_data)
148             return false;
149         return (hdr.nMessageSize == nDataPos);
150     }
151
152     void SetVersion(int nVersionIn)
153     {
154         hdrbuf.SetVersion(nVersionIn);
155         vRecv.SetVersion(nVersionIn);
156     }
157
158     int readHeader(const char *pch, unsigned int nBytes);
159     int readData(const char *pch, unsigned int nBytes);
160 };
161
162
163
164
165
166 /** Information about a peer */
167 class CNode
168 {
169 public:
170     // socket
171     uint64 nServices;
172     SOCKET hSocket;
173     CDataStream ssSend;
174     size_t nSendSize; // total size of all vSendMsg entries
175     size_t nSendOffset; // offset inside the first vSendMsg already sent
176     uint64 nSendBytes;
177     std::deque<CSerializeData> vSendMsg;
178     CCriticalSection cs_vSend;
179
180     std::deque<CInv> vRecvGetData;
181     std::deque<CNetMessage> vRecvMsg;
182     CCriticalSection cs_vRecvMsg;
183     uint64 nRecvBytes;
184     int nRecvVersion;
185
186     int64 nLastSend;
187     int64 nLastRecv;
188     int64 nLastSendEmpty;
189     int64 nTimeConnected;
190     CAddress addr;
191     std::string addrName;
192     CService addrLocal;
193     int nVersion;
194     std::string strSubVer;
195     bool fOneShot;
196     bool fClient;
197     bool fInbound;
198     bool fNetworkNode;
199     bool fSuccessfullyConnected;
200     bool fDisconnect;
201     // We use fRelayTxes for two purposes -
202     // a) it allows us to not relay tx invs before receiving the peer's version message
203     // b) the peer may tell us in their version message that we should not relay tx invs
204     //    until they have initialized their bloom filter.
205     bool fRelayTxes;
206     CSemaphoreGrant grantOutbound;
207     CCriticalSection cs_filter;
208     CBloomFilter* pfilter;
209     int nRefCount;
210 protected:
211
212     // Denial-of-service detection/prevention
213     // Key is IP address, value is banned-until-time
214     static std::map<CNetAddr, int64> setBanned;
215     static CCriticalSection cs_setBanned;
216     int nMisbehavior;
217
218 public:
219     uint256 hashContinue;
220     CBlockIndex* pindexLastGetBlocksBegin;
221     uint256 hashLastGetBlocksEnd;
222     int nStartingHeight;
223     bool fStartSync;
224
225     // flood relay
226     std::vector<CAddress> vAddrToSend;
227     std::set<CAddress> setAddrKnown;
228     bool fGetAddr;
229     std::set<uint256> setKnown;
230
231     // inventory based relay
232     mruset<CInv> setInventoryKnown;
233     std::vector<CInv> vInventoryToSend;
234     CCriticalSection cs_inventory;
235     std::multimap<int64, CInv> mapAskFor;
236
237     CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : ssSend(SER_NETWORK, MIN_PROTO_VERSION)
238     {
239         nServices = 0;
240         hSocket = hSocketIn;
241         nRecvVersion = MIN_PROTO_VERSION;
242         nLastSend = 0;
243         nLastRecv = 0;
244         nSendBytes = 0;
245         nRecvBytes = 0;
246         nLastSendEmpty = GetTime();
247         nTimeConnected = GetTime();
248         addr = addrIn;
249         addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
250         nVersion = 0;
251         strSubVer = "";
252         fOneShot = false;
253         fClient = false; // set by version message
254         fInbound = fInboundIn;
255         fNetworkNode = false;
256         fSuccessfullyConnected = false;
257         fDisconnect = false;
258         nRefCount = 0;
259         nSendSize = 0;
260         nSendOffset = 0;
261         hashContinue = 0;
262         pindexLastGetBlocksBegin = 0;
263         hashLastGetBlocksEnd = 0;
264         nStartingHeight = -1;
265         fStartSync = false;
266         fGetAddr = false;
267         nMisbehavior = 0;
268         fRelayTxes = false;
269         setInventoryKnown.max_size(SendBufferSize() / 1000);
270         pfilter = new CBloomFilter();
271
272         // Be shy and don't send version until we hear
273         if (hSocket != INVALID_SOCKET && !fInbound)
274             PushVersion();
275     }
276
277     ~CNode()
278     {
279         if (hSocket != INVALID_SOCKET)
280         {
281             closesocket(hSocket);
282             hSocket = INVALID_SOCKET;
283         }
284         if (pfilter)
285             delete pfilter;
286     }
287
288 private:
289     CNode(const CNode&);
290     void operator=(const CNode&);
291 public:
292
293
294     int GetRefCount()
295     {
296         assert(nRefCount >= 0);
297         return nRefCount;
298     }
299
300     // requires LOCK(cs_vRecvMsg)
301     unsigned int GetTotalRecvSize()
302     {
303         unsigned int total = 0;
304         BOOST_FOREACH(const CNetMessage &msg, vRecvMsg) 
305             total += msg.vRecv.size() + 24;
306         return total;
307     }
308
309     // requires LOCK(cs_vRecvMsg)
310     bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
311
312     // requires LOCK(cs_vRecvMsg)
313     void SetRecvVersion(int nVersionIn)
314     {
315         nRecvVersion = nVersionIn;
316         BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
317             msg.SetVersion(nVersionIn);
318     }
319
320     CNode* AddRef()
321     {
322         nRefCount++;
323         return this;
324     }
325
326     void Release()
327     {
328         nRefCount--;
329     }
330
331
332
333     void AddAddressKnown(const CAddress& addr)
334     {
335         setAddrKnown.insert(addr);
336     }
337
338     void PushAddress(const CAddress& addr)
339     {
340         // Known checking here is only to save space from duplicates.
341         // SendMessages will filter it again for knowns that were added
342         // after addresses were pushed.
343         if (addr.IsValid() && !setAddrKnown.count(addr))
344             vAddrToSend.push_back(addr);
345     }
346
347
348     void AddInventoryKnown(const CInv& inv)
349     {
350         {
351             LOCK(cs_inventory);
352             setInventoryKnown.insert(inv);
353         }
354     }
355
356     void PushInventory(const CInv& inv)
357     {
358         {
359             LOCK(cs_inventory);
360             if (!setInventoryKnown.count(inv))
361                 vInventoryToSend.push_back(inv);
362         }
363     }
364
365     void AskFor(const CInv& inv)
366     {
367         // We're using mapAskFor as a priority queue,
368         // the key is the earliest time the request can be sent
369         int64 nRequestTime;
370         limitedmap<CInv, int64>::const_iterator it = mapAlreadyAskedFor.find(inv);
371         if (it != mapAlreadyAskedFor.end())
372             nRequestTime = it->second;
373         else
374             nRequestTime = 0;
375         LogPrint("net", "askfor %s   %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
376
377         // Make sure not to reuse time indexes to keep things in the same order
378         int64 nNow = (GetTime() - 1) * 1000000;
379         static int64 nLastTime;
380         ++nLastTime;
381         nNow = std::max(nNow, nLastTime);
382         nLastTime = nNow;
383
384         // Each retry is 2 minutes after the last
385         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
386         if (it != mapAlreadyAskedFor.end())
387             mapAlreadyAskedFor.update(it, nRequestTime);
388         else
389             mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
390         mapAskFor.insert(std::make_pair(nRequestTime, inv));
391     }
392
393
394
395     // TODO: Document the postcondition of this function.  Is cs_vSend locked?
396     void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
397     {
398         ENTER_CRITICAL_SECTION(cs_vSend);
399         assert(ssSend.size() == 0);
400         ssSend << CMessageHeader(pszCommand, 0);
401         LogPrint("net", "sending: %s ", pszCommand);
402     }
403
404     // TODO: Document the precondition of this function.  Is cs_vSend locked?
405     void AbortMessage() UNLOCK_FUNCTION(cs_vSend)
406     {
407         ssSend.clear();
408
409         LEAVE_CRITICAL_SECTION(cs_vSend);
410
411         LogPrint("net", "(aborted)\n");
412     }
413
414     // TODO: Document the precondition of this function.  Is cs_vSend locked?
415     void EndMessage() UNLOCK_FUNCTION(cs_vSend)
416     {
417         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
418         {
419             LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
420             AbortMessage();
421             return;
422         }
423
424         if (ssSend.size() == 0)
425             return;
426
427         // Set the size
428         unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
429         memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
430
431         // Set the checksum
432         uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
433         unsigned int nChecksum = 0;
434         memcpy(&nChecksum, &hash, sizeof(nChecksum));
435         assert(ssSend.size () >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
436         memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
437
438         LogPrint("net", "(%d bytes)\n", nSize);
439
440         std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
441         ssSend.GetAndClear(*it);
442         nSendSize += (*it).size();
443
444         // If write queue empty, attempt "optimistic write"
445         if (it == vSendMsg.begin())
446             SocketSendData(this);
447
448         LEAVE_CRITICAL_SECTION(cs_vSend);
449     }
450
451     void PushVersion();
452
453
454     void PushMessage(const char* pszCommand)
455     {
456         try
457         {
458             BeginMessage(pszCommand);
459             EndMessage();
460         }
461         catch (...)
462         {
463             AbortMessage();
464             throw;
465         }
466     }
467
468     template<typename T1>
469     void PushMessage(const char* pszCommand, const T1& a1)
470     {
471         try
472         {
473             BeginMessage(pszCommand);
474             ssSend << a1;
475             EndMessage();
476         }
477         catch (...)
478         {
479             AbortMessage();
480             throw;
481         }
482     }
483
484     template<typename T1, typename T2>
485     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
486     {
487         try
488         {
489             BeginMessage(pszCommand);
490             ssSend << a1 << a2;
491             EndMessage();
492         }
493         catch (...)
494         {
495             AbortMessage();
496             throw;
497         }
498     }
499
500     template<typename T1, typename T2, typename T3>
501     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
502     {
503         try
504         {
505             BeginMessage(pszCommand);
506             ssSend << a1 << a2 << a3;
507             EndMessage();
508         }
509         catch (...)
510         {
511             AbortMessage();
512             throw;
513         }
514     }
515
516     template<typename T1, typename T2, typename T3, typename T4>
517     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
518     {
519         try
520         {
521             BeginMessage(pszCommand);
522             ssSend << a1 << a2 << a3 << a4;
523             EndMessage();
524         }
525         catch (...)
526         {
527             AbortMessage();
528             throw;
529         }
530     }
531
532     template<typename T1, typename T2, typename T3, typename T4, typename T5>
533     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
534     {
535         try
536         {
537             BeginMessage(pszCommand);
538             ssSend << a1 << a2 << a3 << a4 << a5;
539             EndMessage();
540         }
541         catch (...)
542         {
543             AbortMessage();
544             throw;
545         }
546     }
547
548     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
549     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
550     {
551         try
552         {
553             BeginMessage(pszCommand);
554             ssSend << a1 << a2 << a3 << a4 << a5 << a6;
555             EndMessage();
556         }
557         catch (...)
558         {
559             AbortMessage();
560             throw;
561         }
562     }
563
564     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
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)
566     {
567         try
568         {
569             BeginMessage(pszCommand);
570             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
571             EndMessage();
572         }
573         catch (...)
574         {
575             AbortMessage();
576             throw;
577         }
578     }
579
580     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
581     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)
582     {
583         try
584         {
585             BeginMessage(pszCommand);
586             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
587             EndMessage();
588         }
589         catch (...)
590         {
591             AbortMessage();
592             throw;
593         }
594     }
595
596     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
597     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)
598     {
599         try
600         {
601             BeginMessage(pszCommand);
602             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
603             EndMessage();
604         }
605         catch (...)
606         {
607             AbortMessage();
608             throw;
609         }
610     }
611
612     bool IsSubscribed(unsigned int nChannel);
613     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
614     void CancelSubscribe(unsigned int nChannel);
615     void CloseSocketDisconnect();
616     void Cleanup();
617
618
619     // Denial-of-service detection/prevention
620     // The idea is to detect peers that are behaving
621     // badly and disconnect/ban them, but do it in a
622     // one-coding-mistake-won't-shatter-the-entire-network
623     // way.
624     // IMPORTANT:  There should be nothing I can give a
625     // node that it will forward on that will make that
626     // node's peers drop it. If there is, an attacker
627     // can isolate a node and/or try to split the network.
628     // Dropping a node for sending stuff that is invalid
629     // now but might be valid in a later version is also
630     // dangerous, because it can cause a network split
631     // between nodes running old code and nodes running
632     // new code.
633     static void ClearBanned(); // needed for unit testing
634     static bool IsBanned(CNetAddr ip);
635     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
636     void copyStats(CNodeStats &stats);
637 };
638
639
640
641 class CTransaction;
642 void RelayTransaction(const CTransaction& tx, const uint256& hash);
643 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
644
645 #endif
This page took 0.056674 seconds and 4 git commands to generate.