Move DNS Seed lookup to a new thread.
[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 WIN32
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 bool BindListenPort(std::string& strError=REF(std::string()));
44 void StartNode(void* parg);
45 bool StopNode();
46
47 enum
48 {
49     MSG_TX = 1,
50     MSG_BLOCK,
51 };
52
53 class CRequestTracker
54 {
55 public:
56     void (*fn)(void*, CDataStream&);
57     void* param1;
58
59     explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
60     {
61         fn = fnIn;
62         param1 = param1In;
63     }
64
65     bool IsNull()
66     {
67         return fn == NULL;
68     }
69 };
70
71
72
73
74
75 extern bool fClient;
76 extern bool fAllowDNS;
77 extern uint64 nLocalServices;
78 extern CAddress addrLocalHost;
79 extern uint64 nLocalHostNonce;
80 extern boost::array<int, 10> vnThreadsRunning;
81
82 extern std::vector<CNode*> vNodes;
83 extern CCriticalSection cs_vNodes;
84 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
85 extern CCriticalSection cs_mapAddresses;
86 extern std::map<CInv, CDataStream> mapRelay;
87 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
88 extern CCriticalSection cs_mapRelay;
89 extern std::map<CInv, int64> mapAlreadyAskedFor;
90
91 // Settings
92 extern int fUseProxy;
93 extern CAddress addrProxy;
94
95
96
97
98
99
100 class CNode
101 {
102 public:
103     // socket
104     uint64 nServices;
105     SOCKET hSocket;
106     CDataStream vSend;
107     CDataStream vRecv;
108     CCriticalSection cs_vSend;
109     CCriticalSection cs_vRecv;
110     int64 nLastSend;
111     int64 nLastRecv;
112     int64 nLastSendEmpty;
113     int64 nTimeConnected;
114     unsigned int nHeaderStart;
115     unsigned int nMessageStart;
116     CAddress addr;
117     int nVersion;
118     std::string strSubVer;
119     bool fClient;
120     bool fInbound;
121     bool fNetworkNode;
122     bool fSuccessfullyConnected;
123     bool fDisconnect;
124 protected:
125     int nRefCount;
126
127     // Denial-of-service detection/prevention
128     // Key is ip address, value is banned-until-time
129     static std::map<unsigned int, int64> setBanned;
130     static CCriticalSection cs_setBanned;
131     int nMisbehavior;
132
133 public:
134     int64 nReleaseTime;
135     std::map<uint256, CRequestTracker> mapRequests;
136     CCriticalSection cs_mapRequests;
137     uint256 hashContinue;
138     CBlockIndex* pindexLastGetBlocksBegin;
139     uint256 hashLastGetBlocksEnd;
140     int nStartingHeight;
141
142     // flood relay
143     std::vector<CAddress> vAddrToSend;
144     std::set<CAddress> setAddrKnown;
145     bool fGetAddr;
146     std::set<uint256> setKnown;
147
148     // inventory based relay
149     std::set<CInv> setInventoryKnown;
150     std::vector<CInv> vInventoryToSend;
151     CCriticalSection cs_inventory;
152     std::multimap<int64, CInv> mapAskFor;
153
154     // publish and subscription
155     std::vector<char> vfSubscribe;
156
157     CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
158     {
159         nServices = 0;
160         hSocket = hSocketIn;
161         vSend.SetType(SER_NETWORK);
162         vSend.SetVersion(0);
163         vRecv.SetType(SER_NETWORK);
164         vRecv.SetVersion(0);
165         // Version 0.2 obsoletes 20 Feb 2012
166         if (GetTime() > 1329696000)
167         {
168             vSend.SetVersion(209);
169             vRecv.SetVersion(209);
170         }
171         nLastSend = 0;
172         nLastRecv = 0;
173         nLastSendEmpty = GetTime();
174         nTimeConnected = GetTime();
175         nHeaderStart = -1;
176         nMessageStart = -1;
177         addr = addrIn;
178         nVersion = 0;
179         strSubVer = "";
180         fClient = false; // set by version message
181         fInbound = fInboundIn;
182         fNetworkNode = false;
183         fSuccessfullyConnected = false;
184         fDisconnect = false;
185         nRefCount = 0;
186         nReleaseTime = 0;
187         hashContinue = 0;
188         pindexLastGetBlocksBegin = 0;
189         hashLastGetBlocksEnd = 0;
190         nStartingHeight = -1;
191         fGetAddr = false;
192         vfSubscribe.assign(256, false);
193         nMisbehavior = 0;
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         CRITICAL_BLOCK(cs_inventory)
254             setInventoryKnown.insert(inv);
255     }
256
257     void PushInventory(const CInv& inv)
258     {
259         CRITICAL_BLOCK(cs_inventory)
260             if (!setInventoryKnown.count(inv))
261                 vInventoryToSend.push_back(inv);
262     }
263
264     void AskFor(const CInv& inv)
265     {
266         // We're using mapAskFor as a priority queue,
267         // the key is the earliest time the request can be sent
268         int64& nRequestTime = mapAlreadyAskedFor[inv];
269         printf("askfor %s   %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
270
271         // Make sure not to reuse time indexes to keep things in the same order
272         int64 nNow = (GetTime() - 1) * 1000000;
273         static int64 nLastTime;
274         nLastTime = nNow = std::max(nNow, ++nLastTime);
275
276         // Each retry is 2 minutes after the last
277         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
278         mapAskFor.insert(std::make_pair(nRequestTime, inv));
279     }
280
281
282
283     void BeginMessage(const char* pszCommand)
284     {
285         cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
286         if (nHeaderStart != -1)
287             AbortMessage();
288         nHeaderStart = vSend.size();
289         vSend << CMessageHeader(pszCommand, 0);
290         nMessageStart = vSend.size();
291         if (fDebug) {
292             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
293             printf("sending: %s ", pszCommand);
294         }
295     }
296
297     void AbortMessage()
298     {
299         if (nHeaderStart == -1)
300             return;
301         vSend.resize(nHeaderStart);
302         nHeaderStart = -1;
303         nMessageStart = -1;
304         cs_vSend.Leave();
305
306         if (fDebug)
307             printf("(aborted)\n");
308     }
309
310     void EndMessage()
311     {
312         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
313         {
314             printf("dropmessages DROPPING SEND MESSAGE\n");
315             AbortMessage();
316             return;
317         }
318
319         if (nHeaderStart == -1)
320             return;
321
322         // Set the size
323         unsigned int nSize = vSend.size() - nMessageStart;
324         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
325
326         // Set the checksum
327         if (vSend.GetVersion() >= 209)
328         {
329             uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
330             unsigned int nChecksum = 0;
331             memcpy(&nChecksum, &hash, sizeof(nChecksum));
332             assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
333             memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
334         }
335
336         if (fDebug) {
337             printf("(%d bytes)\n", nSize);
338         }
339
340         nHeaderStart = -1;
341         nMessageStart = -1;
342         cs_vSend.Leave();
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         /// when NTP implemented, change to just nTime = GetAdjustedTime()
361         int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
362         CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
363         CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
364         RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
365         PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
366                     nLocalHostNonce, std::string(pszSubVer), nBestHeight);
367     }
368
369
370
371
372     void PushMessage(const char* pszCommand)
373     {
374         try
375         {
376             BeginMessage(pszCommand);
377             EndMessage();
378         }
379         catch (...)
380         {
381             AbortMessage();
382             throw;
383         }
384     }
385
386     template<typename T1>
387     void PushMessage(const char* pszCommand, const T1& a1)
388     {
389         try
390         {
391             BeginMessage(pszCommand);
392             vSend << a1;
393             EndMessage();
394         }
395         catch (...)
396         {
397             AbortMessage();
398             throw;
399         }
400     }
401
402     template<typename T1, typename T2>
403     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
404     {
405         try
406         {
407             BeginMessage(pszCommand);
408             vSend << a1 << a2;
409             EndMessage();
410         }
411         catch (...)
412         {
413             AbortMessage();
414             throw;
415         }
416     }
417
418     template<typename T1, typename T2, typename T3>
419     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
420     {
421         try
422         {
423             BeginMessage(pszCommand);
424             vSend << a1 << a2 << a3;
425             EndMessage();
426         }
427         catch (...)
428         {
429             AbortMessage();
430             throw;
431         }
432     }
433
434     template<typename T1, typename T2, typename T3, typename T4>
435     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
436     {
437         try
438         {
439             BeginMessage(pszCommand);
440             vSend << a1 << a2 << a3 << a4;
441             EndMessage();
442         }
443         catch (...)
444         {
445             AbortMessage();
446             throw;
447         }
448     }
449
450     template<typename T1, typename T2, typename T3, typename T4, typename T5>
451     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
452     {
453         try
454         {
455             BeginMessage(pszCommand);
456             vSend << a1 << a2 << a3 << a4 << a5;
457             EndMessage();
458         }
459         catch (...)
460         {
461             AbortMessage();
462             throw;
463         }
464     }
465
466     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
467     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
468     {
469         try
470         {
471             BeginMessage(pszCommand);
472             vSend << a1 << a2 << a3 << a4 << a5 << a6;
473             EndMessage();
474         }
475         catch (...)
476         {
477             AbortMessage();
478             throw;
479         }
480     }
481
482     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
483     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)
484     {
485         try
486         {
487             BeginMessage(pszCommand);
488             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
489             EndMessage();
490         }
491         catch (...)
492         {
493             AbortMessage();
494             throw;
495         }
496     }
497
498     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
499     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)
500     {
501         try
502         {
503             BeginMessage(pszCommand);
504             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
505             EndMessage();
506         }
507         catch (...)
508         {
509             AbortMessage();
510             throw;
511         }
512     }
513
514     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
515     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)
516     {
517         try
518         {
519             BeginMessage(pszCommand);
520             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
521             EndMessage();
522         }
523         catch (...)
524         {
525             AbortMessage();
526             throw;
527         }
528     }
529
530
531     void PushRequest(const char* pszCommand,
532                      void (*fn)(void*, CDataStream&), void* param1)
533     {
534         uint256 hashReply;
535         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
536
537         CRITICAL_BLOCK(cs_mapRequests)
538             mapRequests[hashReply] = CRequestTracker(fn, param1);
539
540         PushMessage(pszCommand, hashReply);
541     }
542
543     template<typename T1>
544     void PushRequest(const char* pszCommand, const T1& a1,
545                      void (*fn)(void*, CDataStream&), void* param1)
546     {
547         uint256 hashReply;
548         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
549
550         CRITICAL_BLOCK(cs_mapRequests)
551             mapRequests[hashReply] = CRequestTracker(fn, param1);
552
553         PushMessage(pszCommand, hashReply, a1);
554     }
555
556     template<typename T1, typename T2>
557     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
558                      void (*fn)(void*, CDataStream&), void* param1)
559     {
560         uint256 hashReply;
561         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
562
563         CRITICAL_BLOCK(cs_mapRequests)
564             mapRequests[hashReply] = CRequestTracker(fn, param1);
565
566         PushMessage(pszCommand, hashReply, a1, a2);
567     }
568
569
570
571     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
572     bool IsSubscribed(unsigned int nChannel);
573     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
574     void CancelSubscribe(unsigned int nChannel);
575     void CloseSocketDisconnect();
576     void Cleanup();
577
578
579     // Denial-of-service detection/prevention
580     // The idea is to detect peers that are behaving
581     // badly and disconnect/ban them, but do it in a
582     // one-coding-mistake-won't-shatter-the-entire-network
583     // way.
584     // IMPORTANT:  There should be nothing I can give a
585     // node that it will forward on that will make that
586     // node's peers drop it. If there is, an attacker
587     // can isolate a node and/or try to split the network.
588     // Dropping a node for sending stuff that is invalid
589     // now but might be valid in a later version is also
590     // dangerous, because it can cause a network split
591     // between nodes running old code and nodes running
592     // new code.
593     static void ClearBanned(); // needed for unit testing
594     static bool IsBanned(unsigned int ip);
595     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
596 };
597
598
599
600
601
602
603
604
605
606
607 inline void RelayInventory(const CInv& inv)
608 {
609     // Put on lists to offer to the other nodes
610     CRITICAL_BLOCK(cs_vNodes)
611         BOOST_FOREACH(CNode* pnode, vNodes)
612             pnode->PushInventory(inv);
613 }
614
615 template<typename T>
616 void RelayMessage(const CInv& inv, const T& a)
617 {
618     CDataStream ss(SER_NETWORK);
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     CRITICAL_BLOCK(cs_mapRelay)
628     {
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[inv] = ss;
638         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
639     }
640
641     RelayInventory(inv);
642 }
643
644
645
646
647
648
649
650
651 //
652 // Templates for the publish and subscription system.
653 // The object being published as T& obj needs to have:
654 //   a set<unsigned int> setSources member
655 //   specializations of AdvertInsert and AdvertErase
656 // Currently implemented for CTable and CProduct.
657 //
658
659 template<typename T>
660 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
661 {
662     // Add to sources
663     obj.setSources.insert(pfrom->addr.ip);
664
665     if (!AdvertInsert(obj))
666         return;
667
668     // Relay
669     CRITICAL_BLOCK(cs_vNodes)
670         BOOST_FOREACH(CNode* pnode, vNodes)
671             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
672                 pnode->PushMessage("publish", nChannel, nHops, obj);
673 }
674
675 template<typename T>
676 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
677 {
678     uint256 hash = obj.GetHash();
679
680     CRITICAL_BLOCK(cs_vNodes)
681         BOOST_FOREACH(CNode* pnode, vNodes)
682             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
683                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
684
685     AdvertErase(obj);
686 }
687
688 template<typename T>
689 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
690 {
691     // Remove a source
692     obj.setSources.erase(pfrom->addr.ip);
693
694     // If no longer supported by any sources, cancel it
695     if (obj.setSources.empty())
696         AdvertStopPublish(pfrom, nChannel, nHops, obj);
697 }
698
699 #endif