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