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