PPCoin: RPC command 'getinfo' shows ip address seen by peer
[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
150     // inventory based relay
151     std::set<CInv> setInventoryKnown;
152     std::vector<CInv> vInventoryToSend;
153     CCriticalSection cs_inventory;
154     std::multimap<int64, 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 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& 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 nNow = (GetTime() - 1) * 1000000;
275         static int64 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     void PushVersion()
361     {
362         /// when NTP implemented, change to just nTime = GetAdjustedTime()
363         int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
364         CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
365         CAddress addrMe = (fUseProxy ? CAddress("0.0.0.0") : addrLocalHost);
366         RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
367         PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
368                     nLocalHostNonce, std::string(pszSubVer), nBestHeight);
369     }
370
371
372
373
374     void PushMessage(const char* pszCommand)
375     {
376         try
377         {
378             BeginMessage(pszCommand);
379             EndMessage();
380         }
381         catch (...)
382         {
383             AbortMessage();
384             throw;
385         }
386     }
387
388     template<typename T1>
389     void PushMessage(const char* pszCommand, const T1& a1)
390     {
391         try
392         {
393             BeginMessage(pszCommand);
394             vSend << a1;
395             EndMessage();
396         }
397         catch (...)
398         {
399             AbortMessage();
400             throw;
401         }
402     }
403
404     template<typename T1, typename T2>
405     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
406     {
407         try
408         {
409             BeginMessage(pszCommand);
410             vSend << a1 << a2;
411             EndMessage();
412         }
413         catch (...)
414         {
415             AbortMessage();
416             throw;
417         }
418     }
419
420     template<typename T1, typename T2, typename T3>
421     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
422     {
423         try
424         {
425             BeginMessage(pszCommand);
426             vSend << a1 << a2 << a3;
427             EndMessage();
428         }
429         catch (...)
430         {
431             AbortMessage();
432             throw;
433         }
434     }
435
436     template<typename T1, typename T2, typename T3, typename T4>
437     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
438     {
439         try
440         {
441             BeginMessage(pszCommand);
442             vSend << a1 << a2 << a3 << a4;
443             EndMessage();
444         }
445         catch (...)
446         {
447             AbortMessage();
448             throw;
449         }
450     }
451
452     template<typename T1, typename T2, typename T3, typename T4, typename T5>
453     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
454     {
455         try
456         {
457             BeginMessage(pszCommand);
458             vSend << a1 << a2 << a3 << a4 << a5;
459             EndMessage();
460         }
461         catch (...)
462         {
463             AbortMessage();
464             throw;
465         }
466     }
467
468     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
469     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
470     {
471         try
472         {
473             BeginMessage(pszCommand);
474             vSend << a1 << a2 << a3 << a4 << a5 << a6;
475             EndMessage();
476         }
477         catch (...)
478         {
479             AbortMessage();
480             throw;
481         }
482     }
483
484     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
485     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)
486     {
487         try
488         {
489             BeginMessage(pszCommand);
490             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
491             EndMessage();
492         }
493         catch (...)
494         {
495             AbortMessage();
496             throw;
497         }
498     }
499
500     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
501     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)
502     {
503         try
504         {
505             BeginMessage(pszCommand);
506             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
507             EndMessage();
508         }
509         catch (...)
510         {
511             AbortMessage();
512             throw;
513         }
514     }
515
516     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
517     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)
518     {
519         try
520         {
521             BeginMessage(pszCommand);
522             vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
523             EndMessage();
524         }
525         catch (...)
526         {
527             AbortMessage();
528             throw;
529         }
530     }
531
532
533     void PushRequest(const char* pszCommand,
534                      void (*fn)(void*, CDataStream&), void* param1)
535     {
536         uint256 hashReply;
537         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
538
539         CRITICAL_BLOCK(cs_mapRequests)
540             mapRequests[hashReply] = CRequestTracker(fn, param1);
541
542         PushMessage(pszCommand, hashReply);
543     }
544
545     template<typename T1>
546     void PushRequest(const char* pszCommand, const T1& a1,
547                      void (*fn)(void*, CDataStream&), void* param1)
548     {
549         uint256 hashReply;
550         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
551
552         CRITICAL_BLOCK(cs_mapRequests)
553             mapRequests[hashReply] = CRequestTracker(fn, param1);
554
555         PushMessage(pszCommand, hashReply, a1);
556     }
557
558     template<typename T1, typename T2>
559     void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
560                      void (*fn)(void*, CDataStream&), void* param1)
561     {
562         uint256 hashReply;
563         RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
564
565         CRITICAL_BLOCK(cs_mapRequests)
566             mapRequests[hashReply] = CRequestTracker(fn, param1);
567
568         PushMessage(pszCommand, hashReply, a1, a2);
569     }
570
571
572
573     void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
574     bool IsSubscribed(unsigned int nChannel);
575     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
576     void CancelSubscribe(unsigned int nChannel);
577     void CloseSocketDisconnect();
578     void Cleanup();
579
580
581     // Denial-of-service detection/prevention
582     // The idea is to detect peers that are behaving
583     // badly and disconnect/ban them, but do it in a
584     // one-coding-mistake-won't-shatter-the-entire-network
585     // way.
586     // IMPORTANT:  There should be nothing I can give a
587     // node that it will forward on that will make that
588     // node's peers drop it. If there is, an attacker
589     // can isolate a node and/or try to split the network.
590     // Dropping a node for sending stuff that is invalid
591     // now but might be valid in a later version is also
592     // dangerous, because it can cause a network split
593     // between nodes running old code and nodes running
594     // new code.
595     static void ClearBanned(); // needed for unit testing
596     static bool IsBanned(unsigned int ip);
597     bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
598 };
599
600
601
602
603
604
605
606
607
608
609 inline void RelayInventory(const CInv& inv)
610 {
611     // Put on lists to offer to the other nodes
612     CRITICAL_BLOCK(cs_vNodes)
613         BOOST_FOREACH(CNode* pnode, vNodes)
614             pnode->PushInventory(inv);
615 }
616
617 template<typename T>
618 void RelayMessage(const CInv& inv, const T& a)
619 {
620     CDataStream ss(SER_NETWORK);
621     ss.reserve(10000);
622     ss << a;
623     RelayMessage(inv, ss);
624 }
625
626 template<>
627 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
628 {
629     CRITICAL_BLOCK(cs_mapRelay)
630     {
631         // Expire old relay messages
632         while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
633         {
634             mapRelay.erase(vRelayExpiration.front().second);
635             vRelayExpiration.pop_front();
636         }
637
638         // Save original serialized message so newer versions are preserved
639         mapRelay[inv] = ss;
640         vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
641     }
642
643     RelayInventory(inv);
644 }
645
646
647
648
649
650
651
652
653 //
654 // Templates for the publish and subscription system.
655 // The object being published as T& obj needs to have:
656 //   a set<unsigned int> setSources member
657 //   specializations of AdvertInsert and AdvertErase
658 // Currently implemented for CTable and CProduct.
659 //
660
661 template<typename T>
662 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
663 {
664     // Add to sources
665     obj.setSources.insert(pfrom->addr.ip);
666
667     if (!AdvertInsert(obj))
668         return;
669
670     // Relay
671     CRITICAL_BLOCK(cs_vNodes)
672         BOOST_FOREACH(CNode* pnode, vNodes)
673             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
674                 pnode->PushMessage("publish", nChannel, nHops, obj);
675 }
676
677 template<typename T>
678 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
679 {
680     uint256 hash = obj.GetHash();
681
682     CRITICAL_BLOCK(cs_vNodes)
683         BOOST_FOREACH(CNode* pnode, vNodes)
684             if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
685                 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
686
687     AdvertErase(obj);
688 }
689
690 template<typename T>
691 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
692 {
693     // Remove a source
694     obj.setSources.erase(pfrom->addr.ip);
695
696     // If no longer supported by any sources, cancel it
697     if (obj.setSources.empty())
698         AdvertStopPublish(pfrom, nChannel, nHops, obj);
699 }
700
701 #endif