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