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