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