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