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