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