Use standard C99 (and Qt) types for 64-bit integers
[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 <stdint.h>
9
10 #include <deque>
11 #include <boost/array.hpp>
12 #include <boost/foreach.hpp>
13 #include <openssl/rand.h>
14
15 #ifndef WIN32
16 #include <arpa/inet.h>
17 #endif
18
19 #include "protocol.h"
20
21 class CAddrDB;
22 class CRequestTracker;
23 class CNode;
24 class CBlockIndex;
25 extern int nBestHeight;
26 extern int nConnectTimeout;
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 ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
35 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
36 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
37 bool GetMyExternalIP(unsigned int& ipRet);
38 bool AddAddress(CAddress addr, int64_t nTimePenalty=0, CAddrDB *pAddrDB=NULL);
39 void AddressCurrentlyConnected(const CAddress& addr);
40 CNode* FindNode(unsigned int ip);
41 CNode* ConnectNode(CAddress addrConnect, int64_t nTimeout=0);
42 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
43 bool AnySubscribed(unsigned int nChannel);
44 void MapPort(bool fMapPort);
45 bool BindListenPort(std::string& strError=REF(std::string()));
46 void StartNode(void* parg);
47 bool StopNode();
48
49 enum
50 {
51     MSG_TX = 1,
52     MSG_BLOCK,
53 };
54
55 class CRequestTracker
56 {
57 public:
58     void (*fn)(void*, CDataStream&);
59     void* param1;
60
61     explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
62     {
63         fn = fnIn;
64         param1 = param1In;
65     }
66
67     bool IsNull()
68     {
69         return fn == NULL;
70     }
71 };
72
73
74
75
76
77 extern bool fClient;
78 extern bool fAllowDNS;
79 extern uint64_t nLocalServices;
80 extern CAddress addrLocalHost;
81 extern uint64_t nLocalHostNonce;
82 extern boost::array<int, 10> vnThreadsRunning;
83
84 extern std::vector<CNode*> vNodes;
85 extern CCriticalSection cs_vNodes;
86 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
87 extern CCriticalSection cs_mapAddresses;
88 extern std::map<CInv, CDataStream> mapRelay;
89 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
90 extern CCriticalSection cs_mapRelay;
91 extern std::map<CInv, int64_t> mapAlreadyAskedFor;
92
93 // Settings
94 extern int fUseProxy;
95 extern CAddress addrProxy;
96
97
98
99
100
101
102 class CNode
103 {
104 public:
105     // socket
106     uint64_t nServices;
107     SOCKET hSocket;
108     CDataStream vSend;
109     CDataStream vRecv;
110     CCriticalSection cs_vSend;
111     CCriticalSection cs_vRecv;
112     int64_t nLastSend;
113     int64_t nLastRecv;
114     int64_t nLastSendEmpty;
115     int64_t nTimeConnected;
116     unsigned int nHeaderStart;
117     unsigned int nMessageStart;
118     CAddress addr;
119     int nVersion;
120     std::string strSubVer;
121     bool fClient;
122     bool fInbound;
123     bool fNetworkNode;
124     bool fSuccessfullyConnected;
125     bool fDisconnect;
126 protected:
127     int nRefCount;
128
129     // Denial-of-service detection/prevention
130     // Key is ip address, value is banned-until-time
131     static std::map<unsigned int, int64_t> setBanned;
132     static CCriticalSection cs_setBanned;
133     int nMisbehavior;
134
135 public:
136     int64_t nReleaseTime;
137     std::map<uint256, CRequestTracker> mapRequests;
138     CCriticalSection cs_mapRequests;
139     uint256 hashContinue;
140     CBlockIndex* pindexLastGetBlocksBegin;
141     uint256 hashLastGetBlocksEnd;
142     int nStartingHeight;
143
144     // flood relay
145     std::vector<CAddress> vAddrToSend;
146     std::set<CAddress> setAddrKnown;
147     bool fGetAddr;
148     std::set<uint256> setKnown;
149
150     // inventory based relay
151     std::set<CInv> setInventoryKnown;
152     std::vector<CInv> vInventoryToSend;
153     CCriticalSection cs_inventory;
154     std::multimap<int64_t, CInv> mapAskFor;
155
156     // publish and subscription
157     std::vector<char> vfSubscribe;
158
159     CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
160     {
161         nServices = 0;
162         hSocket = hSocketIn;
163         vSend.SetType(SER_NETWORK);
164         vSend.SetVersion(0);
165         vRecv.SetType(SER_NETWORK);
166         vRecv.SetVersion(0);
167         // Version 0.2 obsoletes 20 Feb 2012
168         if (GetTime() > 1329696000)
169         {
170             vSend.SetVersion(209);
171             vRecv.SetVersion(209);
172         }
173         nLastSend = 0;
174         nLastRecv = 0;
175         nLastSendEmpty = GetTime();
176         nTimeConnected = GetTime();
177         nHeaderStart = -1;
178         nMessageStart = -1;
179         addr = addrIn;
180         nVersion = 0;
181         strSubVer = "";
182         fClient = false; // set by version message
183         fInbound = fInboundIn;
184         fNetworkNode = false;
185         fSuccessfullyConnected = false;
186         fDisconnect = false;
187         nRefCount = 0;
188         nReleaseTime = 0;
189         hashContinue = 0;
190         pindexLastGetBlocksBegin = 0;
191         hashLastGetBlocksEnd = 0;
192         nStartingHeight = -1;
193         fGetAddr = false;
194         vfSubscribe.assign(256, false);
195         nMisbehavior = 0;
196
197         // Be shy and don't send version until we hear
198         if (!fInbound)
199             PushVersion();
200     }
201
202     ~CNode()
203     {
204         if (hSocket != INVALID_SOCKET)
205         {
206             closesocket(hSocket);
207             hSocket = INVALID_SOCKET;
208         }
209     }
210
211 private:
212     CNode(const CNode&);
213     void operator=(const CNode&);
214 public:
215
216
217     int GetRefCount()
218     {
219         return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
220     }
221
222     CNode* AddRef(int64_t nTimeout=0)
223     {
224         if (nTimeout != 0)
225             nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
226         else
227             nRefCount++;
228         return this;
229     }
230
231     void Release()
232     {
233         nRefCount--;
234     }
235
236
237
238     void AddAddressKnown(const CAddress& addr)
239     {
240         setAddrKnown.insert(addr);
241     }
242
243     void PushAddress(const CAddress& addr)
244     {
245         // Known checking here is only to save space from duplicates.
246         // SendMessages will filter it again for knowns that were added
247         // after addresses were pushed.
248         if (addr.IsValid() && !setAddrKnown.count(addr))
249             vAddrToSend.push_back(addr);
250     }
251
252
253     void AddInventoryKnown(const CInv& inv)
254     {
255         CRITICAL_BLOCK(cs_inventory)
256             setInventoryKnown.insert(inv);
257     }
258
259     void PushInventory(const CInv& inv)
260     {
261         CRITICAL_BLOCK(cs_inventory)
262             if (!setInventoryKnown.count(inv))
263                 vInventoryToSend.push_back(inv);
264     }
265
266     void AskFor(const CInv& inv)
267     {
268         // We're using mapAskFor as a priority queue,
269         // the key is the earliest time the request can be sent
270         int64_t& nRequestTime = mapAlreadyAskedFor[inv];
271         printf("askfor %s   %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
272
273         // Make sure not to reuse time indexes to keep things in the same order
274         int64_t nNow = (GetTime() - 1) * 1000000;
275         static int64_t nLastTime;
276         nLastTime = nNow = std::max(nNow, ++nLastTime);
277
278         // Each retry is 2 minutes after the last
279         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
280         mapAskFor.insert(std::make_pair(nRequestTime, inv));
281     }
282
283
284
285     void BeginMessage(const char* pszCommand)
286     {
287         cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
288         if (nHeaderStart != -1)
289             AbortMessage();
290         nHeaderStart = vSend.size();
291         vSend << CMessageHeader(pszCommand, 0);
292         nMessageStart = vSend.size();
293         if (fDebug) {
294             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
295             printf("sending: %s ", pszCommand);
296         }
297     }
298
299     void AbortMessage()
300     {
301         if (nHeaderStart == -1)
302             return;
303         vSend.resize(nHeaderStart);
304         nHeaderStart = -1;
305         nMessageStart = -1;
306         cs_vSend.Leave();
307
308         if (fDebug)
309             printf("(aborted)\n");
310     }
311
312     void EndMessage()
313     {
314         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
315         {
316             printf("dropmessages DROPPING SEND MESSAGE\n");
317             AbortMessage();
318             return;
319         }
320
321         if (nHeaderStart == -1)
322             return;
323
324         // Set the size
325         unsigned int nSize = vSend.size() - nMessageStart;
326         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
327
328         // Set the checksum
329         if (vSend.GetVersion() >= 209)
330         {
331             uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
332             unsigned int nChecksum = 0;
333             memcpy(&nChecksum, &hash, sizeof(nChecksum));
334             assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
335             memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
336         }
337
338         if (fDebug) {
339             printf("(%d bytes)\n", nSize);
340         }
341
342         nHeaderStart = -1;
343         nMessageStart = -1;
344         cs_vSend.Leave();
345     }
346
347     void EndMessageAbortIfEmpty()
348     {
349         if (nHeaderStart == -1)
350             return;
351         int nSize = vSend.size() - nMessageStart;
352         if (nSize > 0)
353             EndMessage();
354         else
355             AbortMessage();
356     }
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(unsigned int 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