-
+ AE473B8D2838555DF527E16AC7CAE7DFFF39BFD68769B1FCABB1F847E29E1245AF78799942E790016C376A76E112B9EC16D2D7D5F52736E3CC72E45432706D3B
bitcoin/src/net.h
(0 . 0)(1 . 701)
16361 // Copyright (c) 2009-2010 Satoshi Nakamoto
16362 // Copyright (c) 2009-2012 The Bitcoin developers
16363 // Distributed under the MIT/X11 software license, see the accompanying
16364 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
16365 #ifndef BITCOIN_NET_H
16366 #define BITCOIN_NET_H
16367
16368 #include <deque>
16369 #include <boost/array.hpp>
16370 #include <boost/foreach.hpp>
16371 #include <openssl/rand.h>
16372
16373 #ifndef WIN32
16374 #include <arpa/inet.h>
16375 #endif
16376
16377 #include "protocol.h"
16378
16379 class CAddrDB;
16380 class CRequestTracker;
16381 class CNode;
16382 class CBlockIndex;
16383 extern int nBestHeight;
16384 extern int nConnectTimeout;
16385
16386
16387
16388 inline unsigned int ReceiveBufferSize() { return 1000*GetArg("-maxreceivebuffer", 10*1000); }
16389 inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 10*1000); }
16390 static const unsigned int PUBLISH_HOPS = 5;
16391
16392 bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet, int nTimeout=nConnectTimeout);
16393 bool Lookup(const char *pszName, std::vector<CAddress>& vaddr, int nServices, int nMaxSolutions, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
16394 bool Lookup(const char *pszName, CAddress& addr, int nServices, bool fAllowLookup = false, int portDefault = 0, bool fAllowPort = false);
16395 bool GetMyExternalIP(unsigned int& ipRet);
16396 bool AddAddress(CAddress addr, int64 nTimePenalty=0, CAddrDB *pAddrDB=NULL);
16397 void AddressCurrentlyConnected(const CAddress& addr);
16398 CNode* FindNode(unsigned int ip);
16399 CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);
16400 void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);
16401 bool AnySubscribed(unsigned int nChannel);
16402 void MapPort(bool fMapPort);
16403 bool BindListenPort(std::string& strError=REF(std::string()));
16404 void StartNode(void* parg);
16405 bool StopNode();
16406
16407 enum
16408 {
16409 MSG_TX = 1,
16410 MSG_BLOCK,
16411 };
16412
16413 class CRequestTracker
16414 {
16415 public:
16416 void (*fn)(void*, CDataStream&);
16417 void* param1;
16418
16419 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)
16420 {
16421 fn = fnIn;
16422 param1 = param1In;
16423 }
16424
16425 bool IsNull()
16426 {
16427 return fn == NULL;
16428 }
16429 };
16430
16431
16432
16433
16434
16435 extern bool fClient;
16436 extern bool fAllowDNS;
16437 extern uint64 nLocalServices;
16438 extern CAddress addrLocalHost;
16439 extern uint64 nLocalHostNonce;
16440 extern boost::array<int, 10> vnThreadsRunning;
16441
16442 extern std::vector<CNode*> vNodes;
16443 extern CCriticalSection cs_vNodes;
16444 extern std::map<std::vector<unsigned char>, CAddress> mapAddresses;
16445 extern CCriticalSection cs_mapAddresses;
16446 extern std::map<CInv, CDataStream> mapRelay;
16447 extern std::deque<std::pair<int64, CInv> > vRelayExpiration;
16448 extern CCriticalSection cs_mapRelay;
16449 extern std::map<CInv, int64> mapAlreadyAskedFor;
16450
16451 // Settings
16452 extern int fUseProxy;
16453 extern CAddress addrProxy;
16454
16455
16456
16457
16458
16459
16460 class CNode
16461 {
16462 public:
16463 // socket
16464 uint64 nServices;
16465 SOCKET hSocket;
16466 CDataStream vSend;
16467 CDataStream vRecv;
16468 CCriticalSection cs_vSend;
16469 CCriticalSection cs_vRecv;
16470 int64 nLastSend;
16471 int64 nLastRecv;
16472 int64 nLastSendEmpty;
16473 int64 nTimeConnected;
16474 unsigned int nHeaderStart;
16475 unsigned int nMessageStart;
16476 CAddress addr;
16477 int nVersion;
16478 std::string strSubVer;
16479 bool fClient;
16480 bool fInbound;
16481 bool fNetworkNode;
16482 bool fSuccessfullyConnected;
16483 bool fDisconnect;
16484 protected:
16485 int nRefCount;
16486
16487 // Denial-of-service detection/prevention
16488 // Key is ip address, value is banned-until-time
16489 static std::map<unsigned int, int64> setBanned;
16490 static CCriticalSection cs_setBanned;
16491 int nMisbehavior;
16492
16493 public:
16494 int64 nReleaseTime;
16495 std::map<uint256, CRequestTracker> mapRequests;
16496 CCriticalSection cs_mapRequests;
16497 uint256 hashContinue;
16498 CBlockIndex* pindexLastGetBlocksBegin;
16499 uint256 hashLastGetBlocksEnd;
16500 int nStartingHeight;
16501
16502 // flood relay
16503 std::vector<CAddress> vAddrToSend;
16504 std::set<CAddress> setAddrKnown;
16505 bool fGetAddr;
16506 std::set<uint256> setKnown;
16507
16508 // inventory based relay
16509 std::set<CInv> setInventoryKnown;
16510 std::vector<CInv> vInventoryToSend;
16511 CCriticalSection cs_inventory;
16512 std::multimap<int64, CInv> mapAskFor;
16513
16514 // publish and subscription
16515 std::vector<char> vfSubscribe;
16516
16517 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)
16518 {
16519 nServices = 0;
16520 hSocket = hSocketIn;
16521 vSend.SetType(SER_NETWORK);
16522 vSend.SetVersion(0);
16523 vRecv.SetType(SER_NETWORK);
16524 vRecv.SetVersion(0);
16525 // Version 0.2 obsoletes 20 Feb 2012
16526 if (GetTime() > 1329696000)
16527 {
16528 vSend.SetVersion(209);
16529 vRecv.SetVersion(209);
16530 }
16531 nLastSend = 0;
16532 nLastRecv = 0;
16533 nLastSendEmpty = GetTime();
16534 nTimeConnected = GetTime();
16535 nHeaderStart = -1;
16536 nMessageStart = -1;
16537 addr = addrIn;
16538 nVersion = 0;
16539 strSubVer = "";
16540 fClient = false; // set by version message
16541 fInbound = fInboundIn;
16542 fNetworkNode = false;
16543 fSuccessfullyConnected = false;
16544 fDisconnect = false;
16545 nRefCount = 0;
16546 nReleaseTime = 0;
16547 hashContinue = 0;
16548 pindexLastGetBlocksBegin = 0;
16549 hashLastGetBlocksEnd = 0;
16550 nStartingHeight = -1;
16551 fGetAddr = false;
16552 vfSubscribe.assign(256, false);
16553 nMisbehavior = 0;
16554
16555 // Be shy and don't send version until we hear
16556 if (!fInbound)
16557 PushVersion();
16558 }
16559
16560 ~CNode()
16561 {
16562 if (hSocket != INVALID_SOCKET)
16563 {
16564 closesocket(hSocket);
16565 hSocket = INVALID_SOCKET;
16566 }
16567 }
16568
16569 private:
16570 CNode(const CNode&);
16571 void operator=(const CNode&);
16572 public:
16573
16574
16575 int GetRefCount()
16576 {
16577 return std::max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);
16578 }
16579
16580 CNode* AddRef(int64 nTimeout=0)
16581 {
16582 if (nTimeout != 0)
16583 nReleaseTime = std::max(nReleaseTime, GetTime() + nTimeout);
16584 else
16585 nRefCount++;
16586 return this;
16587 }
16588
16589 void Release()
16590 {
16591 nRefCount--;
16592 }
16593
16594
16595
16596 void AddAddressKnown(const CAddress& addr)
16597 {
16598 setAddrKnown.insert(addr);
16599 }
16600
16601 void PushAddress(const CAddress& addr)
16602 {
16603 // Known checking here is only to save space from duplicates.
16604 // SendMessages will filter it again for knowns that were added
16605 // after addresses were pushed.
16606 if (addr.IsValid() && !setAddrKnown.count(addr))
16607 vAddrToSend.push_back(addr);
16608 }
16609
16610
16611 void AddInventoryKnown(const CInv& inv)
16612 {
16613 CRITICAL_BLOCK(cs_inventory)
16614 setInventoryKnown.insert(inv);
16615 }
16616
16617 void PushInventory(const CInv& inv)
16618 {
16619 CRITICAL_BLOCK(cs_inventory)
16620 if (!setInventoryKnown.count(inv))
16621 vInventoryToSend.push_back(inv);
16622 }
16623
16624 void AskFor(const CInv& inv)
16625 {
16626 // We're using mapAskFor as a priority queue,
16627 // the key is the earliest time the request can be sent
16628 int64& nRequestTime = mapAlreadyAskedFor[inv];
16629 printf("askfor %s %"PRI64d"\n", inv.ToString().c_str(), nRequestTime);
16630
16631 // Make sure not to reuse time indexes to keep things in the same order
16632 int64 nNow = (GetTime() - 1) * 1000000;
16633 static int64 nLastTime;
16634 ++nLastTime;
16635 nNow = std::max(nNow, nLastTime);
16636 nLastTime = nNow;
16637
16638 // Each retry is 2 minutes after the last
16639 nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
16640 mapAskFor.insert(std::make_pair(nRequestTime, inv));
16641 }
16642
16643
16644
16645 void BeginMessage(const char* pszCommand)
16646 {
16647 ENTER_CRITICAL_SECTION(cs_vSend);
16648 if (nHeaderStart != -1)
16649 AbortMessage();
16650 nHeaderStart = vSend.size();
16651 vSend << CMessageHeader(pszCommand, 0);
16652 nMessageStart = vSend.size();
16653 if (fDebug) {
16654 printf("%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
16655 printf("sending: %s ", pszCommand);
16656 }
16657 }
16658
16659 void AbortMessage()
16660 {
16661 if (nHeaderStart == -1)
16662 return;
16663 vSend.resize(nHeaderStart);
16664 nHeaderStart = -1;
16665 nMessageStart = -1;
16666 LEAVE_CRITICAL_SECTION(cs_vSend);
16667
16668 if (fDebug)
16669 printf("(aborted)\n");
16670 }
16671
16672 void EndMessage()
16673 {
16674 if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
16675 {
16676 printf("dropmessages DROPPING SEND MESSAGE\n");
16677 AbortMessage();
16678 return;
16679 }
16680
16681 if (nHeaderStart == -1)
16682 return;
16683
16684 // Set the size
16685 unsigned int nSize = vSend.size() - nMessageStart;
16686 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));
16687
16688 // Set the checksum
16689 if (vSend.GetVersion() >= 209)
16690 {
16691 uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end());
16692 unsigned int nChecksum = 0;
16693 memcpy(&nChecksum, &hash, sizeof(nChecksum));
16694 assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum));
16695 memcpy((char*)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum));
16696 }
16697
16698 if (fDebug) {
16699 printf("(%d bytes)\n", nSize);
16700 }
16701
16702 nHeaderStart = -1;
16703 nMessageStart = -1;
16704 LEAVE_CRITICAL_SECTION(cs_vSend);
16705 }
16706
16707 void EndMessageAbortIfEmpty()
16708 {
16709 if (nHeaderStart == -1)
16710 return;
16711 int nSize = vSend.size() - nMessageStart;
16712 if (nSize > 0)
16713 EndMessage();
16714 else
16715 AbortMessage();
16716 }
16717
16718
16719
16720 void PushVersion()
16721 {
16722 /// when NTP implemented, change to just nTime = GetAdjustedTime()
16723 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());
16724 CAddress addrYou = (fUseProxy ? CAddress("0.0.0.0") : addr);
16725 CAddress addrMe = (fUseProxy || !addrLocalHost.IsRoutable() ? CAddress("0.0.0.0") : addrLocalHost);
16726 RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
16727 PushMessage("version", VERSION, nLocalServices, nTime, addrYou, addrMe,
16728 nLocalHostNonce, std::string(pszSubVer), nBestHeight);
16729 }
16730
16731
16732
16733
16734 void PushMessage(const char* pszCommand)
16735 {
16736 try
16737 {
16738 BeginMessage(pszCommand);
16739 EndMessage();
16740 }
16741 catch (...)
16742 {
16743 AbortMessage();
16744 throw;
16745 }
16746 }
16747
16748 template<typename T1>
16749 void PushMessage(const char* pszCommand, const T1& a1)
16750 {
16751 try
16752 {
16753 BeginMessage(pszCommand);
16754 vSend << a1;
16755 EndMessage();
16756 }
16757 catch (...)
16758 {
16759 AbortMessage();
16760 throw;
16761 }
16762 }
16763
16764 template<typename T1, typename T2>
16765 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)
16766 {
16767 try
16768 {
16769 BeginMessage(pszCommand);
16770 vSend << a1 << a2;
16771 EndMessage();
16772 }
16773 catch (...)
16774 {
16775 AbortMessage();
16776 throw;
16777 }
16778 }
16779
16780 template<typename T1, typename T2, typename T3>
16781 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)
16782 {
16783 try
16784 {
16785 BeginMessage(pszCommand);
16786 vSend << a1 << a2 << a3;
16787 EndMessage();
16788 }
16789 catch (...)
16790 {
16791 AbortMessage();
16792 throw;
16793 }
16794 }
16795
16796 template<typename T1, typename T2, typename T3, typename T4>
16797 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)
16798 {
16799 try
16800 {
16801 BeginMessage(pszCommand);
16802 vSend << a1 << a2 << a3 << a4;
16803 EndMessage();
16804 }
16805 catch (...)
16806 {
16807 AbortMessage();
16808 throw;
16809 }
16810 }
16811
16812 template<typename T1, typename T2, typename T3, typename T4, typename T5>
16813 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5)
16814 {
16815 try
16816 {
16817 BeginMessage(pszCommand);
16818 vSend << a1 << a2 << a3 << a4 << a5;
16819 EndMessage();
16820 }
16821 catch (...)
16822 {
16823 AbortMessage();
16824 throw;
16825 }
16826 }
16827
16828 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6>
16829 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6)
16830 {
16831 try
16832 {
16833 BeginMessage(pszCommand);
16834 vSend << a1 << a2 << a3 << a4 << a5 << a6;
16835 EndMessage();
16836 }
16837 catch (...)
16838 {
16839 AbortMessage();
16840 throw;
16841 }
16842 }
16843
16844 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7>
16845 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)
16846 {
16847 try
16848 {
16849 BeginMessage(pszCommand);
16850 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7;
16851 EndMessage();
16852 }
16853 catch (...)
16854 {
16855 AbortMessage();
16856 throw;
16857 }
16858 }
16859
16860 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8>
16861 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)
16862 {
16863 try
16864 {
16865 BeginMessage(pszCommand);
16866 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8;
16867 EndMessage();
16868 }
16869 catch (...)
16870 {
16871 AbortMessage();
16872 throw;
16873 }
16874 }
16875
16876 template<typename T1, typename T2, typename T3, typename T4, typename T5, typename T6, typename T7, typename T8, typename T9>
16877 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)
16878 {
16879 try
16880 {
16881 BeginMessage(pszCommand);
16882 vSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9;
16883 EndMessage();
16884 }
16885 catch (...)
16886 {
16887 AbortMessage();
16888 throw;
16889 }
16890 }
16891
16892
16893 void PushRequest(const char* pszCommand,
16894 void (*fn)(void*, CDataStream&), void* param1)
16895 {
16896 uint256 hashReply;
16897 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
16898
16899 CRITICAL_BLOCK(cs_mapRequests)
16900 mapRequests[hashReply] = CRequestTracker(fn, param1);
16901
16902 PushMessage(pszCommand, hashReply);
16903 }
16904
16905 template<typename T1>
16906 void PushRequest(const char* pszCommand, const T1& a1,
16907 void (*fn)(void*, CDataStream&), void* param1)
16908 {
16909 uint256 hashReply;
16910 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
16911
16912 CRITICAL_BLOCK(cs_mapRequests)
16913 mapRequests[hashReply] = CRequestTracker(fn, param1);
16914
16915 PushMessage(pszCommand, hashReply, a1);
16916 }
16917
16918 template<typename T1, typename T2>
16919 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,
16920 void (*fn)(void*, CDataStream&), void* param1)
16921 {
16922 uint256 hashReply;
16923 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));
16924
16925 CRITICAL_BLOCK(cs_mapRequests)
16926 mapRequests[hashReply] = CRequestTracker(fn, param1);
16927
16928 PushMessage(pszCommand, hashReply, a1, a2);
16929 }
16930
16931
16932
16933 void PushGetBlocks(CBlockIndex* pindexBegin, uint256 hashEnd);
16934 bool IsSubscribed(unsigned int nChannel);
16935 void Subscribe(unsigned int nChannel, unsigned int nHops=0);
16936 void CancelSubscribe(unsigned int nChannel);
16937 void CloseSocketDisconnect();
16938 void Cleanup();
16939
16940
16941 // Denial-of-service detection/prevention
16942 // The idea is to detect peers that are behaving
16943 // badly and disconnect/ban them, but do it in a
16944 // one-coding-mistake-won't-shatter-the-entire-network
16945 // way.
16946 // IMPORTANT: There should be nothing I can give a
16947 // node that it will forward on that will make that
16948 // node's peers drop it. If there is, an attacker
16949 // can isolate a node and/or try to split the network.
16950 // Dropping a node for sending stuff that is invalid
16951 // now but might be valid in a later version is also
16952 // dangerous, because it can cause a network split
16953 // between nodes running old code and nodes running
16954 // new code.
16955 static void ClearBanned(); // needed for unit testing
16956 static bool IsBanned(unsigned int ip);
16957 bool Misbehaving(int howmuch); // 1 == a little, 100 == a lot
16958 };
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969 inline void RelayInventory(const CInv& inv)
16970 {
16971 // Put on lists to offer to the other nodes
16972 CRITICAL_BLOCK(cs_vNodes)
16973 BOOST_FOREACH(CNode* pnode, vNodes)
16974 pnode->PushInventory(inv);
16975 }
16976
16977 template<typename T>
16978 void RelayMessage(const CInv& inv, const T& a)
16979 {
16980 CDataStream ss(SER_NETWORK);
16981 ss.reserve(10000);
16982 ss << a;
16983 RelayMessage(inv, ss);
16984 }
16985
16986 template<>
16987 inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)
16988 {
16989 CRITICAL_BLOCK(cs_mapRelay)
16990 {
16991 // Expire old relay messages
16992 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())
16993 {
16994 mapRelay.erase(vRelayExpiration.front().second);
16995 vRelayExpiration.pop_front();
16996 }
16997
16998 // Save original serialized message so newer versions are preserved
16999 mapRelay[inv] = ss;
17000 vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
17001 }
17002
17003 RelayInventory(inv);
17004 }
17005
17006
17007
17008
17009
17010
17011
17012
17013 //
17014 // Templates for the publish and subscription system.
17015 // The object being published as T& obj needs to have:
17016 // a set<unsigned int> setSources member
17017 // specializations of AdvertInsert and AdvertErase
17018 // Currently implemented for CTable and CProduct.
17019 //
17020
17021 template<typename T>
17022 void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
17023 {
17024 // Add to sources
17025 obj.setSources.insert(pfrom->addr.ip);
17026
17027 if (!AdvertInsert(obj))
17028 return;
17029
17030 // Relay
17031 CRITICAL_BLOCK(cs_vNodes)
17032 BOOST_FOREACH(CNode* pnode, vNodes)
17033 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
17034 pnode->PushMessage("publish", nChannel, nHops, obj);
17035 }
17036
17037 template<typename T>
17038 void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
17039 {
17040 uint256 hash = obj.GetHash();
17041
17042 CRITICAL_BLOCK(cs_vNodes)
17043 BOOST_FOREACH(CNode* pnode, vNodes)
17044 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))
17045 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);
17046
17047 AdvertErase(obj);
17048 }
17049
17050 template<typename T>
17051 void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)
17052 {
17053 // Remove a source
17054 obj.setSources.erase(pfrom->addr.ip);
17055
17056 // If no longer supported by any sources, cancel it
17057 if (obj.setSources.empty())
17058 AdvertStopPublish(pfrom, nChannel, nHops, obj);
17059 }
17060
17061 #endif