Bitcoin v0.1.0 · 2009-01-08
net.h
1// Copyright (c) 2009 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45class CMessageHeader;6class CAddress;7class CInv;8class CRequestTracker;9class CNode;10111213static const unsigned short DEFAULT_PORT = htons(8333);14static const unsigned int PUBLISH_HOPS = 5;15enum16{17 NODE_NETWORK = (1 << 0),18};19202122232425bool ConnectSocket(const CAddress& addrConnect, SOCKET& hSocketRet);26bool GetMyExternalIP(unsigned int& ipRet);27bool AddAddress(CAddrDB& addrdb, const CAddress& addr);28CNode* FindNode(unsigned int ip);29CNode* ConnectNode(CAddress addrConnect, int64 nTimeout=0);30void AbandonRequests(void (*fn)(void*, CDataStream&), void* param1);31bool AnySubscribed(unsigned int nChannel);32void ThreadBitcoinMiner(void* parg);33bool StartNode(string& strError=REF(string()));34bool StopNode();35void CheckForShutdown(int n);36373839404142434445//46// Message header47// (4) message start48// (12) command49// (4) size5051// The message start string is designed to be unlikely to occur in normal data.52// The characters are rarely used upper ascii, not valid as UTF-8, and produce53// a large 4-byte int at any alignment.54static const char pchMessageStart[4] = { 0xf9, 0xbe, 0xb4, 0xd9 };5556class CMessageHeader57{58public:59 enum { COMMAND_SIZE=12 };60 char pchMessageStart[sizeof(::pchMessageStart)];61 char pchCommand[COMMAND_SIZE];62 unsigned int nMessageSize;6364 CMessageHeader()65 {66 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));67 memset(pchCommand, 0, sizeof(pchCommand));68 pchCommand[1] = 1;69 nMessageSize = -1;70 }7172 CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)73 {74 memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart));75 strncpy(pchCommand, pszCommand, COMMAND_SIZE);76 nMessageSize = nMessageSizeIn;77 }7879 IMPLEMENT_SERIALIZE80 (81 READWRITE(FLATDATA(pchMessageStart));82 READWRITE(FLATDATA(pchCommand));83 READWRITE(nMessageSize);84 )8586 string GetCommand()87 {88 if (pchCommand[COMMAND_SIZE-1] == 0)89 return string(pchCommand, pchCommand + strlen(pchCommand));90 else91 return string(pchCommand, pchCommand + COMMAND_SIZE);92 }9394 bool IsValid()95 {96 // Check start string97 if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0)98 return false;99100 // Check the command string for errors101 for (char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)102 {103 if (*p1 == 0)104 {105 // Must be all zeros after the first zero106 for (; p1 < pchCommand + COMMAND_SIZE; p1++)107 if (*p1 != 0)108 return false;109 }110 else if (*p1 < ' ' || *p1 > 0x7E)111 return false;112 }113114 // Message size115 if (nMessageSize > 0x10000000)116 {117 printf("CMessageHeader::IsValid() : nMessageSize too large %u\n", nMessageSize);118 return false;119 }120121 return true;122 }123};124125126127128129130static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };131132class CAddress133{134public:135 uint64 nServices;136 unsigned char pchReserved[12];137 unsigned int ip;138 unsigned short port;139140 // disk only141 unsigned int nTime;142143 // memory only144 unsigned int nLastFailed;145146 CAddress()147 {148 nServices = 0;149 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));150 ip = 0;151 port = DEFAULT_PORT;152 nTime = GetAdjustedTime();153 nLastFailed = 0;154 }155156 CAddress(unsigned int ipIn, unsigned short portIn, uint64 nServicesIn=0)157 {158 nServices = nServicesIn;159 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));160 ip = ipIn;161 port = portIn;162 nTime = GetAdjustedTime();163 nLastFailed = 0;164 }165166 explicit CAddress(const struct sockaddr_in& sockaddr, uint64 nServicesIn=0)167 {168 nServices = nServicesIn;169 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));170 ip = sockaddr.sin_addr.s_addr;171 port = sockaddr.sin_port;172 nTime = GetAdjustedTime();173 nLastFailed = 0;174 }175176 explicit CAddress(const char* pszIn, uint64 nServicesIn=0)177 {178 nServices = nServicesIn;179 memcpy(pchReserved, pchIPv4, sizeof(pchReserved));180 ip = 0;181 port = DEFAULT_PORT;182 nTime = GetAdjustedTime();183 nLastFailed = 0;184185 char psz[100];186 if (strlen(pszIn) > ARRAYLEN(psz)-1)187 return;188 strcpy(psz, pszIn);189 unsigned int a, b, c, d, e;190 if (sscanf(psz, "%u.%u.%u.%u:%u", &a, &b, &c, &d, &e) < 4)191 return;192 char* pszPort = strchr(psz, ':');193 if (pszPort)194 {195 *pszPort++ = '\0';196 port = htons(atoi(pszPort));197 }198 ip = inet_addr(psz);199 }200201 IMPLEMENT_SERIALIZE202 (203 if (nType & SER_DISK)204 {205 READWRITE(nVersion);206 READWRITE(nTime);207 }208 READWRITE(nServices);209 READWRITE(FLATDATA(pchReserved));210 READWRITE(ip);211 READWRITE(port);212 )213214 friend inline bool operator==(const CAddress& a, const CAddress& b)215 {216 return (memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved)) == 0 &&217 a.ip == b.ip &&218 a.port == b.port);219 }220221 friend inline bool operator<(const CAddress& a, const CAddress& b)222 {223 int ret = memcmp(a.pchReserved, b.pchReserved, sizeof(a.pchReserved));224 if (ret < 0)225 return true;226 else if (ret == 0)227 {228 if (ntohl(a.ip) < ntohl(b.ip))229 return true;230 else if (a.ip == b.ip)231 return ntohs(a.port) < ntohs(b.port);232 }233 return false;234 }235236 vector<unsigned char> GetKey() const237 {238 CDataStream ss;239 ss.reserve(18);240 ss << FLATDATA(pchReserved) << ip << port;241242 #if defined(_MSC_VER) && _MSC_VER < 1300243 return vector<unsigned char>((unsigned char*)&ss.begin()[0], (unsigned char*)&ss.end()[0]);244 #else245 return vector<unsigned char>(ss.begin(), ss.end());246 #endif247 }248249 struct sockaddr_in GetSockAddr() const250 {251 struct sockaddr_in sockaddr;252 sockaddr.sin_family = AF_INET;253 sockaddr.sin_addr.s_addr = ip;254 sockaddr.sin_port = port;255 return sockaddr;256 }257258 bool IsIPv4() const259 {260 return (memcmp(pchReserved, pchIPv4, sizeof(pchIPv4)) == 0);261 }262263 bool IsRoutable() const264 {265 return !(GetByte(3) == 10 || (GetByte(3) == 192 && GetByte(2) == 168));266 }267268 unsigned char GetByte(int n) const269 {270 return ((unsigned char*)&ip)[3-n];271 }272273 string ToStringIPPort() const274 {275 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));276 }277278 string ToStringIP() const279 {280 return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));281 }282283 string ToString() const284 {285 return strprintf("%u.%u.%u.%u:%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0), ntohs(port));286 //return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));287 }288289 void print() const290 {291 printf("CAddress(%s)\n", ToString().c_str());292 }293};294295296297298299300301enum302{303 MSG_TX = 1,304 MSG_BLOCK,305 MSG_REVIEW,306 MSG_PRODUCT,307 MSG_TABLE,308};309310static const char* ppszTypeName[] =311{312 "ERROR",313 "tx",314 "block",315 "review",316 "product",317 "table",318};319320class CInv321{322public:323 int type;324 uint256 hash;325326 CInv()327 {328 type = 0;329 hash = 0;330 }331332 CInv(int typeIn, const uint256& hashIn)333 {334 type = typeIn;335 hash = hashIn;336 }337338 CInv(const string& strType, const uint256& hashIn)339 {340 int i;341 for (i = 1; i < ARRAYLEN(ppszTypeName); i++)342 {343 if (strType == ppszTypeName[i])344 {345 type = i;346 break;347 }348 }349 if (i == ARRAYLEN(ppszTypeName))350 throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType.c_str()));351 hash = hashIn;352 }353354 IMPLEMENT_SERIALIZE355 (356 READWRITE(type);357 READWRITE(hash);358 )359360 friend inline bool operator<(const CInv& a, const CInv& b)361 {362 return (a.type < b.type || (a.type == b.type && a.hash < b.hash));363 }364365 bool IsKnownType() const366 {367 return (type >= 1 && type < ARRAYLEN(ppszTypeName));368 }369370 const char* GetCommand() const371 {372 if (!IsKnownType())373 throw std::out_of_range(strprintf("CInv::GetCommand() : type=% unknown type", type));374 return ppszTypeName[type];375 }376377 string ToString() const378 {379 return strprintf("%s %s", GetCommand(), hash.ToString().substr(0,14).c_str());380 }381382 void print() const383 {384 printf("CInv(%s)\n", ToString().c_str());385 }386};387388389390391392class CRequestTracker393{394public:395 void (*fn)(void*, CDataStream&);396 void* param1;397398 explicit CRequestTracker(void (*fnIn)(void*, CDataStream&)=NULL, void* param1In=NULL)399 {400 fn = fnIn;401 param1 = param1In;402 }403404 bool IsNull()405 {406 return fn == NULL;407 }408};409410411412413414extern bool fClient;415extern uint64 nLocalServices;416extern CAddress addrLocalHost;417extern CNode* pnodeLocalHost;418extern bool fShutdown;419extern array<bool, 10> vfThreadRunning;420extern vector<CNode*> vNodes;421extern CCriticalSection cs_vNodes;422extern map<vector<unsigned char>, CAddress> mapAddresses;423extern CCriticalSection cs_mapAddresses;424extern map<CInv, CDataStream> mapRelay;425extern deque<pair<int64, CInv> > vRelayExpiration;426extern CCriticalSection cs_mapRelay;427extern map<CInv, int64> mapAlreadyAskedFor;428extern CAddress addrProxy;429430431432433434class CNode435{436public:437 // socket438 uint64 nServices;439 SOCKET hSocket;440 CDataStream vSend;441 CDataStream vRecv;442 CCriticalSection cs_vSend;443 CCriticalSection cs_vRecv;444 unsigned int nPushPos;445 CAddress addr;446 int nVersion;447 bool fClient;448 bool fInbound;449 bool fNetworkNode;450 bool fDisconnect;451protected:452 int nRefCount;453public:454 int64 nReleaseTime;455 map<uint256, CRequestTracker> mapRequests;456 CCriticalSection cs_mapRequests;457458 // flood459 vector<CAddress> vAddrToSend;460 set<CAddress> setAddrKnown;461462 // inventory based relay463 set<CInv> setInventoryKnown;464 set<CInv> setInventoryKnown2;465 vector<CInv> vInventoryToSend;466 CCriticalSection cs_inventory;467 multimap<int64, CInv> mapAskFor;468469 // publish and subscription470 vector<char> vfSubscribe;471472473 CNode(SOCKET hSocketIn, CAddress addrIn, bool fInboundIn=false)474 {475 nServices = 0;476 hSocket = hSocketIn;477 vSend.SetType(SER_NETWORK);478 vRecv.SetType(SER_NETWORK);479 nPushPos = -1;480 addr = addrIn;481 nVersion = 0;482 fClient = false; // set by version message483 fInbound = fInboundIn;484 fNetworkNode = false;485 fDisconnect = false;486 nRefCount = 0;487 nReleaseTime = 0;488 vfSubscribe.assign(256, false);489490 // Push a version message491 /// when NTP implemented, change to just nTime = GetAdjustedTime()492 int64 nTime = (fInbound ? GetAdjustedTime() : GetTime());493 PushMessage("version", VERSION, nLocalServices, nTime, addr);494 }495496 ~CNode()497 {498 if (hSocket != INVALID_SOCKET)499 closesocket(hSocket);500 }501502private:503 CNode(const CNode&);504 void operator=(const CNode&);505public:506507508 bool ReadyToDisconnect()509 {510 return fDisconnect || GetRefCount() <= 0;511 }512513 int GetRefCount()514 {515 return max(nRefCount, 0) + (GetTime() < nReleaseTime ? 1 : 0);516 }517518 void AddRef(int64 nTimeout=0)519 {520 if (nTimeout != 0)521 nReleaseTime = max(nReleaseTime, GetTime() + nTimeout);522 else523 nRefCount++;524 }525526 void Release()527 {528 nRefCount--;529 }530531532533 void AddInventoryKnown(const CInv& inv)534 {535 CRITICAL_BLOCK(cs_inventory)536 setInventoryKnown.insert(inv);537 }538539 void PushInventory(const CInv& inv)540 {541 CRITICAL_BLOCK(cs_inventory)542 if (!setInventoryKnown.count(inv))543 vInventoryToSend.push_back(inv);544 }545546 void AskFor(const CInv& inv)547 {548 // We're using mapAskFor as a priority queue,549 // the key is the earliest time the request can be sent550 int64& nRequestTime = mapAlreadyAskedFor[inv];551 printf("askfor %s %I64d\n", inv.ToString().c_str(), nRequestTime);552553 // Make sure not to reuse time indexes to keep things in the same order554 int64 nNow = (GetTime() - 1) * 1000000;555 static int64 nLastTime;556 nLastTime = nNow = max(nNow, ++nLastTime);557558 // Each retry is 2 minutes after the last559 nRequestTime = max(nRequestTime + 2 * 60 * 1000000, nNow);560 mapAskFor.insert(make_pair(nRequestTime, inv));561 }562563564565 void BeginMessage(const char* pszCommand)566 {567 EnterCriticalSection(&cs_vSend);568 if (nPushPos != -1)569 AbortMessage();570 nPushPos = vSend.size();571 vSend << CMessageHeader(pszCommand, 0);572 printf("sending: %-12s ", pszCommand);573 }574575 void AbortMessage()576 {577 if (nPushPos == -1)578 return;579 vSend.resize(nPushPos);580 nPushPos = -1;581 LeaveCriticalSection(&cs_vSend);582 printf("(aborted)\n");583 }584585 void EndMessage()586 {587 extern int nDropMessagesTest;588 if (nDropMessagesTest > 0 && GetRand(nDropMessagesTest) == 0)589 {590 printf("dropmessages DROPPING SEND MESSAGE\n");591 AbortMessage();592 return;593 }594595 if (nPushPos == -1)596 return;597598 // Patch in the size599 unsigned int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);600 memcpy((char*)&vSend[nPushPos] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize));601602 printf("(%d bytes) ", nSize);603 //for (int i = nPushPos+sizeof(CMessageHeader); i < min(vSend.size(), nPushPos+sizeof(CMessageHeader)+20U); i++)604 // printf("%02x ", vSend[i] & 0xff);605 printf("\n");606607 nPushPos = -1;608 LeaveCriticalSection(&cs_vSend);609 }610611 void EndMessageAbortIfEmpty()612 {613 if (nPushPos == -1)614 return;615 int nSize = vSend.size() - nPushPos - sizeof(CMessageHeader);616 if (nSize > 0)617 EndMessage();618 else619 AbortMessage();620 }621622 const char* GetMessageCommand() const623 {624 if (nPushPos == -1)625 return "";626 return &vSend[nPushPos] + offsetof(CMessageHeader, pchCommand);627 }628629630631632 void PushMessage(const char* pszCommand)633 {634 try635 {636 BeginMessage(pszCommand);637 EndMessage();638 }639 catch (...)640 {641 AbortMessage();642 throw;643 }644 }645646 template<typename T1>647 void PushMessage(const char* pszCommand, const T1& a1)648 {649 try650 {651 BeginMessage(pszCommand);652 vSend << a1;653 EndMessage();654 }655 catch (...)656 {657 AbortMessage();658 throw;659 }660 }661662 template<typename T1, typename T2>663 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2)664 {665 try666 {667 BeginMessage(pszCommand);668 vSend << a1 << a2;669 EndMessage();670 }671 catch (...)672 {673 AbortMessage();674 throw;675 }676 }677678 template<typename T1, typename T2, typename T3>679 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3)680 {681 try682 {683 BeginMessage(pszCommand);684 vSend << a1 << a2 << a3;685 EndMessage();686 }687 catch (...)688 {689 AbortMessage();690 throw;691 }692 }693694 template<typename T1, typename T2, typename T3, typename T4>695 void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4)696 {697 try698 {699 BeginMessage(pszCommand);700 vSend << a1 << a2 << a3 << a4;701 EndMessage();702 }703 catch (...)704 {705 AbortMessage();706 throw;707 }708 }709710711 void PushRequest(const char* pszCommand,712 void (*fn)(void*, CDataStream&), void* param1)713 {714 uint256 hashReply;715 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));716717 CRITICAL_BLOCK(cs_mapRequests)718 mapRequests[hashReply] = CRequestTracker(fn, param1);719720 PushMessage(pszCommand, hashReply);721 }722723 template<typename T1>724 void PushRequest(const char* pszCommand, const T1& a1,725 void (*fn)(void*, CDataStream&), void* param1)726 {727 uint256 hashReply;728 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));729730 CRITICAL_BLOCK(cs_mapRequests)731 mapRequests[hashReply] = CRequestTracker(fn, param1);732733 PushMessage(pszCommand, hashReply, a1);734 }735736 template<typename T1, typename T2>737 void PushRequest(const char* pszCommand, const T1& a1, const T2& a2,738 void (*fn)(void*, CDataStream&), void* param1)739 {740 uint256 hashReply;741 RAND_bytes((unsigned char*)&hashReply, sizeof(hashReply));742743 CRITICAL_BLOCK(cs_mapRequests)744 mapRequests[hashReply] = CRequestTracker(fn, param1);745746 PushMessage(pszCommand, hashReply, a1, a2);747 }748749750751 bool IsSubscribed(unsigned int nChannel);752 void Subscribe(unsigned int nChannel, unsigned int nHops=0);753 void CancelSubscribe(unsigned int nChannel);754 void Disconnect();755};756757758759760761762763764765766inline void RelayInventory(const CInv& inv)767{768 // Put on lists to offer to the other nodes769 CRITICAL_BLOCK(cs_vNodes)770 foreach(CNode* pnode, vNodes)771 pnode->PushInventory(inv);772}773774template<typename T>775void RelayMessage(const CInv& inv, const T& a)776{777 CDataStream ss(SER_NETWORK);778 ss.reserve(10000);779 ss << a;780 RelayMessage(inv, ss);781}782783template<>784inline void RelayMessage<>(const CInv& inv, const CDataStream& ss)785{786 CRITICAL_BLOCK(cs_mapRelay)787 {788 // Expire old relay messages789 while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime())790 {791 mapRelay.erase(vRelayExpiration.front().second);792 vRelayExpiration.pop_front();793 }794795 // Save original serialized message so newer versions are preserved796 mapRelay[inv] = ss;797 vRelayExpiration.push_back(make_pair(GetTime() + 15 * 60, inv));798 }799800 RelayInventory(inv);801}802803804805806807808809810//811// Templates for the publish and subscription system.812// The object being published as T& obj needs to have:813// a set<unsigned int> setSources member814// specializations of AdvertInsert and AdvertErase815// Currently implemented for CTable and CProduct.816//817818template<typename T>819void AdvertStartPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)820{821 // Add to sources822 obj.setSources.insert(pfrom->addr.ip);823824 if (!AdvertInsert(obj))825 return;826827 // Relay828 CRITICAL_BLOCK(cs_vNodes)829 foreach(CNode* pnode, vNodes)830 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))831 pnode->PushMessage("publish", nChannel, nHops, obj);832}833834template<typename T>835void AdvertStopPublish(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)836{837 uint256 hash = obj.GetHash();838839 CRITICAL_BLOCK(cs_vNodes)840 foreach(CNode* pnode, vNodes)841 if (pnode != pfrom && (nHops < PUBLISH_HOPS || pnode->IsSubscribed(nChannel)))842 pnode->PushMessage("pub-cancel", nChannel, nHops, hash);843844 AdvertErase(obj);845}846847template<typename T>848void AdvertRemoveSource(CNode* pfrom, unsigned int nChannel, unsigned int nHops, T& obj)849{850 // Remove a source851 obj.setSources.erase(pfrom->addr.ip);852853 // If no longer supported by any sources, cancel it854 if (obj.setSources.empty())855 AdvertStopPublish(pfrom, nChannel, nHops, obj);856}
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
