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