PPCoin: Define synchronized checkpoint message
[novacoin.git] / src / net.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_NET_H
7 #define BITCOIN_NET_H
8
9 #include <deque>
10 #include <boost/array.hpp>
11 #include <boost/foreach.hpp>
12 #include <openssl/rand.h>
13
14 #ifndef WIN32
15 #include <arpa/inet.h>
16 #endif
17
18 #include "protocol.h"
19
20 class CAddrDB;
21 class CRequestTracker;
22 class CNode;
23 class CBlockIndex;
24 extern int nBestHeight;
25 extern int nConnectTimeout;
26
27
28
29 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
30 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
31 static const unsigned int PUBLISH_HOPS = 5;
32
33 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
34 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
35 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
36 bool GetMyExternalIP(unsigned int& ipRet);
37 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
38 void AddressCurrentlyConnected(const CAddress& addr);
39 CNode* FindNode(unsigned int ip);
40 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
41 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
42 bool AnySubscribed(unsigned int nChannel);
43 void MapPort(bool fMapPort);
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 CAddress addrSeenByPeer;
81 extern uint64 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, CInv> > vRelayExpiration;
90 extern CCriticalSection cs_mapRelay;
91 extern std::map<CInv, int64> 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 nServices;
107     SOCKET hSocket;
108     CDataStream vSend;
109     CDataStream vRecv;
110     CCriticalSection cs_vSend;
111     CCriticalSection cs_vRecv;
112     int64 nLastSend;
113     int64 nLastRecv;
114     int64 nLastSendEmpty;
115     int64 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> setBanned;
132     static CCriticalSection cs_setBanned;
133     int nMisbehavior;
134
135 public:
136     int64 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     uint256 hashCheckpointKnown; // ppcoin: known sent sync-checkpoint
150
151     // inventory based relay
152     std::set<CInv> setInventoryKnown;
153     std::vector<CInv> vInventoryToSend;
154     CCriticalSection cs_inventory;
155     std::multimap<int64, CInv> mapAskFor;
156
157     // publish and subscription
158     std::vector<char> vfSubscribe;
159
160     CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
161     {
162         nServices = 0;
163         hSocket = hSocketIn;
164         vSend.SetType(SER_NETWORK);
165         vSend.SetVersion(0);
166         vRecv.SetType(SER_NETWORK);
167         vRecv.SetVersion(0);
168         // Version 0.2 obsoletes 20 Feb 2012
169         if (GetTime() > 1329696000)
170         {
171             vSend.SetVersion(209);
172             vRecv.SetVersion(209);
173         }
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         hashCheckpointKnown = 0;
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 = nNow = std::max(nNow, ++nLastTime);
279
280         // Each retry is 2 minutes after the last
281         nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
282         mapAskFor.insert(std::make_pair(nRequestTime, inv));
283     }
284
285
286
287     void BeginMessage(const char* pszCommand)
288     {
289         cs_vSend.Enter("cs_vSend", __FILE__, __LINE__);
290         if (nHeaderStart != -1)
291             AbortMessage();
292         nHeaderStart = vSend.size();
293         vSend << CMessageHeader(pszCommand, 0);
294         nMessageStart = vSend.size();
295         if (fDebug) {
296             printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
297             printf("sending: %s ", pszCommand);
298         }
299     }
300
301     void AbortMessage()
302     {
303         if (nHeaderStart == -1)
304             return;
305         vSend.resize(nHeaderStart);
306         nHeaderStart = -1;
307         nMessageStart = -1;
308         cs_vSend.Leave();
309
310         if (fDebug)
311             printf("(aborted)\n");
312     }
313
314     void EndMessage()
315     {
316         if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
317         {
318             printf("dropmessages DROPPING SEND MESSAGE\n");
319             AbortMessage();
320             return;
321         }
322
323         if (nHeaderStart == -1)
324             return;
325
326         // Set the size
327         unsigned int nSize = vSend.size() - nMessageStart;
328         memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
329
330         // Set the checksum
331         if (vSend.GetVersion() >= 209)
332         {
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
340         if (fDebug) {
341             printf("(%d bytes)\n", nSize);
342         }
343
344         nHeaderStart = -1;
345         nMessageStart = -1;
346         cs_vSend.Leave();
347     }
348
349     void EndMessageAbortIfEmpty()
350     {
351         if (nHeaderStart == -1)
352             return;
353         int nSize = vSend.size() - nMessageStart;
354         if (nSize > 0)
355             EndMessage();
356         else
357             AbortMessage();
358     }
359
360
361
362     void PushVersion()
363     {
364         /// when NTP implemented, change to just nTime = GetAdjustedTime()
365         int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
366         CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
367         CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
368         RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
369         PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
370                     nLocalHostNonce, std::string(pszSubVer), nBestHeight);
371     }
372
373
374
375
376     void PushMessage(const char* pszCommand)
377     {
378         try
379         {
380             BeginMessage(pszCommand);
381             EndMessage();
382         }
383         catch (...)
384         {
385             AbortMessage();
386             throw;
387         }
388     }
389
390     template<typename T1>
391     void PushMessage(const char* pszCommand, const T1& a1)
392     {
393         try
394         {
395             BeginMessage(pszCommand);
396             vSend << a1;
397             EndMessage();
398         }
399         catch (...)
400         {
401             AbortMessage();
402             throw;
403         }
404     }
405
406     template<typename T1, typename T2>
407     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
408     {
409         try
410         {
411             BeginMessage(pszCommand);
412             vSend << a1 << a2;
413             EndMessage();
414         }
415         catch (...)
416         {
417             AbortMessage();
418             throw;
419         }
420     }
421
422     template<typename T1, typename T2, typename T3>
423     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
424     {
425         try
426         {
427             BeginMessage(pszCommand);
428             vSend << a1 << a2 << a3;
429             EndMessage();
430         }
431         catch (...)
432         {
433             AbortMessage();
434             throw;
435         }
436     }
437
438     template<typename T1, typename T2, typename T3, typename T4>
439     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
440     {
441         try
442         {
443             BeginMessage(pszCommand);
444             vSend << a1 << a2 << a3 << a4;
445             EndMessage();
446         }
447         catch (...)
448         {
449             AbortMessage();
450             throw;
451         }
452     }
453
454     template<typename T1, typename T2, typename T3, typename T4, typename T5>
455     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
456     {
457         try
458         {
459             BeginMessage(pszCommand);
460             vSend << a1 << a2 << a3 << a4 << a5;
461             EndMessage();
462         }
463         catch (...)
464         {
465             AbortMessage();
466             throw;
467         }
468     }
469
470     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
471     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
472     {
473         try
474         {
475             BeginMessage(pszCommand);
476             vSend << a1 << a2 << a3 << a4 << a5 << a6;
477             EndMessage();
478         }
479         catch (...)
480         {
481             AbortMessage();
482             throw;
483         }
484     }
485
486     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
487     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)
488     {
489         try
490         {
491             BeginMessage(pszCommand);
492             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
493             EndMessage();
494         }
495         catch (...)
496         {
497             AbortMessage();
498             throw;
499         }
500     }
501
502     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
503     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)
504     {
505         try
506         {
507             BeginMessage(pszCommand);
508             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
509             EndMessage();
510         }
511         catch (...)
512         {
513             AbortMessage();
514             throw;
515         }
516     }
517
518     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
519     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)
520     {
521         try
522         {
523             BeginMessage(pszCommand);
524             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
525             EndMessage();
526         }
527         catch (...)
528         {
529             AbortMessage();
530             throw;
531         }
532     }
533
534
535     void PushRequest(const char* pszCommand,
536                      void (*fn)(void*, CDataStream&), void* param1)
537     {
538         uint256 hashReply;
539         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
540
541         CRITICAL_BLOCK(cs_mapRequests)
542             mapRequests[hashReply] = CRequestTracker(fn, param1);
543
544         PushMessage(pszCommand, hashReply);
545     }
546
547     template<typename T1>
548     void PushRequest(const char* pszCommand, const T1& a1,
549                      void (*fn)(void*, CDataStream&), void* param1)
550     {
551         uint256 hashReply;
552         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
553
554         CRITICAL_BLOCK(cs_mapRequests)
555             mapRequests[hashReply] = CRequestTracker(fn, param1);
556
557         PushMessage(pszCommand, hashReply, a1);
558     }
559
560     template<typename T1, typename T2>
561     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
562                      void (*fn)(void*, CDataStream&), void* param1)
563     {
564         uint256 hashReply;
565         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
566
567         CRITICAL_BLOCK(cs_mapRequests)
568             mapRequests[hashReply] = CRequestTracker(fn, param1);
569
570         PushMessage(pszCommand, hashReply, a1, a2);
571     }
572
573
574
575     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
576     bool IsSubscribed(unsigned int nChannel);
577     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
578     void CancelSubscribe(unsigned int nChannel);
579     void CloseSocketDisconnect();
580     void Cleanup();
581
582
583     // Denial-of-service detection/prevention
584     // The idea is to detect peers that are behaving
585     // badly and disconnect/ban them, but do it in a
586     // one-coding-mistake-won't-shatter-the-entire-network
587     // way.
588     // IMPORTANT:  There should be nothing I can give a
589     // node that it will forward on that will make that
590     // node's peers drop it. If there is, an attacker
591     // can isolate a node and/or try to split the network.
592     // Dropping a node for sending stuff that is invalid
593     // now but might be valid in a later version is also
594     // dangerous, because it can cause a network split
595     // between nodes running old code and nodes running
596     // new code.
597     static void ClearBanned(); // needed for unit testing
598     static bool IsBanned(unsigned int ip);
599     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
600 };
601
602
603
604
605
606
607
608
609
610
611 inline void RelayInventory(const CInv& inv)
612 {
613     // Put on lists to offer to the other nodes
614     CRITICAL_BLOCK(cs_vNodes)
615         BOOST_FOREACH(CNode* pnode, vNodes)
616             pnode->PushInventory(inv);
617 }
618
619 template<typename T>
620 void RelayMessage(const CInv& inv, const T& a)
621 {
622     CDataStream ss(SER_NETWORK);
623     ss.reserve(10000);
624     ss << a;
625     RelayMessage(inv, ss);
626 }
627
628 template<>
629 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
630 {
631     CRITICAL_BLOCK(cs_mapRelay)
632     {
633         // Expire old relay messages
634         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
635         {
636             mapRelay.erase(vRelayExpiration.front().second);
637             vRelayExpiration.pop_front();
638         }
639
640         // Save original serialized message so newer versions are preserved
641         mapRelay[inv] = ss;
642         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
643     }
644
645     RelayInventory(inv);
646 }
647
648
649
650
651
652
653
654
655 //
656 // Templates for the publish and subscription system.
657 // The object being published as T& obj needs to have:
658 //   a set<unsigned int> setSources member
659 //   specializations of AdvertInsert and AdvertErase
660 // Currently implemented for CTable and CProduct.
661 //
662
663 template<typename T>
664 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
665 {
666     // Add to sources
667     obj.setSources.insert(pfrom->addr.ip);
668
669     if (!AdvertInsert(obj))
670         return;
671
672     // Relay
673     CRITICAL_BLOCK(cs_vNodes)
674         BOOST_FOREACH(CNode* pnode, vNodes)
675             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
676                 pnode->PushMessage("publish", nChannel, nHops, obj);
677 }
678
679 template<typename T>
680 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
681 {
682     uint256 hash = obj.GetHash();
683
684     CRITICAL_BLOCK(cs_vNodes)
685         BOOST_FOREACH(CNode* pnode, vNodes)
686             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
687                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
688
689     AdvertErase(obj);
690 }
691
692 template<typename T>
693 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
694 {
695     // Remove a source
696     obj.setSources.erase(pfrom->addr.ip);
697
698     // If no longer supported by any sources, cancel it
699     if (obj.setSources.empty())
700         AdvertStopPublish(pfrom, nChannel, nHops, obj);
701 }
702
703 #endif