]> Git Repo - VerusCoin.git/blob - src/net.h
Merge pull request #3176 from Diapolo/key
[VerusCoin.git] / src / net.h
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.
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
32
33
34 inline unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
35 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
36
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);
48 bool StopNode();
49 void SocketSendData(CNode *pnode);
50
51 // Signals for message handling
52 struct CNodeSignals
53 {
54     boost::signals2::signal<int ()> GetHeight;
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     double dPingTime;
123     double dPingWait;
124     std::string addrLocal;
125 };
126
127
128
129
130 class CNetMessage {
131 public:
132     bool in_data;                   // parsing header (false) or data (true)
133
134     CDataStream hdrbuf;             // partially received header
135     CMessageHeader hdr;             // complete header
136     unsigned int nHdrPos;
137
138     CDataStream vRecv;              // received message data
139     unsigned int nDataPos;
140
141     CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
142         hdrbuf.resize(24);
143         in_data = false;
144         nHdrPos = 0;
145         nDataPos = 0;
146     }
147
148     bool complete() const
149     {
150         if (!in_data)
151             return false;
152         return (hdr.nMessageSize == nDataPos);
153     }
154
155     void SetVersion(int nVersionIn)
156     {
157         hdrbuf.SetVersion(nVersionIn);
158         vRecv.SetVersion(nVersionIn);
159     }
160
161     int readHeader(const char *pch, unsigned int nBytes);
162     int readData(const char *pch, unsigned int nBytes);
163 };
164
165
166
167
168
169 /** Information about a peer */
170 class CNode
171 {
172 public:
173     // socket
174     uint64 nServices;
175     SOCKET hSocket;
176     CDataStream ssSend;
177     size_t nSendSize; // total size of all vSendMsg entries
178     size_t nSendOffset; // offset inside the first vSendMsg already sent
179     uint64 nSendBytes;
180     std::deque<CSerializeData> vSendMsg;
181     CCriticalSection cs_vSend;
182
183     std::deque<CInv> vRecvGetData;
184     std::deque<CNetMessage> vRecvMsg;
185     CCriticalSection cs_vRecvMsg;
186     uint64 nRecvBytes;
187     int nRecvVersion;
188
189     int64 nLastSend;
190     int64 nLastRecv;
191     int64 nLastSendEmpty;
192     int64 nTimeConnected;
193     CAddress addr;
194     std::string addrName;
195     CService addrLocal;
196     int nVersion;
197     std::string strSubVer;
198     bool fOneShot;
199     bool fClient;
200     bool fInbound;
201     bool fNetworkNode;
202     bool fSuccessfullyConnected;
203     bool fDisconnect;
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.
208     bool fRelayTxes;
209     CSemaphoreGrant grantOutbound;
210     CCriticalSection cs_filter;
211     CBloomFilter* pfilter;
212     int nRefCount;
213 protected:
214
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;
219     int nMisbehavior;
220
221     // Basic fuzz-testing
222     void Fuzz(int nChance); // modifies ssSend
223
224 public:
225     uint256 hashContinue;
226     CBlockIndex* pindexLastGetBlocksBegin;
227     uint256 hashLastGetBlocksEnd;
228     int nStartingHeight;
229     bool fStartSync;
230
231     // flood relay
232     std::vector<CAddress> vAddrToSend;
233     std::set<CAddress> setAddrKnown;
234     bool fGetAddr;
235     std::set<uint256> setKnown;
236
237     // inventory based relay
238     mruset<CInv> setInventoryKnown;
239     std::vector<CInv> vInventoryToSend;
240     CCriticalSection cs_inventory;
241     std::multimap<int64, CInv> mapAskFor;
242
243     // Ping time measurement
244     uint64 nPingNonceSent;
245     int64 nPingUsecStart;
246     int64 nPingUsecTime;
247     bool fPingQueued;
248     
249     CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : ssSend(SER_NETWORK, MIN_PROTO_VERSION)
250     {
251         nServices = 0;
252         hSocket = hSocketIn;
253         nRecvVersion = MIN_PROTO_VERSION;
254         nLastSend = 0;
255         nLastRecv = 0;
256         nSendBytes = 0;
257         nRecvBytes = 0;
258         nLastSendEmpty = GetTime();
259         nTimeConnected = GetTime();
260         addr = addrIn;
261         addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
262         nVersion = 0;
263         strSubVer = "";
264         fOneShot = false;
265         fClient = false; // set by version message
266         fInbound = fInboundIn;
267         fNetworkNode = false;
268         fSuccessfullyConnected = false;
269         fDisconnect = false;
270         nRefCount = 0;
271         nSendSize = 0;
272         nSendOffset = 0;
273         hashContinue = 0;
274         pindexLastGetBlocksBegin = 0;
275         hashLastGetBlocksEnd = 0;
276         nStartingHeight = -1;
277         fStartSync = false;
278         fGetAddr = false;
279         nMisbehavior = 0;
280         fRelayTxes = false;
281         setInventoryKnown.max_size(SendBufferSize() / 1000);
282         pfilter = new CBloomFilter();
283         nPingNonceSent = 0;
284         nPingUsecStart = 0;
285         nPingUsecTime = 0;
286         fPingQueued = false;
287
288         // Be shy and don't send version until we hear
289         if (hSocket != INVALID_SOCKET && !fInbound)
290             PushVersion();
291     }
292
293     ~CNode()
294     {
295         if (hSocket != INVALID_SOCKET)
296         {
297             closesocket(hSocket);
298             hSocket = INVALID_SOCKET;
299         }
300         if (pfilter)
301             delete pfilter;
302     }
303
304 private:
305     // Network usage totals
306     static CCriticalSection cs_totalBytesRecv;
307     static CCriticalSection cs_totalBytesSent;
308     static uint64 nTotalBytesRecv;
309     static uint64 nTotalBytesSent;
310
311     CNode(const CNode&);
312     void operator=(const CNode&);
313
314 public:
315
316
317     int GetRefCount()
318     {
319         assert(nRefCount >= 0);
320         return nRefCount;
321     }
322
323     // requires LOCK(cs_vRecvMsg)
324     unsigned int GetTotalRecvSize()
325     {
326         unsigned int total = 0;
327         BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
328             total += msg.vRecv.size() + 24;
329         return total;
330     }
331
332     // requires LOCK(cs_vRecvMsg)
333     bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
334
335     // requires LOCK(cs_vRecvMsg)
336     void SetRecvVersion(int nVersionIn)
337     {
338         nRecvVersion = nVersionIn;
339         BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
340             msg.SetVersion(nVersionIn);
341     }
342
343     CNode* AddRef()
344     {
345         nRefCount++;
346         return this;
347     }
348
349     void Release()
350     {
351         nRefCount--;
352     }
353
354
355
356     void AddAddressKnown(const CAddress& addr)
357     {
358         setAddrKnown.insert(addr);
359     }
360
361     void PushAddress(const CAddress& addr)
362     {
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);
368     }
369
370
371     void AddInventoryKnown(const CInv& inv)
372     {
373         {
374             LOCK(cs_inventory);
375             setInventoryKnown.insert(inv);
376         }
377     }
378
379     void PushInventory(const CInv& inv)
380     {
381         {
382             LOCK(cs_inventory);
383             if (!setInventoryKnown.count(inv))
384                 vInventoryToSend.push_back(inv);
385         }
386     }
387
388     void AskFor(const CInv& inv)
389     {
390         // We're using mapAskFor as a priority queue,
391         // the key is the earliest time the request can be sent
392         int64 nRequestTime;
393         limitedmap<CInv, int64>::const_iterator it = mapAlreadyAskedFor.find(inv);
394         if (it != mapAlreadyAskedFor.end())
395             nRequestTime = it->second;
396         else
397             nRequestTime = 0;
398         LogPrint("net", "askfor %s   %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
399
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;
403         ++nLastTime;
404         nNow = std::max(nNow, nLastTime);
405         nLastTime = nNow;
406
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);
411         else
412             mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
413         mapAskFor.insert(std::make_pair(nRequestTime, inv));
414     }
415
416
417
418     // TODO: Document the postcondition of this function.  Is cs_vSend locked?
419     void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
420     {
421         ENTER_CRITICAL_SECTION(cs_vSend);
422         assert(ssSend.size() == 0);
423         ssSend << CMessageHeader(pszCommand, 0);
424         LogPrint("net", "sending: %s ", pszCommand);
425     }
426
427     // TODO: Document the precondition of this function.  Is cs_vSend locked?
428     void AbortMessage() UNLOCK_FUNCTION(cs_vSend)
429     {
430         ssSend.clear();
431
432         LEAVE_CRITICAL_SECTION(cs_vSend);
433
434         LogPrint("net", "(aborted)\n");
435     }
436
437     // TODO: Document the precondition of this function.  Is cs_vSend locked?
438     void EndMessage() UNLOCK_FUNCTION(cs_vSend)
439     {
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)
444         {
445             LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
446             AbortMessage();
447             return;
448         }
449         if (mapArgs.count("-fuzzmessagestest"))
450             Fuzz(GetArg("-fuzzmessagestest", 10));
451
452         if (ssSend.size() == 0)
453             return;
454
455         // Set the size
456         unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
457         memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
458
459         // Set the checksum
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));
465
466         LogPrint("net", "(%d bytes)\n", nSize);
467
468         std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
469         ssSend.GetAndClear(*it);
470         nSendSize += (*it).size();
471
472         // If write queue empty, attempt "optimistic write"
473         if (it == vSendMsg.begin())
474             SocketSendData(this);
475
476         LEAVE_CRITICAL_SECTION(cs_vSend);
477     }
478
479     void PushVersion();
480
481
482     void PushMessage(const char* pszCommand)
483     {
484         try
485         {
486             BeginMessage(pszCommand);
487             EndMessage();
488         }
489         catch (...)
490         {
491             AbortMessage();
492             throw;
493         }
494     }
495
496     template<typename T1>
497     void PushMessage(const char* pszCommand, const T1& a1)
498     {
499         try
500         {
501             BeginMessage(pszCommand);
502             ssSend << a1;
503             EndMessage();
504         }
505         catch (...)
506         {
507             AbortMessage();
508             throw;
509         }
510     }
511
512     template<typename T1, typename T2>
513     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
514     {
515         try
516         {
517             BeginMessage(pszCommand);
518             ssSend << a1 << a2;
519             EndMessage();
520         }
521         catch (...)
522         {
523             AbortMessage();
524             throw;
525         }
526     }
527
528     template<typename T1, typename T2, typename T3>
529     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
530     {
531         try
532         {
533             BeginMessage(pszCommand);
534             ssSend << a1 << a2 << a3;
535             EndMessage();
536         }
537         catch (...)
538         {
539             AbortMessage();
540             throw;
541         }
542     }
543
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)
546     {
547         try
548         {
549             BeginMessage(pszCommand);
550             ssSend << a1 << a2 << a3 << a4;
551             EndMessage();
552         }
553         catch (...)
554         {
555             AbortMessage();
556             throw;
557         }
558     }
559
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)
562     {
563         try
564         {
565             BeginMessage(pszCommand);
566             ssSend << a1 << a2 << a3 << a4 << a5;
567             EndMessage();
568         }
569         catch (...)
570         {
571             AbortMessage();
572             throw;
573         }
574     }
575
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)
578     {
579         try
580         {
581             BeginMessage(pszCommand);
582             ssSend << a1 << a2 << a3 << a4 << a5 << a6;
583             EndMessage();
584         }
585         catch (...)
586         {
587             AbortMessage();
588             throw;
589         }
590     }
591
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)
594     {
595         try
596         {
597             BeginMessage(pszCommand);
598             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
599             EndMessage();
600         }
601         catch (...)
602         {
603             AbortMessage();
604             throw;
605         }
606     }
607
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)
610     {
611         try
612         {
613             BeginMessage(pszCommand);
614             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
615             EndMessage();
616         }
617         catch (...)
618         {
619             AbortMessage();
620             throw;
621         }
622     }
623
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)
626     {
627         try
628         {
629             BeginMessage(pszCommand);
630             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
631             EndMessage();
632         }
633         catch (...)
634         {
635             AbortMessage();
636             throw;
637         }
638     }
639
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();
644     void Cleanup();
645
646
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
651     // way.
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
660     // new code.
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);
665
666     // Network stats
667     static void RecordBytesRecv(uint64 bytes);
668     static void RecordBytesSent(uint64 bytes);
669
670     static uint64 GetTotalBytesRecv();
671     static uint64 GetTotalBytesSent();
672 };
673
674
675
676 class CTransaction;
677 void RelayTransaction(const CTransaction& tx, const uint256& hash);
678 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
679
680 #endif
This page took 0.061509 seconds and 4 git commands to generate.