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 __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 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 public:
127     int64 nReleaseTime;
128     std::map<uint256, CRequestTracker> mapRequests;
129     CCriticalSection cs_mapRequests;
130     uint256 hashContinue;
131     CBlockIndex* pindexLastGetBlocksBegin;
132     uint256 hashLastGetBlocksEnd;
133     int nStartingHeight;
134
135     // flood relay
136     std::vector<CAddress> vAddrToSend;
137     std::set<CAddress> setAddrKnown;
138     bool fGetAddr;
139     std::set<uint256> setKnown;
140
141     // inventory based relay
142     std::set<CInv> setInventoryKnown;
143     std::vector<CInv> vInventoryToSend;
144     CCriticalSection cs_inventory;
145     std::multimap<int64, CInv> mapAskFor;
146
147     // publish and subscription
148     std::vector<char> vfSubscribe;
149
150
151     CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
152     {
153         nServices = 0;
154         hSocket = hSocketIn;
155         vSend.SetType(SER_NETWORK);
156         vSend.SetVersion(0);
157         vRecv.SetType(SER_NETWORK);
158         vRecv.SetVersion(0);
159         // Version 0.2 obsoletes 20 Feb 2012
160         if (GetTime() > 1329696000)
161         {
162             vSend.SetVersion(209);
163             vRecv.SetVersion(209);
164         }
165         nLastSend = 0;
166         nLastRecv = 0;
167         nLastSendEmpty = GetTime();
168         nTimeConnected = GetTime();
169         nHeaderStart = -1;
170         nMessageStart = -1;
171         addr = addrIn;
172         nVersion = 0;
173         strSubVer = "";
174         fClient = false; // set by version message
175         fInbound = fInboundIn;
176         fNetworkNode = false;
177         fSuccessfullyConnected = false;
178         fDisconnect = false;
179         nRefCount = 0;
180         nReleaseTime = 0;
181         hashContinue = 0;
182         pindexLastGetBlocksBegin = 0;
183         hashLastGetBlocksEnd = 0;
184         nStartingHeight = -1;
185         fGetAddr = false;
186         vfSubscribe.assign(256, false);
187
188         // Be shy and don't send version until we hear
189         if (!fInbound)
190             PushVersion();
191     }
192
193     ~CNode()
194     {
195         if (hSocket != INVALID_SOCKET)
196         {
197             closesocket(hSocket);
198             hSocket = INVALID_SOCKET;
199         }
200     }
201
202 private:
203     CNode(const CNode&);
204     void operator=(const CNode&);
205 public:
206
207
208     int GetRefCount()
209     {
210         return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
211     }
212
213     CNode* AddRef(int64 nTimeout=0)
214     {
215         if (nTimeout != 0)
216             nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
217         else
218             nRefCount++;
219         return this;
220     }
221
222     void Release()
223     {
224         nRefCount--;
225     }
226
227
228
229     void AddAddressKnown(const CAddress& addr)
230     {
231         setAddrKnown.insert(addr);
232     }
233
234     void PushAddress(const CAddress& addr)
235     {
236         // Known checking here is only to save space from duplicates.
237         // SendMessages will filter it again for knowns that were added
238         // after addresses were pushed.
239         if (addr.IsValid() && !setAddrKnown.count(addr))
240             vAddrToSend.push_back(addr);
241     }
242
243
244     void AddInventoryKnown(const CInv& inv)
245     {
246         CRITICAL_BLOCK(cs_inventory)
247             setInventoryKnown.insert(inv);
248     }
249
250     void PushInventory(const CInv& inv)
251     {
252         CRITICAL_BLOCK(cs_inventory)
253             if (!setInventoryKnown.count(inv))
254                 vInventoryToSend.push_back(inv);
255     }
256
257     void AskFor(const CInv& inv)
258     {
259         // We're using mapAskFor as a priority queue,
260         // the key is the earliest time the request can be sent
261         int64& nRequestTime = mapAlreadyAskedFor[inv];
262         printf("askfor %s   %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
263
264         // Make sure not to reuse time indexes to keep things in the same order
265         int64 nNow = (GetTime() - 1) * 1000000;
266         static int64 nLastTime;
267         nLastTime = nNow = std::max(nNow, ++nLastTime);
268
269         // Each retry is 2 minutes after the last
270         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
271         mapAskFor.insert(std::make_pair(nRequestTime, inv));
272     }
273
274
275
276     void BeginMessage(const char* pszCommand)
277     {
278         cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
279         if (nHeaderStart != -1)
280             AbortMessage();
281         nHeaderStart = vSend.size();
282         vSend << CMessageHeader(pszCommand, 0);
283         nMessageStart = vSend.size();
284         if (fDebug) {
285             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
286             printf("sending: %s ", pszCommand);
287         }
288     }
289
290     void AbortMessage()
291     {
292         if (nHeaderStart == -1)
293             return;
294         vSend.resize(nHeaderStart);
295         nHeaderStart = -1;
296         nMessageStart = -1;
297         cs_vSend.Leave();
298
299         if (fDebug)
300             printf("(aborted)\n");
301     }
302
303     void EndMessage()
304     {
305         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
306         {
307             printf("dropmessages DROPPING SEND MESSAGE\n");
308             AbortMessage();
309             return;
310         }
311
312         if (nHeaderStart == -1)
313             return;
314
315         // Set the size
316         unsigned int nSize = vSend.size() - nMessageStart;
317         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
318
319         // Set the checksum
320         if (vSend.GetVersion() >= 209)
321         {
322             uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
323             unsigned int nChecksum = 0;
324             memcpy(&nChecksum, &hash, sizeof(nChecksum));
325             assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
326             memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
327         }
328
329         if (fDebug) {
330             printf("(%d bytes)\n", nSize);
331         }
332
333         nHeaderStart = -1;
334         nMessageStart = -1;
335         cs_vSend.Leave();
336     }
337
338     void EndMessageAbortIfEmpty()
339     {
340         if (nHeaderStart == -1)
341             return;
342         int nSize = vSend.size() - nMessageStart;
343         if (nSize > 0)
344             EndMessage();
345         else
346             AbortMessage();
347     }
348
349
350
351     void PushVersion()
352     {
353         /// when NTP implemented, change to just nTime = GetAdjustedTime()
354         int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
355         CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
356         CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
357         RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
358         PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
359                     nLocalHostNonce, std::string(pszSubVer), nBestHeight);
360     }
361
362
363
364
365     void PushMessage(const char* pszCommand)
366     {
367         try
368         {
369             BeginMessage(pszCommand);
370             EndMessage();
371         }
372         catch (...)
373         {
374             AbortMessage();
375             throw;
376         }
377     }
378
379     template<typename T1>
380     void PushMessage(const char* pszCommand, const T1& a1)
381     {
382         try
383         {
384             BeginMessage(pszCommand);
385             vSend << a1;
386             EndMessage();
387         }
388         catch (...)
389         {
390             AbortMessage();
391             throw;
392         }
393     }
394
395     template<typename T1, typename T2>
396     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
397     {
398         try
399         {
400             BeginMessage(pszCommand);
401             vSend << a1 << a2;
402             EndMessage();
403         }
404         catch (...)
405         {
406             AbortMessage();
407             throw;
408         }
409     }
410
411     template<typename T1, typename T2, typename T3>
412     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
413     {
414         try
415         {
416             BeginMessage(pszCommand);
417             vSend << a1 << a2 << a3;
418             EndMessage();
419         }
420         catch (...)
421         {
422             AbortMessage();
423             throw;
424         }
425     }
426
427     template<typename T1, typename T2, typename T3, typename T4>
428     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
429     {
430         try
431         {
432             BeginMessage(pszCommand);
433             vSend << a1 << a2 << a3 << a4;
434             EndMessage();
435         }
436         catch (...)
437         {
438             AbortMessage();
439             throw;
440         }
441     }
442
443     template<typename T1, typename T2, typename T3, typename T4, typename T5>
444     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
445     {
446         try
447         {
448             BeginMessage(pszCommand);
449             vSend << a1 << a2 << a3 << a4 << a5;
450             EndMessage();
451         }
452         catch (...)
453         {
454             AbortMessage();
455             throw;
456         }
457     }
458
459     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
460     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
461     {
462         try
463         {
464             BeginMessage(pszCommand);
465             vSend << a1 << a2 << a3 << a4 << a5 << a6;
466             EndMessage();
467         }
468         catch (...)
469         {
470             AbortMessage();
471             throw;
472         }
473     }
474
475     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
476     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)
477     {
478         try
479         {
480             BeginMessage(pszCommand);
481             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
482             EndMessage();
483         }
484         catch (...)
485         {
486             AbortMessage();
487             throw;
488         }
489     }
490
491     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
492     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)
493     {
494         try
495         {
496             BeginMessage(pszCommand);
497             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
498             EndMessage();
499         }
500         catch (...)
501         {
502             AbortMessage();
503             throw;
504         }
505     }
506
507     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
508     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)
509     {
510         try
511         {
512             BeginMessage(pszCommand);
513             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
514             EndMessage();
515         }
516         catch (...)
517         {
518             AbortMessage();
519             throw;
520         }
521     }
522
523
524     void PushRequest(const char* pszCommand,
525                      void (*fn)(void*, CDataStream&), void* param1)
526     {
527         uint256 hashReply;
528         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
529
530         CRITICAL_BLOCK(cs_mapRequests)
531             mapRequests[hashReply] = CRequestTracker(fn, param1);
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         CRITICAL_BLOCK(cs_mapRequests)
544             mapRequests[hashReply] = CRequestTracker(fn, param1);
545
546         PushMessage(pszCommand, hashReply, a1);
547     }
548
549     template<typename T1, typename T2>
550     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
551                      void (*fn)(void*, CDataStream&), void* param1)
552     {
553         uint256 hashReply;
554         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
555
556         CRITICAL_BLOCK(cs_mapRequests)
557             mapRequests[hashReply] = CRequestTracker(fn, param1);
558
559         PushMessage(pszCommand, hashReply, a1, a2);
560     }
561
562
563
564     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
565     bool IsSubscribed(unsigned int nChannel);
566     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
567     void CancelSubscribe(unsigned int nChannel);
568     void CloseSocketDisconnect();
569     void Cleanup();
570 };
571
572
573
574
575
576
577
578
579
580
581 inline void RelayInventory(const CInv& inv)
582 {
583     // Put on lists to offer to the other nodes
584     CRITICAL_BLOCK(cs_vNodes)
585         BOOST_FOREACH(CNode* pnode, vNodes)
586             pnode->PushInventory(inv);
587 }
588
589 template<typename T>
590 void RelayMessage(const CInv& inv, const T& a)
591 {
592     CDataStream ss(SER_NETWORK);
593     ss.reserve(10000);
594     ss << a;
595     RelayMessage(inv, ss);
596 }
597
598 template<>
599 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
600 {
601     CRITICAL_BLOCK(cs_mapRelay)
602     {
603         // Expire old relay messages
604         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
605         {
606             mapRelay.erase(vRelayExpiration.front().second);
607             vRelayExpiration.pop_front();
608         }
609
610         // Save original serialized message so newer versions are preserved
611         mapRelay[inv] = ss;
612         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
613     }
614
615     RelayInventory(inv);
616 }
617
618
619
620
621
622
623
624
625 //
626 // Templates for the publish and subscription system.
627 // The object being published as T& obj needs to have:
628 //   a set<unsigned int> setSources member
629 //   specializations of AdvertInsert and AdvertErase
630 // Currently implemented for CTable and CProduct.
631 //
632
633 template<typename T>
634 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
635 {
636     // Add to sources
637     obj.setSources.insert(pfrom->addr.ip);
638
639     if (!AdvertInsert(obj))
640         return;
641
642     // Relay
643     CRITICAL_BLOCK(cs_vNodes)
644         BOOST_FOREACH(CNode* pnode, vNodes)
645             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
646                 pnode->PushMessage("publish", nChannel, nHops, obj);
647 }
648
649 template<typename T>
650 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
651 {
652     uint256 hash = obj.GetHash();
653
654     CRITICAL_BLOCK(cs_vNodes)
655         BOOST_FOREACH(CNode* pnode, vNodes)
656             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
657                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
658
659     AdvertErase(obj);
660 }
661
662 template<typename T>
663 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
664 {
665     // Remove a source
666     obj.setSources.erase(pfrom->addr.ip);
667
668     // If no longer supported by any sources, cancel it
669     if (obj.setSources.empty())
670         AdvertStopPublish(pfrom, nChannel, nHops, obj);
671 }
672
673 #endif