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