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