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