Update License in File Headers
[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 COPYING 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     signed 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;
268         nNow = std::max(nNow, nLastTime);
269         nLastTime = nNow;
270
271         // Each retry is 2 minutes after the last
272         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
273         mapAskFor.insert(std::make_pair(nRequestTime, inv));
274     }
275
276
277
278     void BeginMessage(const char* pszCommand)
279     {
280         ENTER_CRITICAL_SECTION(cs_vSend);
281         if (nHeaderStart != -1)
282             AbortMessage();
283         nHeaderStart = vSend.size();
284         vSend << CMessageHeader(pszCommand, 0);
285         nMessageStart = vSend.size();
286         if (fDebug) {
287             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
288             printf("sending: %s ", pszCommand);
289         }
290     }
291
292     void AbortMessage()
293     {
294         if (nHeaderStart == -1)
295             return;
296         vSend.resize(nHeaderStart);
297         nHeaderStart = -1;
298         nMessageStart = -1;
299         LEAVE_CRITICAL_SECTION(cs_vSend);
300
301         if (fDebug)
302             printf("(aborted)\n");
303     }
304
305     void EndMessage()
306     {
307         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
308         {
309             printf("dropmessages DROPPING SEND MESSAGE\n");
310             AbortMessage();
311             return;
312         }
313
314         if (nHeaderStart == -1)
315             return;
316
317         // Set the size
318         unsigned int nSize = vSend.size() - nMessageStart;
319         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
320
321         // Set the checksum
322         if (vSend.GetVersion() >= 209)
323         {
324             uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
325             unsigned int nChecksum = 0;
326             memcpy(&nChecksum, &hash, sizeof(nChecksum));
327             assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
328             memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
329         }
330
331         if (fDebug) {
332             printf("(%d bytes)\n", nSize);
333         }
334
335         nHeaderStart = -1;
336         nMessageStart = -1;
337         LEAVE_CRITICAL_SECTION(cs_vSend);
338     }
339
340     void EndMessageAbortIfEmpty()
341     {
342         if (nHeaderStart == -1)
343             return;
344         int nSize = vSend.size() - nMessageStart;
345         if (nSize > 0)
346             EndMessage();
347         else
348             AbortMessage();
349     }
350
351
352
353     void PushVersion()
354     {
355         /// when NTP implemented, change to just nTime = GetAdjustedTime()
356         int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
357         CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
358         CAddress addrMe = (fUseProxy || !addrLocalHost.IsRoutable() ? CAddress("0.0.0.0") : addrLocalHost);
359         RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
360         PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
361                     nLocalHostNonce, std::string(pszSubVer), nBestHeight);
362     }
363
364
365
366
367     void PushMessage(const char* pszCommand)
368     {
369         try
370         {
371             BeginMessage(pszCommand);
372             EndMessage();
373         }
374         catch (...)
375         {
376             AbortMessage();
377             throw;
378         }
379     }
380
381     template<typename T1>
382     void PushMessage(const char* pszCommand, const T1& a1)
383     {
384         try
385         {
386             BeginMessage(pszCommand);
387             vSend << a1;
388             EndMessage();
389         }
390         catch (...)
391         {
392             AbortMessage();
393             throw;
394         }
395     }
396
397     template<typename T1, typename T2>
398     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
399     {
400         try
401         {
402             BeginMessage(pszCommand);
403             vSend << a1 << a2;
404             EndMessage();
405         }
406         catch (...)
407         {
408             AbortMessage();
409             throw;
410         }
411     }
412
413     template<typename T1, typename T2, typename T3>
414     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
415     {
416         try
417         {
418             BeginMessage(pszCommand);
419             vSend << a1 << a2 << a3;
420             EndMessage();
421         }
422         catch (...)
423         {
424             AbortMessage();
425             throw;
426         }
427     }
428
429     template<typename T1, typename T2, typename T3, typename T4>
430     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
431     {
432         try
433         {
434             BeginMessage(pszCommand);
435             vSend << a1 << a2 << a3 << a4;
436             EndMessage();
437         }
438         catch (...)
439         {
440             AbortMessage();
441             throw;
442         }
443     }
444
445     template<typename T1, typename T2, typename T3, typename T4, typename T5>
446     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
447     {
448         try
449         {
450             BeginMessage(pszCommand);
451             vSend << a1 << a2 << a3 << a4 << a5;
452             EndMessage();
453         }
454         catch (...)
455         {
456             AbortMessage();
457             throw;
458         }
459     }
460
461     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
462     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
463     {
464         try
465         {
466             BeginMessage(pszCommand);
467             vSend << a1 << a2 << a3 << a4 << a5 << a6;
468             EndMessage();
469         }
470         catch (...)
471         {
472             AbortMessage();
473             throw;
474         }
475     }
476
477     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
478     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)
479     {
480         try
481         {
482             BeginMessage(pszCommand);
483             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
484             EndMessage();
485         }
486         catch (...)
487         {
488             AbortMessage();
489             throw;
490         }
491     }
492
493     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
494     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)
495     {
496         try
497         {
498             BeginMessage(pszCommand);
499             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
500             EndMessage();
501         }
502         catch (...)
503         {
504             AbortMessage();
505             throw;
506         }
507     }
508
509     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
510     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)
511     {
512         try
513         {
514             BeginMessage(pszCommand);
515             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
516             EndMessage();
517         }
518         catch (...)
519         {
520             AbortMessage();
521             throw;
522         }
523     }
524
525
526     void PushRequest(const char* pszCommand,
527                      void (*fn)(void*, CDataStream&), void* param1)
528     {
529         uint256 hashReply;
530         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
531
532         CRITICAL_BLOCK(cs_mapRequests)
533             mapRequests[hashReply] = CRequestTracker(fn, param1);
534
535         PushMessage(pszCommand, hashReply);
536     }
537
538     template<typename T1>
539     void PushRequest(const char* pszCommand, const T1& a1,
540                      void (*fn)(void*, CDataStream&), void* param1)
541     {
542         uint256 hashReply;
543         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
544
545         CRITICAL_BLOCK(cs_mapRequests)
546             mapRequests[hashReply] = CRequestTracker(fn, param1);
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         CRITICAL_BLOCK(cs_mapRequests)
559             mapRequests[hashReply] = CRequestTracker(fn, param1);
560
561         PushMessage(pszCommand, hashReply, a1, a2);
562     }
563
564
565
566     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
567     bool IsSubscribed(unsigned int nChannel);
568     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
569     void CancelSubscribe(unsigned int nChannel);
570     void CloseSocketDisconnect();
571     void Cleanup();
572 };
573
574
575
576
577
578
579
580
581
582
583 inline void RelayInventory(const CInv& inv)
584 {
585     // Put on lists to offer to the other nodes
586     CRITICAL_BLOCK(cs_vNodes)
587         BOOST_FOREACH(CNode* pnode, vNodes)
588             pnode->PushInventory(inv);
589 }
590
591 template<typename T>
592 void RelayMessage(const CInv& inv, const T& a)
593 {
594     CDataStream ss(SER_NETWORK);
595     ss.reserve(10000);
596     ss << a;
597     RelayMessage(inv, ss);
598 }
599
600 template<>
601 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
602 {
603     CRITICAL_BLOCK(cs_mapRelay)
604     {
605         // Expire old relay messages
606         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
607         {
608             mapRelay.erase(vRelayExpiration.front().second);
609             vRelayExpiration.pop_front();
610         }
611
612         // Save original serialized message so newer versions are preserved
613         mapRelay[inv] = ss;
614         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
615     }
616
617     RelayInventory(inv);
618 }
619
620
621
622
623
624
625
626
627 //
628 // Templates for the publish and subscription system.
629 // The object being published as T& obj needs to have:
630 //   a set<unsigned int> setSources member
631 //   specializations of AdvertInsert and AdvertErase
632 // Currently implemented for CTable and CProduct.
633 //
634
635 template<typename T>
636 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
637 {
638     // Add to sources
639     obj.setSources.insert(pfrom->addr.ip);
640
641     if (!AdvertInsert(obj))
642         return;
643
644     // Relay
645     CRITICAL_BLOCK(cs_vNodes)
646         BOOST_FOREACH(CNode* pnode, vNodes)
647             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
648                 pnode->PushMessage("publish", nChannel, nHops, obj);
649 }
650
651 template<typename T>
652 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
653 {
654     uint256 hash = obj.GetHash();
655
656     CRITICAL_BLOCK(cs_vNodes)
657         BOOST_FOREACH(CNode* pnode, vNodes)
658             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
659                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
660
661     AdvertErase(obj);
662 }
663
664 template<typename T>
665 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
666 {
667     // Remove a source
668     obj.setSources.erase(pfrom->addr.ip);
669
670     // If no longer supported by any sources, cancel it
671     if (obj.setSources.empty())
672         AdvertStopPublish(pfrom, nChannel, nHops, obj);
673 }
674
675 #endif