Headers 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 "mruset.h"
9 #include "netbase.h"
10 #include "addrman.h"
11 #include "hash.h"
12 #include "streams.h"
13
14 #ifndef WIN32
15 #include <arpa/inet.h>
16 #endif
17
18 #include <limits>
19 #include <deque>
20
21
22 class CRequestTracker;
23 class CNode;
24 class CBlockIndex;
25 extern int nBestHeight;
26
27 const uint16_t nSocksDefault = 9050;
28 const uint16_t nPortZero = 0;
29
30
31 inline uint64_t ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); }
32 inline uint64_t SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); }
33
34 void AddOneShot(std::string strDest);
35 bool RecvLine(SOCKET hSocket, std::string& strLine);
36 bool GetMyExternalIP(CNetAddr& ipRet);
37 void AddressCurrentlyConnected(const CService& addr);
38 CNode* FindNode(const CNetAddr& ip);
39 CNode* FindNode(const CService& ip);
40 CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, int64_t nTimeout=0);
41 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
42 void MapPort();
43 unsigned short GetListenPort();
44 bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string()));
45 void StartNode(void* parg);
46 bool StopNode();
47
48 enum
49 {
50     LOCAL_NONE,   // unknown
51     LOCAL_IF,     // address a local interface listens on
52     LOCAL_BIND,   // address explicit bound to
53     LOCAL_IRC,    // address reported by IRC (deprecated)
54     LOCAL_HTTP,   // address reported by whatismyip.com and similar
55     LOCAL_MANUAL, // address explicitly specified (-externalip=)
56
57     LOCAL_MAX
58 };
59
60
61 bool IsPeerAddrLocalGood(CNode *pnode);
62 void AdvertiseLocal(CNode *pnode);
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     THREAD_IPCOLLECTOR,
116
117     THREAD_MAX
118 };
119
120 extern bool fClient;
121 extern bool fDiscover;
122 extern bool fNoListen;
123
124 extern bool fDiscover;
125 extern uint64_t nLocalServices;
126 extern uint64_t nLocalHostNonce;
127 extern CAddress addrSeenByPeer;
128 extern std::array<int, THREAD_MAX> vnThreadsRunning;
129 extern CAddrMan addrman;
130
131 extern std::vector<CNode*> vNodes;
132 extern CCriticalSection cs_vNodes;
133 extern std::vector<std::string> vAddedNodes;
134 extern CCriticalSection cs_vAddedNodes;
135 extern std::map<CInv, CDataStream> mapRelay;
136 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
137 extern CCriticalSection cs_mapRelay;
138 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
139
140
141
142
143 class CNodeStats
144 {
145 public:
146     uint64_t nServices;
147     int64_t nLastSend;
148     int64_t nLastRecv;
149     int64_t nTimeConnected;
150     std::string addrName;
151     int32_t nVersion;
152     std::string strSubVer;
153     bool fInbound;
154     int64_t nReleaseTime;
155     int32_t nStartingHeight;
156     int32_t nMisbehavior;
157     uint64_t nSendBytes;
158     uint64_t nRecvBytes;
159     bool fSyncNode;
160 };
161
162
163
164
165
166 /** Information about a peer */
167 class CNode
168 {
169 public:
170     // socket
171     uint64_t nServices;
172     SOCKET hSocket;
173     CDataStream vSend;
174     CDataStream vRecv;
175     uint64_t nSendBytes;
176     uint64_t nRecvBytes;
177     CCriticalSection cs_vSend;
178     CCriticalSection cs_vRecv;
179     int64_t nLastSend;
180     int64_t nLastRecv;
181     int64_t nLastSendEmpty;
182     int64_t nTimeConnected;
183     int32_t nHeaderStart;
184     uint32_t nMessageStart;
185     CAddress addr;
186     std::string addrName;
187     CService addrLocal;
188     int32_t nVersion;
189     std::string strSubVer;
190     bool fOneShot;
191     bool fClient;
192     bool fInbound;
193     bool fNetworkNode;
194     bool fSuccessfullyConnected;
195     bool fDisconnect;
196     CSemaphoreGrant grantOutbound;
197 protected:
198     int nRefCount;
199
200     // Denial-of-service detection/prevention
201     // Key is IP address, value is banned-until-time
202     static std::map<CNetAddr, int64_t> setBanned;
203     static CCriticalSection cs_setBanned;
204     int nMisbehavior;
205
206 public:
207     int64_t nReleaseTime;
208     std::map<uint256, CRequestTracker> mapRequests;
209     CCriticalSection cs_mapRequests;
210     uint256 hashContinue;
211     CBlockIndex* pindexLastGetBlocksBegin;
212     uint256 hashLastGetBlocksEnd;
213     int32_t nStartingHeight;
214     bool fStartSync;
215
216     // flood relay
217     std::vector<CAddress> vAddrToSend;
218     std::set<CAddress> setAddrKnown;
219     bool fGetAddr;
220     std::set<uint256> setKnown;
221     uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
222     int64_t nNextAddrSend;
223     int64_t nNextLocalAddrSend;
224     int64_t nNextInvSend;
225
226     // inventory based relay
227     mruset<CInv> setInventoryKnown;
228     std::vector<CInv> vInventoryToSend;
229     CCriticalSection cs_inventory;
230     std::multimap<int64_t, CInv> mapAskFor;
231
232     CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false) : vSend(SER_NETWORK, MIN_PROTO_VERSION), vRecv(SER_NETWORK, MIN_PROTO_VERSION)
233     {
234         nServices = 0;
235         hSocket = hSocketIn;
236         nLastSend = 0;
237         nLastRecv = 0;
238         nSendBytes = 0;
239         nRecvBytes = 0;
240         nLastSendEmpty = GetTime();
241         nTimeConnected = GetTime();
242         nHeaderStart = -1;
243         nMessageStart = std::numeric_limits<uint32_t>::max();
244         addr = addrIn;
245         addrName = addrNameIn.empty() ? addr.ToStringIPPort() : addrNameIn;
246         nVersion = 0;
247         strSubVer.clear();
248         fOneShot = false;
249         fClient = false; // set by version message
250         fInbound = fInboundIn;
251         fNetworkNode = false;
252         fSuccessfullyConnected = false;
253         fDisconnect = false;
254         nRefCount = 0;
255         nReleaseTime = 0;
256         hashContinue = 0;
257         pindexLastGetBlocksBegin = 0;
258         hashLastGetBlocksEnd = 0;
259         nStartingHeight = -1;
260         nNextLocalAddrSend = 0;
261         nNextAddrSend = 0;
262         nNextInvSend = 0;
263         fStartSync = false;
264         fGetAddr = false;
265         nMisbehavior = 0;
266         hashCheckpointKnown = 0;
267         setInventoryKnown.max_size((size_t)SendBufferSize() / 1000);
268
269         // Be shy and don't send version until we hear
270         if (hSocket != INVALID_SOCKET && !fInbound)
271             PushVersion();
272     }
273
274     ~CNode()
275     {
276         if (hSocket != INVALID_SOCKET)
277         {
278             CloseSocket(hSocket);
279         }
280     }
281
282
283 private:
284     // Network usage totals
285     static CCriticalSection cs_totalBytesRecv;
286     static CCriticalSection cs_totalBytesSent;
287     static uint64_t nTotalBytesRecv;
288     static uint64_t nTotalBytesSent;
289     CNode(const CNode&);
290     void operator=(const CNode&);
291 public:
292
293
294     int GetRefCount()
295     {
296         return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
297     }
298
299     CNode* AddRef(int64_t nTimeout=0)
300     {
301         if (nTimeout != 0)
302             nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
303         else
304             nRefCount++;
305         return this;
306     }
307
308     void Release()
309     {
310         nRefCount--;
311     }
312
313
314
315     void AddAddressKnown(const CAddress& addr)
316     {
317         setAddrKnown.insert(addr);
318     }
319
320     void PushAddress(const CAddress& addr)
321     {
322         // Known checking here is only to save space from duplicates.
323         // SendMessages will filter it again for knowns that were added
324         // after addresses were pushed.
325         if (addr.IsValid() && !setAddrKnown.count(addr))
326             vAddrToSend.push_back(addr);
327     }
328
329
330     void AddInventoryKnown(const CInv& inv)
331     {
332         {
333             LOCK(cs_inventory);
334             setInventoryKnown.insert(inv);
335         }
336     }
337
338     void PushInventory(const CInv& inv)
339     {
340         {
341             LOCK(cs_inventory);
342             if (!setInventoryKnown.count(inv))
343                 vInventoryToSend.push_back(inv);
344         }
345     }
346
347     void AskFor(const CInv& inv)
348     {
349         // We're using mapAskFor as a priority queue,
350         // the key is the earliest time the request can be sent
351         int64_t& nRequestTime = mapAlreadyAskedFor[inv];
352         if (fDebugNet)
353             printf("askfor %s   %" PRId64 " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
354
355         // Make sure not to reuse time indexes to keep things in the same order
356         int64_t nNow = (GetTime() - 1) * 1000000;
357         static int64_t nLastTime;
358         ++nLastTime;
359         nNow = std::max(nNow, nLastTime);
360         nLastTime = nNow;
361
362         // Each retry is 2 minutes after the last
363         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
364         mapAskFor.insert(std::make_pair(nRequestTime, inv));
365     }
366
367     void BeginMessage(const char* pszCommand)
368     {
369         ENTER_CRITICAL_SECTION(cs_vSend);
370         if (nHeaderStart != -1)
371             AbortMessage();
372         nHeaderStart = (int32_t)vSend.size();
373         vSend << CMessageHeader(pszCommand, 0);
374         nMessageStart = (uint32_t)vSend.size();
375         if (fDebug)
376             printf("sending: %s ", pszCommand);
377     }
378
379     void AbortMessage()
380     {
381         if (nHeaderStart < 0)
382             return;
383         vSend.resize(nHeaderStart);
384         nHeaderStart = -1;
385         nMessageStart = std::numeric_limits<uint32_t>::max();
386         LEAVE_CRITICAL_SECTION(cs_vSend);
387
388         if (fDebug)
389             printf("(aborted)\n");
390     }
391
392     void EndMessage();
393
394     void EndMessageAbortIfEmpty()
395     {
396         if (nHeaderStart < 0)
397             return;
398         int nSize = (int) vSend.size() - nMessageStart;
399         if (nSize > 0)
400             EndMessage();
401         else
402             AbortMessage();
403     }
404
405     void PushVersion();
406
407     template<typename ...Args>
408     void PushMessage(const char* pszCommand, const Args&... args)
409     {
410         try
411         {
412             BeginMessage(pszCommand);
413             if constexpr (sizeof...(Args) > 0)
414                 (vSend << ... << args);
415             EndMessage();
416         }
417         catch (...)
418         {
419             AbortMessage();
420             throw;
421         }
422     }
423
424     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
425     bool IsSubscribed(unsigned int nChannel);
426     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
427     void CancelSubscribe(unsigned int nChannel);
428     void CloseSocketDisconnect();
429     void Cleanup();
430
431
432     // Denial-of-service detection/prevention
433     // The idea is to detect peers that are behaving
434     // badly and disconnect/ban them, but do it in a
435     // one-coding-mistake-won't-shatter-the-entire-network
436     // way.
437     // IMPORTANT:  There should be nothing I can give a
438     // node that it will forward on that will make that
439     // node's peers drop it. If there is, an attacker
440     // can isolate a node and/or try to split the network.
441     // Dropping a node for sending stuff that is invalid
442     // now but might be valid in a later version is also
443     // dangerous, because it can cause a network split
444     // between nodes running old code and nodes running
445     // new code.
446     static void ClearBanned(); // needed for unit testing
447     static bool IsBanned(CNetAddr ip);
448     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
449     void copyStats(CNodeStats &stats);
450     // Network stats
451     static void RecordBytesRecv(uint64_t bytes);
452     static void RecordBytesSent(uint64_t bytes);
453
454     static uint64_t GetTotalBytesRecv();
455     static uint64_t GetTotalBytesSent();
456 };
457
458 class CTransaction;
459 void RelayTransaction(const CTransaction& tx, const uint256& hash);
460 void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss);
461
462
463 /** Return a timestamp in the future (in microseconds) for exponentially distributed events. */
464 int64_t PoissonNextSend(int64_t nNow, int average_interval_seconds);
465
466 #endif