Post-feb20 simplifications
[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 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 WIN32
14 #include <arpa/inet.h>
15 #endif
16
17 #include "netbase.h"
18 #include "protocol.h"
19
20 class CAddrDB;
21 class CRequestTracker;
22 class CNode;
23 class CBlockIndex;
24 extern int nBestHeight;
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 GetMyExternalIP(CNetAddr& ipRet);
33 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
34 void AddressCurrentlyConnected(const CService& addr);
35 CNode* FindNode(const CNetAddr& ip);
36 CNode* FindNode(const CService& ip);
37 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
38 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
39 bool AnySubscribed(unsigned int nChannel);
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
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
82     THREAD_MAX
83 };
84
85 extern bool fClient;
86 extern bool fAllowDNS;
87 extern uint64 nLocalServices;
88 extern CAddress addrLocalHost;
89 extern uint64 nLocalHostNonce;
90 extern boost::array<int, THREAD_MAX> vnThreadsRunning;
91
92 extern std::vector<CNode*> vNodes;
93 extern CCriticalSection cs_vNodes;
94 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
95 extern CCriticalSection cs_mapAddresses;
96 extern std::map<CInv, CDataStream> mapRelay;
97 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
98 extern CCriticalSection cs_mapRelay;
99 extern std::map<CInv, int64> mapAlreadyAskedFor;
100
101
102
103
104
105
106
107 class CNode
108 {
109 public:
110     // socket
111     uint64 nServices;
112     SOCKET hSocket;
113     CDataStream vSend;
114     CDataStream vRecv;
115     CCriticalSection cs_vSend;
116     CCriticalSection cs_vRecv;
117     int64 nLastSend;
118     int64 nLastRecv;
119     int64 nLastSendEmpty;
120     int64 nTimeConnected;
121     unsigned int nHeaderStart;
122     unsigned int nMessageStart;
123     CAddress addr;
124     int nVersion;
125     std::string strSubVer;
126     bool fClient;
127     bool fInbound;
128     bool fNetworkNode;
129     bool fSuccessfullyConnected;
130     bool fDisconnect;
131 protected:
132     int nRefCount;
133
134     // Denial-of-service detection/prevention
135     // Key is ip address, value is banned-until-time
136     static std::map<CNetAddr, int64> setBanned;
137     static CCriticalSection cs_setBanned;
138     int nMisbehavior;
139
140 public:
141     int64 nReleaseTime;
142     std::map<uint256, CRequestTracker> mapRequests;
143     CCriticalSection cs_mapRequests;
144     uint256 hashContinue;
145     CBlockIndex* pindexLastGetBlocksBegin;
146     uint256 hashLastGetBlocksEnd;
147     int nStartingHeight;
148
149     // flood relay
150     std::vector<CAddress> vAddrToSend;
151     std::set<CAddress> setAddrKnown;
152     bool fGetAddr;
153     std::set<uint256> setKnown;
154
155     // inventory based relay
156     std::set<CInv> setInventoryKnown;
157     std::vector<CInv> vInventoryToSend;
158     CCriticalSection cs_inventory;
159     std::multimap<int64, CInv> mapAskFor;
160
161     // publish and subscription
162     std::vector<char> vfSubscribe;
163
164     CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
165     {
166         nServices = 0;
167         hSocket = hSocketIn;
168         vSend.SetType(SER_NETWORK);
169         vRecv.SetType(SER_NETWORK);
170         vSend.SetVersion(209);
171         vRecv.SetVersion(209);
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;
276         nNow = std::max(nNow, nLastTime);
277         nLastTime = nNow;
278
279         // Each retry is 2 minutes after the last
280         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
281         mapAskFor.insert(std::make_pair(nRequestTime, inv));
282     }
283
284
285
286     void BeginMessage(const char* pszCommand)
287     {
288         ENTER_CRITICAL_SECTION(cs_vSend);
289         if (nHeaderStart != -1)
290             AbortMessage();
291         nHeaderStart = vSend.size();
292         vSend << CMessageHeader(pszCommand, 0);
293         nMessageStart = vSend.size();
294         if (fDebug) {
295             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
296             printf("sending: %s ", pszCommand);
297         }
298     }
299
300     void AbortMessage()
301     {
302         if (nHeaderStart == -1)
303             return;
304         vSend.resize(nHeaderStart);
305         nHeaderStart = -1;
306         nMessageStart = -1;
307         LEAVE_CRITICAL_SECTION(cs_vSend);
308
309         if (fDebug)
310             printf("(aborted)\n");
311     }
312
313     void EndMessage()
314     {
315         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
316         {
317             printf("dropmessages DROPPING SEND MESSAGE\n");
318             AbortMessage();
319             return;
320         }
321
322         if (nHeaderStart == -1)
323             return;
324
325         // Set the size
326         unsigned int nSize = vSend.size() - nMessageStart;
327         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
328
329         // Set the checksum
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         if (fDebug) {
337             printf("(%d bytes)\n", nSize);
338         }
339
340         nHeaderStart = -1;
341         nMessageStart = -1;
342         LEAVE_CRITICAL_SECTION(cs_vSend);
343     }
344
345     void EndMessageAbortIfEmpty()
346     {
347         if (nHeaderStart == -1)
348             return;
349         int nSize = vSend.size() - nMessageStart;
350         if (nSize > 0)
351             EndMessage();
352         else
353             AbortMessage();
354     }
355
356
357
358     void PushVersion();
359
360
361     void PushMessage(const char* pszCommand)
362     {
363         try
364         {
365             BeginMessage(pszCommand);
366             EndMessage();
367         }
368         catch (...)
369         {
370             AbortMessage();
371             throw;
372         }
373     }
374
375     template<typename T1>
376     void PushMessage(const char* pszCommand, const T1& a1)
377     {
378         try
379         {
380             BeginMessage(pszCommand);
381             vSend << a1;
382             EndMessage();
383         }
384         catch (...)
385         {
386             AbortMessage();
387             throw;
388         }
389     }
390
391     template<typename T1, typename T2>
392     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
393     {
394         try
395         {
396             BeginMessage(pszCommand);
397             vSend << a1 << a2;
398             EndMessage();
399         }
400         catch (...)
401         {
402             AbortMessage();
403             throw;
404         }
405     }
406
407     template<typename T1, typename T2, typename T3>
408     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
409     {
410         try
411         {
412             BeginMessage(pszCommand);
413             vSend << a1 << a2 << a3;
414             EndMessage();
415         }
416         catch (...)
417         {
418             AbortMessage();
419             throw;
420         }
421     }
422
423     template<typename T1, typename T2, typename T3, typename T4>
424     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
425     {
426         try
427         {
428             BeginMessage(pszCommand);
429             vSend << a1 << a2 << a3 << a4;
430             EndMessage();
431         }
432         catch (...)
433         {
434             AbortMessage();
435             throw;
436         }
437     }
438
439     template<typename T1, typename T2, typename T3, typename T4, typename T5>
440     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
441     {
442         try
443         {
444             BeginMessage(pszCommand);
445             vSend << a1 << a2 << a3 << a4 << a5;
446             EndMessage();
447         }
448         catch (...)
449         {
450             AbortMessage();
451             throw;
452         }
453     }
454
455     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
456     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
457     {
458         try
459         {
460             BeginMessage(pszCommand);
461             vSend << a1 << a2 << a3 << a4 << a5 << a6;
462             EndMessage();
463         }
464         catch (...)
465         {
466             AbortMessage();
467             throw;
468         }
469     }
470
471     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
472     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)
473     {
474         try
475         {
476             BeginMessage(pszCommand);
477             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
478             EndMessage();
479         }
480         catch (...)
481         {
482             AbortMessage();
483             throw;
484         }
485     }
486
487     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
488     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)
489     {
490         try
491         {
492             BeginMessage(pszCommand);
493             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
494             EndMessage();
495         }
496         catch (...)
497         {
498             AbortMessage();
499             throw;
500         }
501     }
502
503     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
504     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)
505     {
506         try
507         {
508             BeginMessage(pszCommand);
509             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
510             EndMessage();
511         }
512         catch (...)
513         {
514             AbortMessage();
515             throw;
516         }
517     }
518
519
520     void PushRequest(const char* pszCommand,
521                      void (*fn)(void*, CDataStream&), void* param1)
522     {
523         uint256 hashReply;
524         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
525
526         CRITICAL_BLOCK(cs_mapRequests)
527             mapRequests[hashReply] = CRequestTracker(fn, param1);
528
529         PushMessage(pszCommand, hashReply);
530     }
531
532     template<typename T1>
533     void PushRequest(const char* pszCommand, const T1& a1,
534                      void (*fn)(void*, CDataStream&), void* param1)
535     {
536         uint256 hashReply;
537         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
538
539         CRITICAL_BLOCK(cs_mapRequests)
540             mapRequests[hashReply] = CRequestTracker(fn, param1);
541
542         PushMessage(pszCommand, hashReply, a1);
543     }
544
545     template<typename T1, typename T2>
546     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
547                      void (*fn)(void*, CDataStream&), void* param1)
548     {
549         uint256 hashReply;
550         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
551
552         CRITICAL_BLOCK(cs_mapRequests)
553             mapRequests[hashReply] = CRequestTracker(fn, param1);
554
555         PushMessage(pszCommand, hashReply, a1, a2);
556     }
557
558
559
560     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
561     bool IsSubscribed(unsigned int nChannel);
562     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
563     void CancelSubscribe(unsigned int nChannel);
564     void CloseSocketDisconnect();
565     void Cleanup();
566
567
568     // Denial-of-service detection/prevention
569     // The idea is to detect peers that are behaving
570     // badly and disconnect/ban them, but do it in a
571     // one-coding-mistake-won't-shatter-the-entire-network
572     // way.
573     // IMPORTANT:  There should be nothing I can give a
574     // node that it will forward on that will make that
575     // node's peers drop it. If there is, an attacker
576     // can isolate a node and/or try to split the network.
577     // Dropping a node for sending stuff that is invalid
578     // now but might be valid in a later version is also
579     // dangerous, because it can cause a network split
580     // between nodes running old code and nodes running
581     // new code.
582     static void ClearBanned(); // needed for unit testing
583     static bool IsBanned(CNetAddr ip);
584     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
585 };
586
587
588
589
590
591
592
593
594
595
596 inline void RelayInventory(const CInv& inv)
597 {
598     // Put on lists to offer to the other nodes
599     CRITICAL_BLOCK(cs_vNodes)
600         BOOST_FOREACH(CNode* pnode, vNodes)
601             pnode->PushInventory(inv);
602 }
603
604 template<typename T>
605 void RelayMessage(const CInv& inv, const T& a)
606 {
607     CDataStream ss(SER_NETWORK);
608     ss.reserve(10000);
609     ss << a;
610     RelayMessage(inv, ss);
611 }
612
613 template<>
614 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
615 {
616     CRITICAL_BLOCK(cs_mapRelay)
617     {
618         // Expire old relay messages
619         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
620         {
621             mapRelay.erase(vRelayExpiration.front().second);
622             vRelayExpiration.pop_front();
623         }
624
625         // Save original serialized message so newer versions are preserved
626         mapRelay[inv] = ss;
627         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
628     }
629
630     RelayInventory(inv);
631 }
632
633
634
635
636
637
638
639
640 //
641 // Templates for the publish and subscription system.
642 // The object being published as T& obj needs to have:
643 //   a set<unsigned int> setSources member
644 //   specializations of AdvertInsert and AdvertErase
645 // Currently implemented for CTable and CProduct.
646 //
647
648 template<typename T>
649 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
650 {
651     // Add to sources
652     obj.setSources.insert(pfrom->addr.ip);
653
654     if (!AdvertInsert(obj))
655         return;
656
657     // Relay
658     CRITICAL_BLOCK(cs_vNodes)
659         BOOST_FOREACH(CNode* pnode, vNodes)
660             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
661                 pnode->PushMessage("publish", nChannel, nHops, obj);
662 }
663
664 template<typename T>
665 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
666 {
667     uint256 hash = obj.GetHash();
668
669     CRITICAL_BLOCK(cs_vNodes)
670         BOOST_FOREACH(CNode* pnode, vNodes)
671             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
672                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
673
674     AdvertErase(obj);
675 }
676
677 template<typename T>
678 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
679 {
680     // Remove a source
681     obj.setSources.erase(pfrom->addr.ip);
682
683     // If no longer supported by any sources, cancel it
684     if (obj.setSources.empty())
685         AdvertStopPublish(pfrom, nChannel, nHops, obj);
686 }
687
688 #endif