Remove unused includes.
[novacoin.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 <limits>
9 #include <deque>
10 #ifndef Q_MOC_RUN
11 #include <boost/array.hpp>
12 #include <boost/foreach.hpp>
13 #endif
14 #include <openssl/rand.h>
15
16 #ifndef WIN32
17 #include <arpa/inet.h>
18 #endif
19
20 #include "mruset.h"
21 #include "netbase.h"
22 #include "addrman.h"
23 #include "hash.h"
24
25 class CRequestTracker;
26 class CNode;
27 class CBlockIndex;
28 extern int nBestHeight;
29
30 const uint16_t nSocksDefault = 9050;
31 const uint16_t nPortZero = 0;
32
33
34 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
35 inline uint64_t 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, int64_t nTimeout=0);
44 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
45 void MapPort();
46 unsigned short GetListenPort();
47 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
48 void StartNode(void* parg);
49 bool StopNode();
50
51 enum
52 {
53     LOCAL_NONE,   // unknown
54     LOCAL_IF,     // address a local interface listens on
55     LOCAL_BIND,   // address explicit bound to
56     LOCAL_IRC,    // address reported by IRC (deprecated)
57     LOCAL_HTTP,   // address reported by whatismyip.com and similar
58     LOCAL_MANUAL, // address explicitly specified (-externalip=)
59
60     LOCAL_MAX
61 };
62
63 void SetLimited(enum Network net, bool fLimited = true);
64 bool IsLimited(enum Network net);
65 bool IsLimited(const CNetAddr& addr);
66 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
67 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
68 bool SeenLocal(const CService& addr);
69 bool IsLocal(const CService& addr);
70 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
71 bool IsReachable(const CNetAddr &addr);
72 void SetReachable(enum Network net, bool fFlag = true);
73 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
74
75
76 enum
77 {
78     MSG_TX = 1,
79     MSG_BLOCK
80 };
81
82 class CRequestTracker
83 {
84 public:
85     void (*fn)(void*, CDataStream&);
86     void* param1;
87
88     explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
89     {
90         fn = fnIn;
91         param1 = param1In;
92     }
93
94     bool IsNull()
95     {
96         return fn == NULL;
97     }
98 };
99
100
101 /** Thread types */
102 enum threadId
103 {
104     THREAD_SOCKETHANDLER,
105     THREAD_OPENCONNECTIONS,
106     THREAD_MESSAGEHANDLER,
107     THREAD_RPCLISTENER,
108     THREAD_DNSSEED,
109     THREAD_ADDEDCONNECTIONS,
110     THREAD_DUMPADDRESS,
111     THREAD_RPCHANDLER,
112     THREAD_MINTER,
113     THREAD_SCRIPTCHECK,
114     THREAD_NTP,
115
116     THREAD_MAX
117 };
118
119 extern bool fClient;
120 extern bool fDiscover;
121 extern uint64_t nLocalServices;
122 extern uint64_t nLocalHostNonce;
123 extern CAddress addrSeenByPeer;
124 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
125 extern CAddrMan addrman;
126
127 extern std::vector<CNode*> vNodes;
128 extern CCriticalSection cs_vNodes;
129 extern std::vector<std::string> vAddedNodes;
130 extern CCriticalSection cs_vAddedNodes;
131 extern std::map<CInv, CDataStream> mapRelay;
132 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
133 extern CCriticalSection cs_mapRelay;
134 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
135
136
137
138
139 class CNodeStats
140 {
141 public:
142     uint64_t nServices;
143     int64_t nLastSend;
144     int64_t nLastRecv;
145     int64_t nTimeConnected;
146     std::string addrName;
147     int32_t nVersion;
148     std::string strSubVer;
149     bool fInbound;
150     int64_t nReleaseTime;
151     int32_t nStartingHeight;
152     int32_t nMisbehavior;
153     uint64_t nSendBytes;
154     uint64_t nRecvBytes;
155     bool fSyncNode;
156 };
157
158
159
160
161
162 /** Information about a peer */
163 class CNode
164 {
165 public:
166     // socket
167     uint64_t nServices;
168     SOCKET hSocket;
169     CDataStream vSend;
170     CDataStream vRecv;
171     uint64_t nSendBytes;
172     uint64_t nRecvBytes;
173     CCriticalSection cs_vSend;
174     CCriticalSection cs_vRecv;
175     int64_t nLastSend;
176     int64_t nLastRecv;
177     int64_t nLastSendEmpty;
178     int64_t nTimeConnected;
179     int32_t nHeaderStart;
180     uint32_t nMessageStart;
181     CAddress addr;
182     std::string addrName;
183     CService addrLocal;
184     int32_t nVersion;
185     std::string strSubVer;
186     bool fOneShot;
187     bool fClient;
188     bool fInbound;
189     bool fNetworkNode;
190     bool fSuccessfullyConnected;
191     bool fDisconnect;
192     CSemaphoreGrant grantOutbound;
193 protected:
194     int nRefCount;
195
196     // Denial-of-service detection/prevention
197     // Key is IP address, value is banned-until-time
198     static std::map<CNetAddr, int64_t> setBanned;
199     static CCriticalSection cs_setBanned;
200     int nMisbehavior;
201
202 public:
203     int64_t nReleaseTime;
204     std::map<uint256, CRequestTracker> mapRequests;
205     CCriticalSection cs_mapRequests;
206     uint256 hashContinue;
207     CBlockIndex* pindexLastGetBlocksBegin;
208     uint256 hashLastGetBlocksEnd;
209     int32_t nStartingHeight;
210     bool fStartSync;
211
212     // flood relay
213     std::vector<CAddress> vAddrToSend;
214     std::set<CAddress> setAddrKnown;
215     bool fGetAddr;
216     std::set<uint256> setKnown;
217     uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
218
219     // inventory based relay
220     mruset<CInv> setInventoryKnown;
221     std::vector<CInv> vInventoryToSend;
222     CCriticalSection cs_inventory;
223     std::multimap<int64_t, CInv> mapAskFor;
224
225     CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
226     {
227         nServices = 0;
228         hSocket = hSocketIn;
229         nLastSend = 0;
230         nLastRecv = 0;
231         nSendBytes = 0;
232         nRecvBytes = 0;
233         nLastSendEmpty = GetTime();
234         nTimeConnected = GetTime();
235         nHeaderStart = -1;
236         nMessageStart = std::numeric_limits<uint32_t>::max();
237         addr = addrIn;
238         addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
239         nVersion = 0;
240         strSubVer = "";
241         fOneShot = false;
242         fClient = false; // set by version message
243         fInbound = fInboundIn;
244         fNetworkNode = false;
245         fSuccessfullyConnected = false;
246         fDisconnect = false;
247         nRefCount = 0;
248         nReleaseTime = 0;
249         hashContinue = 0;
250         pindexLastGetBlocksBegin = 0;
251         hashLastGetBlocksEnd = 0;
252         nStartingHeight = -1;
253         fStartSync = false;
254         fGetAddr = false;
255         nMisbehavior = 0;
256         hashCheckpointKnown = 0;
257         setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
258
259         // Be shy and don't send version until we hear
260         if (hSocket != INVALID_SOCKET && !fInbound)
261             PushVersion();
262     }
263
264     ~CNode()
265     {
266         if (hSocket != INVALID_SOCKET)
267         {
268             CloseSocket(hSocket);
269         }
270     }
271
272
273 private:
274     // Network usage totals
275     static CCriticalSection cs_totalBytesRecv;
276     static CCriticalSection cs_totalBytesSent;
277     static uint64_t nTotalBytesRecv;
278     static uint64_t nTotalBytesSent;
279     CNode(const CNode&);
280     void operator=(const CNode&);
281 public:
282
283
284     int GetRefCount()
285     {
286         return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
287     }
288
289     CNode* AddRef(int64_t nTimeout=0)
290     {
291         if (nTimeout != 0)
292             nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
293         else
294             nRefCount++;
295         return this;
296     }
297
298     void Release()
299     {
300         nRefCount--;
301     }
302
303
304
305     void AddAddressKnown(const CAddress& addr)
306     {
307         setAddrKnown.insert(addr);
308     }
309
310     void PushAddress(const CAddress& addr)
311     {
312         // Known checking here is only to save space from duplicates.
313         // SendMessages will filter it again for knowns that were added
314         // after addresses were pushed.
315         if (addr.IsValid() && !setAddrKnown.count(addr))
316             vAddrToSend.push_back(addr);
317     }
318
319
320     void AddInventoryKnown(const CInv& inv)
321     {
322         {
323             LOCK(cs_inventory);
324             setInventoryKnown.insert(inv);
325         }
326     }
327
328     void PushInventory(const CInv& inv)
329     {
330         {
331             LOCK(cs_inventory);
332             if (!setInventoryKnown.count(inv))
333                 vInventoryToSend.push_back(inv);
334         }
335     }
336
337     void AskFor(const CInv& inv)
338     {
339         // We're using mapAskFor as a priority queue,
340         // the key is the earliest time the request can be sent
341         int64_t& nRequestTime = mapAlreadyAskedFor[inv];
342         if (fDebugNet)
343             printf("askfor %s   %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
344
345         // Make sure not to reuse time indexes to keep things in the same order
346         int64_t nNow = (GetTime() - 1) * 1000000;
347         static int64_t nLastTime;
348         ++nLastTime;
349         nNow = std::max(nNow, nLastTime);
350         nLastTime = nNow;
351
352         // Each retry is 2 minutes after the last
353         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
354         mapAskFor.insert(std::make_pair(nRequestTime, inv));
355     }
356
357
358
359     void BeginMessage(const char* pszCommand)
360     {
361         ENTER_CRITICAL_SECTION(cs_vSend);
362         if (nHeaderStart != -1)
363             AbortMessage();
364         nHeaderStart = (int32_t)vSend.size();
365         vSend << CMessageHeader(pszCommand, 0);
366         nMessageStart = (uint32_t)vSend.size();
367         if (fDebug)
368             printf("sending: %s ", pszCommand);
369     }
370
371     void AbortMessage()
372     {
373         if (nHeaderStart < 0)
374             return;
375         vSend.resize(nHeaderStart);
376         nHeaderStart = -1;
377         nMessageStart = std::numeric_limits<uint32_t>::max();
378         LEAVE_CRITICAL_SECTION(cs_vSend);
379
380         if (fDebug)
381             printf("(aborted)\n");
382     }
383
384     void EndMessage()
385     {
386         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
387         {
388             printf("dropmessages DROPPING SEND MESSAGE\n");
389             AbortMessage();
390             return;
391         }
392
393         if (nHeaderStart < 0)
394             return;
395
396         // Set the size
397         uint32_t nSize = (uint32_t) vSend.size() - nMessageStart;
398         memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::MESSAGE_SIZE_OFFSET, &nSize, sizeof(nSize));
399
400         // Set the checksum
401         uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
402         uint32_t nChecksum = 0;
403         memcpy(&nChecksum, &hash, sizeof(nChecksum));
404         assert(nMessageStart - nHeaderStart >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
405         memcpy((char*)&vSend[nHeaderStart] + CMessageHeader::CHECKSUM_OFFSET, &nChecksum, sizeof(nChecksum));
406
407         if (fDebug) {
408             printf("(%d bytes)\n", nSize);
409         }
410
411         nHeaderStart = -1;
412         nMessageStart = std::numeric_limits<uint32_t>::max();
413         LEAVE_CRITICAL_SECTION(cs_vSend);
414     }
415
416     void EndMessageAbortIfEmpty()
417     {
418         if (nHeaderStart < 0)
419             return;
420         int nSize = (int) vSend.size() - nMessageStart;
421         if (nSize > 0)
422             EndMessage();
423         else
424             AbortMessage();
425     }
426
427
428
429     void PushVersion();
430
431
432     void PushMessage(const char* pszCommand)
433     {
434         try
435         {
436             BeginMessage(pszCommand);
437             EndMessage();
438         }
439         catch (...)
440         {
441             AbortMessage();
442             throw;
443         }
444     }
445
446     template<typename T1>
447     void PushMessage(const char* pszCommand, const T1& a1)
448     {
449         try
450         {
451             BeginMessage(pszCommand);
452             vSend << a1;
453             EndMessage();
454         }
455         catch (...)
456         {
457             AbortMessage();
458             throw;
459         }
460     }
461
462     template<typename T1, typename T2>
463     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
464     {
465         try
466         {
467             BeginMessage(pszCommand);
468             vSend << a1 << a2;
469             EndMessage();
470         }
471         catch (...)
472         {
473             AbortMessage();
474             throw;
475         }
476     }
477
478     template<typename T1, typename T2, typename T3>
479     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
480     {
481         try
482         {
483             BeginMessage(pszCommand);
484             vSend << a1 << a2 << a3;
485             EndMessage();
486         }
487         catch (...)
488         {
489             AbortMessage();
490             throw;
491         }
492     }
493
494     template<typename T1, typename T2, typename T3, typename T4>
495     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
496     {
497         try
498         {
499             BeginMessage(pszCommand);
500             vSend << a1 << a2 << a3 << a4;
501             EndMessage();
502         }
503         catch (...)
504         {
505             AbortMessage();
506             throw;
507         }
508     }
509
510     template<typename T1, typename T2, typename T3, typename T4, typename T5>
511     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
512     {
513         try
514         {
515             BeginMessage(pszCommand);
516             vSend << a1 << a2 << a3 << a4 << a5;
517             EndMessage();
518         }
519         catch (...)
520         {
521             AbortMessage();
522             throw;
523         }
524     }
525
526     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
527     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
528     {
529         try
530         {
531             BeginMessage(pszCommand);
532             vSend << a1 << a2 << a3 << a4 << a5 << a6;
533             EndMessage();
534         }
535         catch (...)
536         {
537             AbortMessage();
538             throw;
539         }
540     }
541
542     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
543     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)
544     {
545         try
546         {
547             BeginMessage(pszCommand);
548             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
549             EndMessage();
550         }
551         catch (...)
552         {
553             AbortMessage();
554             throw;
555         }
556     }
557
558     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
559     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)
560     {
561         try
562         {
563             BeginMessage(pszCommand);
564             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
565             EndMessage();
566         }
567         catch (...)
568         {
569             AbortMessage();
570             throw;
571         }
572     }
573
574     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
575     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)
576     {
577         try
578         {
579             BeginMessage(pszCommand);
580             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
581             EndMessage();
582         }
583         catch (...)
584         {
585             AbortMessage();
586             throw;
587         }
588     }
589
590
591     void PushRequest(const char* pszCommand,
592                      void (*fn)(void*, CDataStream&), void* param1)
593     {
594         uint256 hashReply;
595         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
596
597         {
598             LOCK(cs_mapRequests);
599             mapRequests[hashReply] = CRequestTracker(fn, param1);
600         }
601
602         PushMessage(pszCommand, hashReply);
603     }
604
605     template<typename T1>
606     void PushRequest(const char* pszCommand, const T1& a1,
607                      void (*fn)(void*, CDataStream&), void* param1)
608     {
609         uint256 hashReply;
610         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
611
612         {
613             LOCK(cs_mapRequests);
614             mapRequests[hashReply] = CRequestTracker(fn, param1);
615         }
616
617         PushMessage(pszCommand, hashReply, a1);
618     }
619
620     template<typename T1, typename T2>
621     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
622                      void (*fn)(void*, CDataStream&), void* param1)
623     {
624         uint256 hashReply;
625         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
626
627         {
628             LOCK(cs_mapRequests);
629             mapRequests[hashReply] = CRequestTracker(fn, param1);
630         }
631
632         PushMessage(pszCommand, hashReply, a1, a2);
633     }
634
635
636
637     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
638     bool IsSubscribed(unsigned int nChannel);
639     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
640     void CancelSubscribe(unsigned int nChannel);
641     void CloseSocketDisconnect();
642     void Cleanup();
643
644
645     // Denial-of-service detection/prevention
646     // The idea is to detect peers that are behaving
647     // badly and disconnect/ban them, but do it in a
648     // one-coding-mistake-won't-shatter-the-entire-network
649     // way.
650     // IMPORTANT:  There should be nothing I can give a
651     // node that it will forward on that will make that
652     // node's peers drop it. If there is, an attacker
653     // can isolate a node and/or try to split the network.
654     // Dropping a node for sending stuff that is invalid
655     // now but might be valid in a later version is also
656     // dangerous, because it can cause a network split
657     // between nodes running old code and nodes running
658     // new code.
659     static void ClearBanned(); // needed for unit testing
660     static bool IsBanned(CNetAddr ip);
661     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
662     void copyStats(CNodeStats &stats);
663     // Network stats
664     static void RecordBytesRecv(uint64_t bytes);
665     static void RecordBytesSent(uint64_t bytes);
666
667     static uint64_t GetTotalBytesRecv();
668     static uint64_t GetTotalBytesSent();
669 };
670
671 inline void RelayInventory(const CInv& inv)
672 {
673     // Put on lists to offer to the other nodes
674     {
675         LOCK(cs_vNodes);
676         BOOST_FOREACH(CNode* pnode, vNodes)
677             pnode->PushInventory(inv);
678     }
679 }
680
681 class CTransaction;
682 void RelayTransaction(const CTransaction& tx, const uint256& hash);
683 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
684
685
686 #endif