Back to home page

Bitcoin sources

 
 

    


0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2014 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
0005 
0006 #ifndef BITCOIN_NET_H
0007 #define BITCOIN_NET_H
0008 
0009 #include "bloom.h"
0010 #include "compat.h"
0011 #include "hash.h"
0012 #include "limitedmap.h"
0013 #include "mruset.h"
0014 #include "netbase.h"
0015 #include "protocol.h"
0016 #include "random.h"
0017 #include "streams.h"
0018 #include "sync.h"
0019 #include "uint256.h"
0020 #include "utilstrencodings.h"
0021 
0022 #include <deque>
0023 #include <stdint.h>
0024 
0025 #ifndef WIN32
0026 #include <arpa/inet.h>
0027 #endif
0028 
0029 #include <boost/filesystem/path.hpp>
0030 #include <boost/foreach.hpp>
0031 #include <boost/signals2/signal.hpp>
0032 
0033 class CAddrMan;
0034 class CBlockIndex;
0035 class CNode;
0036 
0037 namespace boost {
0038     class thread_group;
0039 } // namespace boost
0040 
0041 /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */
0042 static const int PING_INTERVAL = 2 * 60;
0043 /** Time after which to disconnect, after waiting for a ping response (or inactivity). */
0044 static const int TIMEOUT_INTERVAL = 20 * 60;
0045 /** The maximum number of entries in an 'inv' protocol message */
0046 static const unsigned int MAX_INV_SZ = 50000;
0047 /** The maximum number of new addresses to accumulate before announcing. */
0048 static const unsigned int MAX_ADDR_TO_SEND = 1000;
0049 /** -listen default */
0050 static const bool DEFAULT_LISTEN = true;
0051 /** -upnp default */
0052 #ifdef USE_UPNP
0053 static const bool DEFAULT_UPNP = USE_UPNP;
0054 #else
0055 static const bool DEFAULT_UPNP = false;
0056 #endif
0057 /** The maximum number of entries in mapAskFor */
0058 static const size_t MAPASKFOR_MAX_SZ = MAX_INV_SZ;
0059 
0060 unsigned int ReceiveFloodSize();
0061 unsigned int SendBufferSize();
0062 
0063 void AddOneShot(std::string strDest);
0064 bool RecvLine(SOCKET hSocket, std::string& strLine);
0065 void AddressCurrentlyConnected(const CService& addr);
0066 CNode* FindNode(const CNetAddr& ip);
0067 CNode* FindNode(const std::string& addrName);
0068 CNode* FindNode(const CService& ip);
0069 CNode* ConnectNode(CAddress addrConnect, const char *pszDest = NULL);
0070 bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false);
0071 void MapPort(bool fUseUPnP);
0072 unsigned short GetListenPort();
0073 bool BindListenPort(const CService &bindAddr, std::string& strError, bool fWhitelisted = false);
0074 void StartNode(boost::thread_group& threadGroup);
0075 bool StopNode();
0076 void SocketSendData(CNode *pnode);
0077 
0078 typedef int NodeId;
0079 
0080 // Signals for message handling
0081 struct CNodeSignals
0082 {
0083     boost::signals2::signal<int ()> GetHeight;
0084     boost::signals2::signal<bool (CNode*)> ProcessMessages;
0085     boost::signals2::signal<bool (CNode*, bool)> SendMessages;
0086     boost::signals2::signal<void (NodeId, const CNode*)> InitializeNode;
0087     boost::signals2::signal<void (NodeId)> FinalizeNode;
0088 };
0089 
0090 
0091 CNodeSignals& GetNodeSignals();
0092 
0093 
0094 enum
0095 {
0096     LOCAL_NONE,   // unknown
0097     LOCAL_IF,     // address a local interface listens on
0098     LOCAL_BIND,   // address explicit bound to
0099     LOCAL_UPNP,   // address reported by UPnP
0100     LOCAL_MANUAL, // address explicitly specified (-externalip=)
0101 
0102     LOCAL_MAX
0103 };
0104 
0105 bool IsPeerAddrLocalGood(CNode *pnode);
0106 void AdvertizeLocal(CNode *pnode);
0107 void SetLimited(enum Network net, bool fLimited = true);
0108 bool IsLimited(enum Network net);
0109 bool IsLimited(const CNetAddr& addr);
0110 bool AddLocal(const CService& addr, int nScore = LOCAL_NONE);
0111 bool AddLocal(const CNetAddr& addr, int nScore = LOCAL_NONE);
0112 bool SeenLocal(const CService& addr);
0113 bool IsLocal(const CService& addr);
0114 bool GetLocal(CService &addr, const CNetAddr *paddrPeer = NULL);
0115 bool IsReachable(enum Network net);
0116 bool IsReachable(const CNetAddr &addr);
0117 void SetReachable(enum Network net, bool fFlag = true);
0118 CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL);
0119 
0120 
0121 extern bool fDiscover;
0122 extern bool fListen;
0123 extern uint64_t nLocalServices;
0124 extern uint64_t nLocalHostNonce;
0125 extern CAddrMan addrman;
0126 extern int nMaxConnections;
0127 
0128 extern std::vector<CNode*> vNodes;
0129 extern CCriticalSection cs_vNodes;
0130 extern std::map<CInv, CDataStream> mapRelay;
0131 extern std::deque<std::pair<int64_t, CInv> > vRelayExpiration;
0132 extern CCriticalSection cs_mapRelay;
0133 extern limitedmap<CInv, int64_t> mapAlreadyAskedFor;
0134 
0135 extern std::vector<std::string> vAddedNodes;
0136 extern CCriticalSection cs_vAddedNodes;
0137 
0138 extern NodeId nLastNodeId;
0139 extern CCriticalSection cs_nLastNodeId;
0140 
0141 struct LocalServiceInfo {
0142     int nScore;
0143     int nPort;
0144 };
0145 
0146 extern CCriticalSection cs_mapLocalHost;
0147 extern std::map<CNetAddr, LocalServiceInfo> mapLocalHost;
0148 
0149 class CNodeStats
0150 {
0151 public:
0152     NodeId nodeid;
0153     uint64_t nServices;
0154     int64_t nLastSend;
0155     int64_t nLastRecv;
0156     int64_t nTimeConnected;
0157     std::string addrName;
0158     int nVersion;
0159     std::string cleanSubVer;
0160     bool fInbound;
0161     int nStartingHeight;
0162     uint64_t nSendBytes;
0163     uint64_t nRecvBytes;
0164     bool fWhitelisted;
0165     double dPingTime;
0166     double dPingWait;
0167     std::string addrLocal;
0168 };
0169 
0170 
0171 
0172 
0173 class CNetMessage {
0174 public:
0175     bool in_data;                   // parsing header (false) or data (true)
0176 
0177     CDataStream hdrbuf;             // partially received header
0178     CMessageHeader hdr;             // complete header
0179     unsigned int nHdrPos;
0180 
0181     CDataStream vRecv;              // received message data
0182     unsigned int nDataPos;
0183 
0184     int64_t nTime;                  // time (in microseconds) of message receipt.
0185 
0186     CNetMessage(int nTypeIn, int nVersionIn) : hdrbuf(nTypeIn, nVersionIn), vRecv(nTypeIn, nVersionIn) {
0187         hdrbuf.resize(24);
0188         in_data = false;
0189         nHdrPos = 0;
0190         nDataPos = 0;
0191         nTime = 0;
0192     }
0193 
0194     bool complete() const
0195     {
0196         if (!in_data)
0197             return false;
0198         return (hdr.nMessageSize == nDataPos);
0199     }
0200 
0201     void SetVersion(int nVersionIn)
0202     {
0203         hdrbuf.SetVersion(nVersionIn);
0204         vRecv.SetVersion(nVersionIn);
0205     }
0206 
0207     int readHeader(const char *pch, unsigned int nBytes);
0208     int readData(const char *pch, unsigned int nBytes);
0209 };
0210 
0211 
0212 
0213 
0214 
0215 /** Information about a peer */
0216 class CNode
0217 {
0218 public:
0219     // socket
0220     uint64_t nServices;
0221     SOCKET hSocket;
0222     CDataStream ssSend;
0223     size_t nSendSize; // total size of all vSendMsg entries
0224     size_t nSendOffset; // offset inside the first vSendMsg already sent
0225     uint64_t nSendBytes;
0226     std::deque<CSerializeData> vSendMsg;
0227     CCriticalSection cs_vSend;
0228 
0229     std::deque<CInv> vRecvGetData;
0230     std::deque<CNetMessage> vRecvMsg;
0231     CCriticalSection cs_vRecvMsg;
0232     uint64_t nRecvBytes;
0233     int nRecvVersion;
0234 
0235     int64_t nLastSend;
0236     int64_t nLastRecv;
0237     int64_t nTimeConnected;
0238     CAddress addr;
0239     std::string addrName;
0240     CService addrLocal;
0241     int nVersion;
0242     // strSubVer is whatever byte array we read from the wire. However, this field is intended
0243     // to be printed out, displayed to humans in various forms and so on. So we sanitize it and
0244     // store the sanitized version in cleanSubVer. The original should be used when dealing with
0245     // the network or wire types and the cleaned string used when displayed or logged.
0246     std::string strSubVer, cleanSubVer;
0247     bool fWhitelisted; // This peer can bypass DoS banning.
0248     bool fOneShot;
0249     bool fClient;
0250     bool fInbound;
0251     bool fNetworkNode;
0252     bool fSuccessfullyConnected;
0253     bool fDisconnect;
0254     // We use fRelayTxes for two purposes -
0255     // a) it allows us to not relay tx invs before receiving the peer's version message
0256     // b) the peer may tell us in their version message that we should not relay tx invs
0257     //    until they have initialized their bloom filter.
0258     bool fRelayTxes;
0259     CSemaphoreGrant grantOutbound;
0260     CCriticalSection cs_filter;
0261     CBloomFilter* pfilter;
0262     int nRefCount;
0263     NodeId id;
0264 protected:
0265 
0266     // Denial-of-service detection/prevention
0267     // Key is IP address, value is banned-until-time
0268     static std::map<CNetAddr, int64_t> setBanned;
0269     static CCriticalSection cs_setBanned;
0270 
0271     // Whitelisted ranges. Any node connecting from these is automatically
0272     // whitelisted (as well as those connecting to whitelisted binds).
0273     static std::vector<CSubNet> vWhitelistedRange;
0274     static CCriticalSection cs_vWhitelistedRange;
0275 
0276     // Basic fuzz-testing
0277     void Fuzz(int nChance); // modifies ssSend
0278 
0279 public:
0280     uint256 hashContinue;
0281     int nStartingHeight;
0282 
0283     // flood relay
0284     std::vector<CAddress> vAddrToSend;
0285     mruset<CAddress> setAddrKnown;
0286     bool fGetAddr;
0287     std::set<uint256> setKnown;
0288 
0289     // inventory based relay
0290     mruset<CInv> setInventoryKnown;
0291     std::vector<CInv> vInventoryToSend;
0292     CCriticalSection cs_inventory;
0293     std::multimap<int64_t, CInv> mapAskFor;
0294 
0295     // Ping time measurement:
0296     // The pong reply we're expecting, or 0 if no pong expected.
0297     uint64_t nPingNonceSent;
0298     // Time (in usec) the last ping was sent, or 0 if no ping was ever sent.
0299     int64_t nPingUsecStart;
0300     // Last measured round-trip time.
0301     int64_t nPingUsecTime;
0302     // Whether a ping is requested.
0303     bool fPingQueued;
0304 
0305     CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn = "", bool fInboundIn=false);
0306     ~CNode();
0307 
0308 private:
0309     // Network usage totals
0310     static CCriticalSection cs_totalBytesRecv;
0311     static CCriticalSection cs_totalBytesSent;
0312     static uint64_t nTotalBytesRecv;
0313     static uint64_t nTotalBytesSent;
0314 
0315     CNode(const CNode&);
0316     void operator=(const CNode&);
0317 
0318 public:
0319 
0320     NodeId GetId() const {
0321       return id;
0322     }
0323 
0324     int GetRefCount()
0325     {
0326         assert(nRefCount >= 0);
0327         return nRefCount;
0328     }
0329 
0330     // requires LOCK(cs_vRecvMsg)
0331     unsigned int GetTotalRecvSize()
0332     {
0333         unsigned int total = 0;
0334         BOOST_FOREACH(const CNetMessage &msg, vRecvMsg)
0335             total += msg.vRecv.size() + 24;
0336         return total;
0337     }
0338 
0339     // requires LOCK(cs_vRecvMsg)
0340     bool ReceiveMsgBytes(const char *pch, unsigned int nBytes);
0341 
0342     // requires LOCK(cs_vRecvMsg)
0343     void SetRecvVersion(int nVersionIn)
0344     {
0345         nRecvVersion = nVersionIn;
0346         BOOST_FOREACH(CNetMessage &msg, vRecvMsg)
0347             msg.SetVersion(nVersionIn);
0348     }
0349 
0350     CNode* AddRef()
0351     {
0352         nRefCount++;
0353         return this;
0354     }
0355 
0356     void Release()
0357     {
0358         nRefCount--;
0359     }
0360 
0361 
0362 
0363     void AddAddressKnown(const CAddress& addr)
0364     {
0365         setAddrKnown.insert(addr);
0366     }
0367 
0368     void PushAddress(const CAddress& addr)
0369     {
0370         // Known checking here is only to save space from duplicates.
0371         // SendMessages will filter it again for knowns that were added
0372         // after addresses were pushed.
0373         if (addr.IsValid() && !setAddrKnown.count(addr)) {
0374             if (vAddrToSend.size() >= MAX_ADDR_TO_SEND) {
0375                 vAddrToSend[insecure_rand() % vAddrToSend.size()] = addr;
0376             } else {
0377                 vAddrToSend.push_back(addr);
0378             }
0379         }
0380     }
0381 
0382 
0383     void AddInventoryKnown(const CInv& inv)
0384     {
0385         {
0386             LOCK(cs_inventory);
0387             setInventoryKnown.insert(inv);
0388         }
0389     }
0390 
0391     void PushInventory(const CInv& inv)
0392     {
0393         {
0394             LOCK(cs_inventory);
0395             if (!setInventoryKnown.count(inv))
0396                 vInventoryToSend.push_back(inv);
0397         }
0398     }
0399 
0400     void AskFor(const CInv& inv);
0401 
0402     // TODO: Document the postcondition of this function.  Is cs_vSend locked?
0403     void BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend);
0404 
0405     // TODO: Document the precondition of this function.  Is cs_vSend locked?
0406     void AbortMessage() UNLOCK_FUNCTION(cs_vSend);
0407 
0408     // TODO: Document the precondition of this function.  Is cs_vSend locked?
0409     void EndMessage() UNLOCK_FUNCTION(cs_vSend);
0410 
0411     void PushVersion();
0412 
0413 
0414     void PushMessage(const char* pszCommand)
0415     {
0416         try
0417         {
0418             BeginMessage(pszCommand);
0419             EndMessage();
0420         }
0421         catch (...)
0422         {
0423             AbortMessage();
0424             throw;
0425         }
0426     }
0427 
0428     template<typename T1>
0429     void PushMessage(const char* pszCommand, const T1& a1)
0430     {
0431         try
0432         {
0433             BeginMessage(pszCommand);
0434             ssSend << a1;
0435             EndMessage();
0436         }
0437         catch (...)
0438         {
0439             AbortMessage();
0440             throw;
0441         }
0442     }
0443 
0444     template<typename T1, typename T2>
0445     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
0446     {
0447         try
0448         {
0449             BeginMessage(pszCommand);
0450             ssSend << a1 << a2;
0451             EndMessage();
0452         }
0453         catch (...)
0454         {
0455             AbortMessage();
0456             throw;
0457         }
0458     }
0459 
0460     template<typename T1, typename T2, typename T3>
0461     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
0462     {
0463         try
0464         {
0465             BeginMessage(pszCommand);
0466             ssSend << a1 << a2 << a3;
0467             EndMessage();
0468         }
0469         catch (...)
0470         {
0471             AbortMessage();
0472             throw;
0473         }
0474     }
0475 
0476     template<typename T1, typename T2, typename T3, typename T4>
0477     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
0478     {
0479         try
0480         {
0481             BeginMessage(pszCommand);
0482             ssSend << a1 << a2 << a3 << a4;
0483             EndMessage();
0484         }
0485         catch (...)
0486         {
0487             AbortMessage();
0488             throw;
0489         }
0490     }
0491 
0492     template<typename T1, typename T2, typename T3, typename T4, typename T5>
0493     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
0494     {
0495         try
0496         {
0497             BeginMessage(pszCommand);
0498             ssSend << a1 << a2 << a3 << a4 << a5;
0499             EndMessage();
0500         }
0501         catch (...)
0502         {
0503             AbortMessage();
0504             throw;
0505         }
0506     }
0507 
0508     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
0509     void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
0510     {
0511         try
0512         {
0513             BeginMessage(pszCommand);
0514             ssSend << a1 << a2 << a3 << a4 << a5 << a6;
0515             EndMessage();
0516         }
0517         catch (...)
0518         {
0519             AbortMessage();
0520             throw;
0521         }
0522     }
0523 
0524     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
0525     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)
0526     {
0527         try
0528         {
0529             BeginMessage(pszCommand);
0530             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
0531             EndMessage();
0532         }
0533         catch (...)
0534         {
0535             AbortMessage();
0536             throw;
0537         }
0538     }
0539 
0540     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
0541     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)
0542     {
0543         try
0544         {
0545             BeginMessage(pszCommand);
0546             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
0547             EndMessage();
0548         }
0549         catch (...)
0550         {
0551             AbortMessage();
0552             throw;
0553         }
0554     }
0555 
0556     template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
0557     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)
0558     {
0559         try
0560         {
0561             BeginMessage(pszCommand);
0562             ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
0563             EndMessage();
0564         }
0565         catch (...)
0566         {
0567             AbortMessage();
0568             throw;
0569         }
0570     }
0571 
0572     bool IsSubscribed(unsigned int nChannel);
0573     void Subscribe(unsigned int nChannel, unsigned int nHops=0);
0574     void CancelSubscribe(unsigned int nChannel);
0575     void CloseSocketDisconnect();
0576 
0577     // Denial-of-service detection/prevention
0578     // The idea is to detect peers that are behaving
0579     // badly and disconnect/ban them, but do it in a
0580     // one-coding-mistake-won't-shatter-the-entire-network
0581     // way.
0582     // IMPORTANT:  There should be nothing I can give a
0583     // node that it will forward on that will make that
0584     // node's peers drop it. If there is, an attacker
0585     // can isolate a node and/or try to split the network.
0586     // Dropping a node for sending stuff that is invalid
0587     // now but might be valid in a later version is also
0588     // dangerous, because it can cause a network split
0589     // between nodes running old code and nodes running
0590     // new code.
0591     static void ClearBanned(); // needed for unit testing
0592     static bool IsBanned(CNetAddr ip);
0593     static bool Ban(const CNetAddr &ip);
0594     void copyStats(CNodeStats &stats);
0595 
0596     static bool IsWhitelistedRange(const CNetAddr &ip);
0597     static void AddWhitelistedRange(const CSubNet &subnet);
0598 
0599     // Network stats
0600     static void RecordBytesRecv(uint64_t bytes);
0601     static void RecordBytesSent(uint64_t bytes);
0602 
0603     static uint64_t GetTotalBytesRecv();
0604     static uint64_t GetTotalBytesSent();
0605 };
0606 
0607 
0608 
0609 class CTransaction;
0610 void RelayTransaction(const CTransaction& tx);
0611 void RelayTransaction(const CTransaction& tx, const CDataStream& ss);
0612 
0613 /** Access to the (IP) address database (peers.dat) */
0614 class CAddrDB
0615 {
0616 private:
0617     boost::filesystem::path pathAddr;
0618 public:
0619     CAddrDB();
0620     bool Write(const CAddrMan& addr);
0621     bool Read(CAddrMan& addr);
0622 };
0623 
0624 #endif // BITCOIN_NET_H