diff --git a/src/seeder/bitcoin.cpp b/src/seeder/bitcoin.cpp index bf7033773..e3330c35d 100644 --- a/src/seeder/bitcoin.cpp +++ b/src/seeder/bitcoin.cpp @@ -1,321 +1,336 @@ #include "bitcoin.h" #include "db.h" #include "netbase.h" #include "serialize.h" #include "streams.h" #include "uint256.h" #include #define BITCOIN_SEED_NONCE 0x0539a019ca550825ULL +static const uint32_t allones(-1); + class CNode { SOCKET sock; CDataStream vSend; CDataStream vRecv; - unsigned int nHeaderStart; - unsigned int nMessageStart; + uint32_t nHeaderStart; + uint32_t nMessageStart; int nVersion; std::string strSubVer; int nStartingHeight; std::vector *vAddr; int ban; int64_t doneAfter; CAddress you; int GetTimeout() { return you.IsTor() ? 120 : 30; } void BeginMessage(const char *pszCommand) { - if (nHeaderStart != -1) AbortMessage(); + if (nHeaderStart != allones) { + AbortMessage(); + } nHeaderStart = vSend.size(); vSend << CMessageHeader(pszCommand, 0); nMessageStart = vSend.size(); // printf("%s: SEND %s\n", ToString(you).c_str(), pszCommand); } void AbortMessage() { - if (nHeaderStart == -1) return; + if (nHeaderStart == allones) { + return; + } vSend.resize(nHeaderStart); - nHeaderStart = -1; - nMessageStart = -1; + nHeaderStart = allones; + nMessageStart = allones; } void EndMessage() { - if (nHeaderStart == -1) return; - unsigned int nSize = vSend.size() - nMessageStart; + if (nHeaderStart == allones) { + return; + } + uint32_t nSize = vSend.size() - nMessageStart; memcpy((char *)&vSend[nHeaderStart] + offsetof(CMessageHeader, nMessageSize), &nSize, sizeof(nSize)); if (vSend.GetVersion() >= 209) { uint256 hash = Hash(vSend.begin() + nMessageStart, vSend.end()); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); assert(nMessageStart - nHeaderStart >= offsetof(CMessageHeader, nChecksum) + sizeof(nChecksum)); memcpy((char *)&vSend[nHeaderStart] + offsetof(CMessageHeader, nChecksum), &nChecksum, sizeof(nChecksum)); } - nHeaderStart = -1; - nMessageStart = -1; + nHeaderStart = allones; + nMessageStart = allones; } void Send() { - if (sock == INVALID_SOCKET) return; - if (vSend.empty()) return; + if (sock == INVALID_SOCKET) { + return; + } + if (vSend.empty()) { + return; + } int nBytes = send(sock, &vSend[0], vSend.size(), 0); if (nBytes > 0) { vSend.erase(vSend.begin(), vSend.begin() + nBytes); } else { close(sock); sock = INVALID_SOCKET; } } void PushVersion() { int64_t nTime = time(nullptr); uint64_t nLocalNonce = BITCOIN_SEED_NONCE; int64_t nLocalServices = 0; CAddress me(CService("0.0.0.0")); BeginMessage("version"); int nBestHeight = GetRequireHeight(); std::string ver = "/bitcoin-cash-seeder:0.15/"; vSend << PROTOCOL_VERSION << nLocalServices << nTime << you << me << nLocalNonce << ver << nBestHeight; EndMessage(); } void GotVersion() { // printf("\n%s: version %i\n", ToString(you).c_str(), nVersion); if (vAddr) { BeginMessage("getaddr"); EndMessage(); doneAfter = time(nullptr) + GetTimeout(); } else { doneAfter = time(nullptr) + 1; } } bool ProcessMessage(std::string strCommand, CDataStream &vRecv) { // printf("%s: RECV %s\n", ToString(you).c_str(), // strCommand.c_str()); if (strCommand == "version") { int64_t nTime; CAddress addrMe; CAddress addrFrom; uint64_t nNonce = 1; vRecv >> nVersion >> you.nServices >> nTime >> addrMe; if (nVersion == 10300) nVersion = 300; if (nVersion >= 106 && !vRecv.empty()) vRecv >> addrFrom >> nNonce; if (nVersion >= 106 && !vRecv.empty()) vRecv >> strSubVer; if (nVersion >= 209 && !vRecv.empty()) vRecv >> nStartingHeight; if (nVersion >= 209) { BeginMessage("verack"); EndMessage(); } vSend.SetVersion(std::min(nVersion, PROTOCOL_VERSION)); if (nVersion < 209) { this->vRecv.SetVersion(std::min(nVersion, PROTOCOL_VERSION)); GotVersion(); } return false; } if (strCommand == "verack") { this->vRecv.SetVersion(std::min(nVersion, PROTOCOL_VERSION)); GotVersion(); return false; } if (strCommand == "addr" && vAddr) { std::vector vAddrNew; vRecv >> vAddrNew; // printf("%s: got %i addresses\n", ToString(you).c_str(), // (int)vAddrNew.size()); int64_t now = time(nullptr); std::vector::iterator it = vAddrNew.begin(); if (vAddrNew.size() > 1) { if (doneAfter == 0 || doneAfter > now + 1) doneAfter = now + 1; } while (it != vAddrNew.end()) { CAddress &addr = *it; // printf("%s: got address %s\n", ToString(you).c_str(), // addr.ToString().c_str(), (int)(vAddr->size())); it++; if (addr.nTime <= 100000000 || addr.nTime > now + 600) addr.nTime = now - 5 * 86400; if (addr.nTime > now - 604800) vAddr->push_back(addr); // printf("%s: added address %s (#%i)\n", // ToString(you).c_str(), addr.ToString().c_str(), // (int)(vAddr->size())); if (vAddr->size() > 1000) { doneAfter = 1; return true; } } return false; } return false; } bool ProcessMessages() { - if (vRecv.empty()) return false; + if (vRecv.empty()) { + return false; + } + do { CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart)); - int nHeaderSize = GetSerializeSize( + uint32_t nHeaderSize = GetSerializeSize( CMessageHeader(), vRecv.GetType(), vRecv.GetVersion()); if (vRecv.end() - pstart < nHeaderSize) { if (vRecv.size() > nHeaderSize) { vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize); } break; } vRecv.erase(vRecv.begin(), pstart); std::vector vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize); CMessageHeader hdr; vRecv >> hdr; if (!hdr.IsValid()) { // printf("%s: BAD (invalid header)\n", ToString(you).c_str()); ban = 100000; return true; } std::string strCommand = hdr.GetCommand(); unsigned int nMessageSize = hdr.nMessageSize; if (nMessageSize > MAX_SIZE) { // printf("%s: BAD (message too large)\n", // ToString(you).c_str()); ban = 100000; return true; } if (nMessageSize > vRecv.size()) { vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end()); break; } if (vRecv.GetVersion() >= 209) { uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize); unsigned int nChecksum = 0; memcpy(&nChecksum, &hash, sizeof(nChecksum)); if (nChecksum != hdr.nChecksum) continue; } CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.GetType(), vRecv.GetVersion()); vRecv.ignore(nMessageSize); if (ProcessMessage(strCommand, vMsg)) return true; // printf("%s: done processing %s\n", ToString(you).c_str(), // strCommand.c_str()); } while (1); return false; } public: CNode(const CService &ip, std::vector *vAddrIn) - : vSend(SER_NETWORK, 0), vRecv(SER_NETWORK, 0), you(ip), - nHeaderStart(-1), nMessageStart(-1), vAddr(vAddrIn), ban(0), - doneAfter(0), nVersion(0) { + : vSend(SER_NETWORK, 0), vRecv(SER_NETWORK, 0), nHeaderStart(-1), + nMessageStart(-1), nVersion(0), vAddr(vAddrIn), ban(0), doneAfter(0), + you(ip) { if (time(nullptr) > 1329696000) { vSend.SetVersion(209); vRecv.SetVersion(209); } } bool Run() { bool res = true; if (!ConnectSocket(you, sock)) return false; PushVersion(); Send(); int64_t now; while (now = time(nullptr), ban == 0 && (doneAfter == 0 || doneAfter > now) && sock != INVALID_SOCKET) { char pchBuf[0x10000]; fd_set set; FD_ZERO(&set); FD_SET(sock, &set); struct timeval wa; if (doneAfter) { wa.tv_sec = doneAfter - now; wa.tv_usec = 0; } else { wa.tv_sec = GetTimeout(); wa.tv_usec = 0; } int ret = select(sock + 1, &set, nullptr, &set, &wa); if (ret != 1) { if (!doneAfter) res = false; break; } int nBytes = recv(sock, pchBuf, sizeof(pchBuf), 0); int nPos = vRecv.size(); if (nBytes > 0) { vRecv.resize(nPos + nBytes); memcpy(&vRecv[nPos], pchBuf, nBytes); } else if (nBytes == 0) { // printf("%s: BAD (connection closed prematurely)\n", // ToString(you).c_str()); res = false; break; } else { // printf("%s: BAD (connection error)\n", // ToString(you).c_str()); res = false; break; } ProcessMessages(); Send(); } if (sock == INVALID_SOCKET) res = false; close(sock); sock = INVALID_SOCKET; return (ban == 0) && res; } int GetBan() { return ban; } int GetClientVersion() { return nVersion; } std::string GetClientSubVersion() { return strSubVer; } int GetStartingHeight() { return nStartingHeight; } }; bool TestNode(const CService &cip, int &ban, int &clientV, std::string &clientSV, int &blocks, std::vector *vAddr) { try { CNode node(cip, vAddr); bool ret = node.Run(); if (!ret) { ban = node.GetBan(); } else { ban = 0; } clientV = node.GetClientVersion(); clientSV = node.GetClientSubVersion(); blocks = node.GetStartingHeight(); // printf("%s: %s!!!\n", cip.ToString().c_str(), ret ? "GOOD" : "BAD"); return ret; } catch (std::ios_base::failure &e) { ban = 0; return false; } } /* int main(void) { CService ip("bitcoin.sipa.be", 8333, true); std::vector vAddr; vAddr.clear(); int ban = 0; bool ret = TestNode(ip, ban, vAddr); printf("ret=%s ban=%i vAddr.size()=%i\n", ret ? "good" : "bad", ban, (int)vAddr.size()); } */ diff --git a/src/seeder/db.cpp b/src/seeder/db.cpp index ebd522b2b..08b17159f 100644 --- a/src/seeder/db.cpp +++ b/src/seeder/db.cpp @@ -1,209 +1,229 @@ #include "db.h" #include void CAddrInfo::Update(bool good) { uint32_t now = time(nullptr); if (ourLastTry == 0) ourLastTry = now - MIN_RETRY; int age = now - ourLastTry; lastTry = now; ourLastTry = now; total++; if (good) { success++; ourLastSuccess = now; } stat2H.Update(good, age, 3600 * 2); stat8H.Update(good, age, 3600 * 8); stat1D.Update(good, age, 3600 * 24); stat1W.Update(good, age, 3600 * 24 * 7); stat1M.Update(good, age, 3600 * 24 * 30); int ign = GetIgnoreTime(); if (ign && (ignoreTill == 0 || ignoreTill < ign + now)) ignoreTill = ign + now; // printf("%s: got %s result: success=%i/%i; 2H:%.2f%%-%.2f%%(%.2f) // 8H:%.2f%%-%.2f%%(%.2f) 1D:%.2f%%-%.2f%%(%.2f) 1W:%.2f%%-%.2f%%(%.2f) // \n", ToString(ip).c_str(), good ? "good" : "bad", success, total, // 100.0 * stat2H.reliability, 100.0 * (stat2H.reliability + 1.0 - // stat2H.weight), stat2H.count, // 100.0 * stat8H.reliability, 100.0 * (stat8H.reliability + 1.0 - // stat8H.weight), stat8H.count, // 100.0 * stat1D.reliability, 100.0 * (stat1D.reliability + 1.0 - // stat1D.weight), stat1D.count, // 100.0 * stat1W.reliability, 100.0 * (stat1W.reliability + 1.0 - // stat1W.weight), stat1W.count); } bool CAddrDb::Get_(CServiceResult &ip, int &wait) { int64_t now = time(nullptr); - int cont = 0; - int tot = unkId.size() + ourId.size(); + size_t tot = unkId.size() + ourId.size(); if (tot == 0) { wait = 5; return false; } + do { - int rnd = rand() % tot; + size_t rnd = rand() % tot; int ret; if (rnd < unkId.size()) { std::set::iterator it = unkId.end(); it--; ret = *it; unkId.erase(it); } else { ret = ourId.front(); - if (time(nullptr) - idToInfo[ret].ourLastTry < MIN_RETRY) + if (time(nullptr) - idToInfo[ret].ourLastTry < MIN_RETRY) { return false; + } ourId.pop_front(); } + if (idToInfo[ret].ignoreTill && idToInfo[ret].ignoreTill < now) { ourId.push_back(ret); idToInfo[ret].ourLastTry = now; } else { ip.service = idToInfo[ret].ip; ip.ourLastSuccess = idToInfo[ret].ourLastSuccess; break; } } while (1); + nDirty++; return true; } int CAddrDb::Lookup_(const CService &ip) { if (ipToId.count(ip)) return ipToId[ip]; return -1; } void CAddrDb::Good_(const CService &addr, int clientV, std::string clientSV, int blocks) { int id = Lookup_(addr); if (id == -1) return; unkId.erase(id); banned.erase(addr); CAddrInfo &info = idToInfo[id]; info.clientVersion = clientV; info.clientSubVersion = clientSV; info.blocks = blocks; info.Update(true); if (info.IsGood() && goodId.count(id) == 0) { goodId.insert(id); // printf("%s: good; %i good nodes now\n", ToString(addr).c_str(), // (int)goodId.size()); } nDirty++; ourId.push_back(id); } void CAddrDb::Bad_(const CService &addr, int ban) { int id = Lookup_(addr); if (id == -1) return; unkId.erase(id); CAddrInfo &info = idToInfo[id]; info.Update(false); uint32_t now = time(nullptr); int ter = info.GetBanTime(); if (ter) { // printf("%s: terrible\n", ToString(addr).c_str()); if (ban < ter) ban = ter; } if (ban > 0) { // printf("%s: ban for %i seconds\n", ToString(addr).c_str(), ban); banned[info.ip] = ban + now; ipToId.erase(info.ip); goodId.erase(id); idToInfo.erase(id); } else { if (/*!info.IsGood() && */ goodId.count(id) == 1) { goodId.erase(id); // printf("%s: not good; %i good nodes left\n", // ToString(addr).c_str(), (int)goodId.size()); } ourId.push_back(id); } nDirty++; } void CAddrDb::Skipped_(const CService &addr) { int id = Lookup_(addr); if (id == -1) return; unkId.erase(id); ourId.push_back(id); // printf("%s: skipped\n", ToString(addr).c_str()); nDirty++; } void CAddrDb::Add_(const CAddress &addr, bool force) { - if (!force && !addr.IsRoutable()) return; + if (!force && !addr.IsRoutable()) { + return; + } CService ipp(addr); if (banned.count(ipp)) { time_t bantime = banned[ipp]; - if (force || (bantime < time(nullptr) && addr.nTime > bantime)) + if (force || (bantime < time(nullptr) && addr.nTime > bantime)) { banned.erase(ipp); - else + } else { return; + } } if (ipToId.count(ipp)) { CAddrInfo &ai = idToInfo[ipToId[ipp]]; if (addr.nTime > ai.lastTry || ai.services != addr.nServices) { ai.lastTry = addr.nTime; ai.services |= addr.nServices; // printf("%s: updated\n", ToString(addr).c_str()); } if (force) { ai.ignoreTill = 0; } return; } + CAddrInfo ai; ai.ip = ipp; ai.services = addr.nServices; ai.lastTry = addr.nTime; ai.ourLastTry = 0; ai.total = 0; ai.success = 0; int id = nId++; idToInfo[id] = ai; ipToId[ipp] = id; // printf("%s: added\n", ToString(ipp).c_str(), ipToId[ipp]); unkId.insert(id); nDirty++; } -void CAddrDb::GetIPs_(std::set &ips, uint64_t requestedFlags, int max, - const bool *nets) { +void CAddrDb::GetIPs_(std::set &ips, uint64_t requestedFlags, + uint32_t max, const bool *nets) { if (goodId.size() == 0) { int id = -1; if (ourId.size() == 0) { - if (unkId.size() == 0) return; + if (unkId.size() == 0) { + return; + } id = *unkId.begin(); } else { id = *ourId.begin(); } + if (id >= 0 && (idToInfo[id].services & requestedFlags) == requestedFlags) { ips.insert(idToInfo[id].ip); } return; } + std::vector goodIdFiltered; - for (std::set::const_iterator it = goodId.begin(); it != goodId.end(); - it++) { - if ((idToInfo[*it].services & requestedFlags) == requestedFlags) - goodIdFiltered.push_back(*it); + for (auto &id : goodId) { + if ((idToInfo[id].services & requestedFlags) == requestedFlags) { + goodIdFiltered.push_back(id); + } } - if (!goodIdFiltered.size()) return; + if (!goodIdFiltered.size()) { + return; + } - if (max > goodIdFiltered.size() / 2) max = goodIdFiltered.size() / 2; - if (max < 1) max = 1; + if (max > goodIdFiltered.size() / 2) { + max = goodIdFiltered.size() / 2; + } + + if (max < 1) { + max = 1; + } std::set ids; while (ids.size() < max) { ids.insert(goodIdFiltered[rand() % goodIdFiltered.size()]); } - for (std::set::const_iterator it = ids.begin(); it != ids.end(); - it++) { - CService &ip = idToInfo[*it].ip; - if (nets[ip.GetNetwork()]) ips.insert(ip); + + for (auto &id : ids) { + CService &ip = idToInfo[id].ip; + if (nets[ip.GetNetwork()]) { + ips.insert(ip); + } } } diff --git a/src/seeder/db.h b/src/seeder/db.h index 8a7d2ec04..52d5824ed 100644 --- a/src/seeder/db.h +++ b/src/seeder/db.h @@ -1,425 +1,444 @@ #ifndef BITCOIN_SEEDER_DB_H #define BITCOIN_SEEDER_DB_H #include "netbase.h" #include "protocol.h" #include "sync.h" #include "util.h" #include "version.h" #include #include #include #include #include #include #define MIN_RETRY 1000 #define REQUIRE_VERSION 70001 static inline int GetRequireHeight(const bool testnet = fTestNet) { return testnet ? 500000 : 350000; } static inline std::string ToString(const CService &ip) { std::string str = ip.ToString(); - while (str.size() < 22) + while (str.size() < 22) { str += ' '; + } return str; } class CAddrStat { private: float weight; float count; float reliability; public: CAddrStat() : weight(0), count(0), reliability(0) {} void Update(bool good, int64_t age, double tau) { double f = exp(-age / tau); reliability = reliability * f + (good ? (1.0 - f) : 0); count = count * f + 1; weight = weight * f + (1.0 - f); } ADD_SERIALIZE_METHODS; template inline void SerializationOp(Stream &s, Operation ser_action) { READWRITE(weight); READWRITE(count); READWRITE(reliability); } friend class CAddrInfo; }; class CAddrReport { public: CService ip; int clientVersion; int blocks; double uptime[5]; std::string clientSubVersion; int64_t lastSuccess; bool fGood; uint64_t services; }; class CAddrInfo { private: CService ip; uint64_t services; int64_t lastTry; int64_t ourLastTry; int64_t ourLastSuccess; int64_t ignoreTill; CAddrStat stat2H; CAddrStat stat8H; CAddrStat stat1D; CAddrStat stat1W; CAddrStat stat1M; int clientVersion; int blocks; int total; int success; std::string clientSubVersion; public: CAddrInfo() : services(0), lastTry(0), ourLastTry(0), ourLastSuccess(0), ignoreTill(0), clientVersion(0), blocks(0), total(0), success(0) {} CAddrReport GetReport() const { CAddrReport ret; ret.ip = ip; ret.clientVersion = clientVersion; ret.clientSubVersion = clientSubVersion; ret.blocks = blocks; ret.uptime[0] = stat2H.reliability; ret.uptime[1] = stat8H.reliability; ret.uptime[2] = stat1D.reliability; ret.uptime[3] = stat1W.reliability; ret.uptime[4] = stat1M.reliability; ret.lastSuccess = ourLastSuccess; ret.fGood = IsGood(); ret.services = services; return ret; } bool IsGood() const { if (ip.GetPort() != GetDefaultPort()) return false; if (!(services & NODE_NETWORK)) return false; if (!(services & NODE_BITCOIN_CASH)) return false; if (!ip.IsRoutable()) return false; if (clientVersion && clientVersion < REQUIRE_VERSION) return false; if (blocks && blocks < GetRequireHeight()) return false; if (total <= 3 && success * 2 >= total) return true; if (stat2H.reliability > 0.85 && stat2H.count > 2) return true; if (stat8H.reliability > 0.70 && stat8H.count > 4) return true; if (stat1D.reliability > 0.55 && stat1D.count > 8) return true; if (stat1W.reliability > 0.45 && stat1W.count > 16) return true; if (stat1M.reliability > 0.35 && stat1M.count > 32) return true; return false; } + int GetBanTime() const { - if (IsGood()) return 0; + if (IsGood()) { + return 0; + } if (clientVersion && clientVersion < 31900) { return 604800; } if (stat1M.reliability - stat1M.weight + 1.0 < 0.15 && stat1M.count > 32) { return 30 * 86400; } if (stat1W.reliability - stat1W.weight + 1.0 < 0.10 && stat1W.count > 16) { return 7 * 86400; } if (stat1D.reliability - stat1D.weight + 1.0 < 0.05 && stat1D.count > 8) { return 1 * 86400; } return 0; } + int GetIgnoreTime() const { - if (IsGood()) return 0; + if (IsGood()) { + return 0; + } if (stat1M.reliability - stat1M.weight + 1.0 < 0.20 && stat1M.count > 2) { return 10 * 86400; } if (stat1W.reliability - stat1W.weight + 1.0 < 0.16 && stat1W.count > 2) { return 3 * 86400; } if (stat1D.reliability - stat1D.weight + 1.0 < 0.12 && stat1D.count > 2) { return 8 * 3600; } if (stat8H.reliability - stat8H.weight + 1.0 < 0.08 && stat8H.count > 2) { return 2 * 3600; } return 0; } void Update(bool good); friend class CAddrDb; ADD_SERIALIZE_METHODS; template inline void SerializationOp(Stream &s, Operation ser_action) { uint8_t version = 4; READWRITE(version); READWRITE(ip); READWRITE(services); READWRITE(lastTry); uint8_t tried = ourLastTry != 0; READWRITE(tried); - if (tried) { - READWRITE(ourLastTry); - READWRITE(ignoreTill); - READWRITE(stat2H); - READWRITE(stat8H); - READWRITE(stat1D); - READWRITE(stat1W); - if (version >= 1) { - READWRITE(stat1M); - } else if (!ser_action.ForRead()) { - *((CAddrStat *)(&stat1M)) = stat1W; - } - READWRITE(total); - READWRITE(success); - READWRITE(clientVersion); - if (version >= 2) READWRITE(clientSubVersion); - if (version >= 3) READWRITE(blocks); - if (version >= 4) READWRITE(ourLastSuccess); + if (!tried) { + return; + } + + READWRITE(ourLastTry); + READWRITE(ignoreTill); + READWRITE(stat2H); + READWRITE(stat8H); + READWRITE(stat1D); + READWRITE(stat1W); + if (version >= 1) { + READWRITE(stat1M); + } else if (!ser_action.ForRead()) { + *((CAddrStat *)(&stat1M)) = stat1W; } + READWRITE(total); + READWRITE(success); + READWRITE(clientVersion); + if (version >= 2) READWRITE(clientSubVersion); + if (version >= 3) READWRITE(blocks); + if (version >= 4) READWRITE(ourLastSuccess); } }; class CAddrDbStats { public: int nBanned; int nAvail; int nTracked; int nNew; int nGood; int nAge; }; struct CServiceResult { CService service; bool fGood; int nBanTime; int nHeight; int nClientV; std::string strClientV; int64_t ourLastSuccess; }; -// seen nodes -// / \ -// (a) banned nodes available nodes-------------- -// / | \ -// tracked nodes (b) unknown nodes (e) active nodes -// / \ -// (d) good nodes (c) non-good nodes - +/** + * seen nodes + * / \ + * (a) banned nodes available nodes-------------- + * / | \ + * tracked nodes (b) unknown nodes (e) active nodes + * / \ + * (d) good nodes (c) non-good nodes + */ class CAddrDb { private: mutable CCriticalSection cs; // number of address id's int nId; // map address id to address info (b,c,d,e) std::map idToInfo; // map ip to id (b,c,d,e) std::map ipToId; // sequence of tried nodes, in order we have tried connecting to them (c,d) std::deque ourId; // set of nodes not yet tried (b) std::set unkId; // set of good nodes (d, good e) std::set goodId; int nDirty; protected: // internal routines that assume proper locks are acquired // add an address void Add_(const CAddress &addr, bool force); // get an IP to test (must call Good_, Bad_, or Skipped_ on result // afterwards) bool Get_(CServiceResult &ip, int &wait); bool GetMany_(std::vector &ips, int max, int &wait); // mark an IP as good (must have been returned by Get_) void Good_(const CService &ip, int clientV, std::string clientSV, int blocks); // mark an IP as bad (and optionally ban it) (must have been returned by // Get_) void Bad_(const CService &ip, int ban); // mark an IP as skipped (must have been returned by Get_) void Skipped_(const CService &ip); // look up id of an IP int Lookup_(const CService &ip); // get a random set of IPs (shared lock only) - void GetIPs_(std::set &ips, uint64_t requestedFlags, int max, + void GetIPs_(std::set &ips, uint64_t requestedFlags, uint32_t max, const bool *nets); public: // nodes that are banned, with their unban time (a) std::map banned; void GetStats(CAddrDbStats &stats) { LOCK(cs); stats.nBanned = banned.size(); stats.nAvail = idToInfo.size(); stats.nTracked = ourId.size(); stats.nGood = goodId.size(); stats.nNew = unkId.size(); stats.nAge = time(nullptr) - idToInfo[ourId[0]].ourLastTry; } void ResetIgnores() { for (std::map::iterator it = idToInfo.begin(); it != idToInfo.end(); it++) { (*it).second.ignoreTill = 0; } } std::vector GetAll() { std::vector ret; LOCK(cs); for (std::deque::const_iterator it = ourId.begin(); it != ourId.end(); it++) { const CAddrInfo &info = idToInfo[*it]; if (info.success > 0) { ret.push_back(info.GetReport()); } } return ret; } // serialization code // format: // nVersion (0 for now) // n (number of ips in (b,c,d)) // CAddrInfo[n] // banned // acquires a shared lock (this does not suffice for read mode, but we - // assume that only happens at startup, single-threaded) - // this way, dumping does not interfere with GetIPs_, which is called from - // the DNS thread + // assume that only happens at startup, single-threaded) this way, dumping + // does not interfere with GetIPs_, which is called from the DNS thread template void Serialize(Stream &s) const { LOCK(cs); int nVersion = 0; s << nVersion; CAddrDb *db = const_cast(this); int n = ourId.size() + unkId.size(); s << n; for (std::deque::const_iterator it = ourId.begin(); it != ourId.end(); it++) { std::map::iterator ci = db->idToInfo.find(*it); s << (*ci).second; } for (std::set::const_iterator it = unkId.begin(); it != unkId.end(); it++) { std::map::iterator ci = db->idToInfo.find(*it); s << (*ci).second; } s << banned; } template void Unserialize(Stream &s) { LOCK(cs); int nVersion; s >> nVersion; CAddrDb *db = const_cast(this); db->nId = 0; int n; s >> n; for (int i = 0; i < n; i++) { CAddrInfo info; s >> info; if (!info.GetBanTime()) { int id = db->nId++; db->idToInfo[id] = info; db->ipToId[info.ip] = id; if (info.ourLastTry) { db->ourId.push_back(id); if (info.IsGood()) db->goodId.insert(id); } else { db->unkId.insert(id); } } } db->nDirty++; s >> banned; } void Add(const CAddress &addr, bool fForce = false) { LOCK(cs); Add_(addr, fForce); } + void Add(const std::vector &vAddr, bool fForce = false) { LOCK(cs); for (size_t i = 0; i < vAddr.size(); i++) { Add_(vAddr[i], fForce); } } + void Good(const CService &addr, int clientVersion, std::string clientSubVersion, int blocks) { LOCK(cs); Good_(addr, clientVersion, clientSubVersion, blocks); } + void Skipped(const CService &addr) { LOCK(cs); Skipped_(addr); } + void Bad(const CService &addr, int ban = 0) { LOCK(cs); Bad_(addr, ban); } + bool Get(CServiceResult &ip, int &wait) { LOCK(cs); return Get_(ip, wait); } + void GetMany(std::vector &ips, int max, int &wait) { LOCK(cs); while (max > 0) { CServiceResult ip = {}; - if (!Get_(ip, wait)) return; + if (!Get_(ip, wait)) { + return; + } ips.push_back(ip); max--; } } + void ResultMany(const std::vector &ips) { LOCK(cs); - for (int i = 0; i < ips.size(); i++) { + for (size_t i = 0; i < ips.size(); i++) { if (ips[i].fGood) { Good_(ips[i].service, ips[i].nClientV, ips[i].strClientV, ips[i].nHeight); } else { Bad_(ips[i].service, ips[i].nBanTime); } } } - void GetIPs(std::set &ips, uint64_t requestedFlags, int max, + + void GetIPs(std::set &ips, uint64_t requestedFlags, uint32_t max, const bool *nets) { LOCK(cs); GetIPs_(ips, requestedFlags, max, nets); } }; #endif diff --git a/src/seeder/dns.h b/src/seeder/dns.h index fb07dcdad..902304945 100644 --- a/src/seeder/dns.h +++ b/src/seeder/dns.h @@ -1,29 +1,29 @@ #ifndef BITCOIN_SEEDER_DNS_H #define BITCOIN_SEEDER_DNS_H 1 #include typedef struct { int v; union { uint8_t v4[4]; uint8_t v6[16]; } data; } addr_t; typedef struct { int port; int datattl; int nsttl; const char *host; const char *ns; const char *mbox; - int (*cb)(void *opt, char *requested_hostname, addr_t *addr, int max, - int ipv4, int ipv6); + uint32_t (*cb)(void *opt, char *requested_hostname, addr_t *addr, + uint32_t max, uint32_t ipv4, uint32_t ipv6); // stats uint64_t nRequests; } dns_opt_t; extern int dnsserver(dns_opt_t *opt); #endif diff --git a/src/seeder/main.cpp b/src/seeder/main.cpp index 3a36b2e4f..557d7ecfc 100644 --- a/src/seeder/main.cpp +++ b/src/seeder/main.cpp @@ -1,560 +1,573 @@ #include "bitcoin.h" #include "clientversion.h" #include "db.h" #include "streams.h" #include #include #include #include #include #include #include #define __STDC_FORMAT_MACROS #include bool fTestNet = false; class CDnsSeedOpts { public: int nThreads; int nPort; int nDnsThreads; int fUseTestNet; int fWipeBan; int fWipeIgnore; const char *mbox; const char *ns; const char *host; const char *tor; const char *ipv4_proxy; const char *ipv6_proxy; std::set filter_whitelist; CDnsSeedOpts() - : nThreads(96), nDnsThreads(4), nPort(53), mbox(nullptr), ns(nullptr), - host(nullptr), tor(nullptr), fUseTestNet(false), fWipeBan(false), - fWipeIgnore(false), ipv4_proxy(nullptr), ipv6_proxy(nullptr) {} + : nThreads(96), nPort(53), nDnsThreads(4), fUseTestNet(false), + fWipeBan(false), fWipeIgnore(false), mbox(nullptr), ns(nullptr), + host(nullptr), tor(nullptr), ipv4_proxy(nullptr), + ipv6_proxy(nullptr) {} void ParseCommandLine(int argc, char **argv) { static const char *help = "Bitcoin-cash-seeder\n" "Usage: %s -h -n [-m ] [-t ] [-p " "]\n" "\n" "Options:\n" "-h Hostname of the DNS seed\n" "-n Hostname of the nameserver\n" "-m E-Mail address reported in SOA records\n" "-t Number of crawlers to run in parallel (default " "96)\n" "-d Number of DNS server threads (default 4)\n" "-p UDP port to listen on (default 53)\n" "-o Tor proxy IP/Port\n" "-i IPV4 SOCKS5 proxy IP/Port\n" "-k IPV6 SOCKS5 proxy IP/Port\n" "-w f1,f2,... Allow these flag combinations as filters\n" "--testnet Use testnet\n" "--wipeban Wipe list of banned nodes\n" "--wipeignore Wipe list of ignored nodes\n" "-?, --help Show this text\n" "\n"; bool showHelp = false; while (1) { static struct option long_options[] = { {"host", required_argument, 0, 'h'}, {"ns", required_argument, 0, 'n'}, {"mbox", required_argument, 0, 'm'}, {"threads", required_argument, 0, 't'}, {"dnsthreads", required_argument, 0, 'd'}, {"port", required_argument, 0, 'p'}, {"onion", required_argument, 0, 'o'}, {"proxyipv4", required_argument, 0, 'i'}, {"proxyipv6", required_argument, 0, 'k'}, {"filter", required_argument, 0, 'w'}, {"testnet", no_argument, &fUseTestNet, 1}, {"wipeban", no_argument, &fWipeBan, 1}, {"wipeignore", no_argument, &fWipeBan, 1}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0}}; int option_index = 0; int c = getopt_long(argc, argv, "h:n:m:t:p:d:o:i:k:w:", long_options, &option_index); if (c == -1) break; switch (c) { case 'h': { host = optarg; break; } case 'm': { mbox = optarg; break; } case 'n': { ns = optarg; break; } case 't': { int n = strtol(optarg, nullptr, 10); if (n > 0 && n < 1000) nThreads = n; break; } case 'd': { int n = strtol(optarg, nullptr, 10); if (n > 0 && n < 1000) nDnsThreads = n; break; } case 'p': { int p = strtol(optarg, nullptr, 10); if (p > 0 && p < 65536) nPort = p; break; } case 'o': { tor = optarg; break; } case 'i': { ipv4_proxy = optarg; break; } case 'k': { ipv6_proxy = optarg; break; } case 'w': { char *ptr = optarg; while (*ptr != 0) { unsigned long l = strtoul(ptr, &ptr, 0); if (*ptr == ',') { ptr++; } else if (*ptr != 0) { break; } filter_whitelist.insert(l); } break; } case '?': { showHelp = true; break; } } } if (filter_whitelist.empty()) { filter_whitelist.insert(NODE_NETWORK | NODE_BITCOIN_CASH); filter_whitelist.insert(NODE_NETWORK | NODE_BITCOIN_CASH | NODE_BLOOM); filter_whitelist.insert(NODE_NETWORK | NODE_BITCOIN_CASH | NODE_XTHIN); filter_whitelist.insert(NODE_NETWORK | NODE_BITCOIN_CASH | NODE_BLOOM | NODE_XTHIN); } if (host != nullptr && ns == nullptr) showHelp = true; if (showHelp) fprintf(stderr, help, argv[0]); } }; extern "C" { #include "dns.h" } CAddrDb db; extern "C" void *ThreadCrawler(void *data) { int *nThreads = (int *)data; do { std::vector ips; int wait = 5; db.GetMany(ips, 16, wait); int64_t now = time(nullptr); if (ips.empty()) { wait *= 1000; wait += rand() % (500 * *nThreads); Sleep(wait); continue; } + std::vector addr; - for (int i = 0; i < ips.size(); i++) { + for (size_t i = 0; i < ips.size(); i++) { CServiceResult &res = ips[i]; res.nBanTime = 0; res.nClientV = 0; res.nHeight = 0; res.strClientV = ""; bool getaddr = res.ourLastSuccess + 86400 < now; res.fGood = TestNode(res.service, res.nBanTime, res.nClientV, res.strClientV, res.nHeight, getaddr ? &addr : nullptr); } + db.ResultMany(ips); db.Add(addr); } while (1); return nullptr; } -extern "C" int GetIPList(void *thread, char *requestedHostname, addr_t *addr, - int max, int ipv4, int ipv6); +extern "C" uint32_t GetIPList(void *thread, char *requestedHostname, + addr_t *addr, uint32_t max, uint32_t ipv4, + uint32_t ipv6); class CDnsThread { public: struct FlagSpecificData { int nIPv4, nIPv6; std::vector cache; time_t cacheTime; unsigned int cacheHits; FlagSpecificData() : nIPv4(0), nIPv6(0), cacheTime(0), cacheHits(0) {} }; dns_opt_t dns_opt; // must be first const int id; std::map perflag; std::atomic dbQueries; std::set filterWhitelist; void cacheHit(uint64_t requestedFlags, bool force = false) { static bool nets[NET_MAX] = {}; if (!nets[NET_IPV4]) { nets[NET_IPV4] = true; nets[NET_IPV6] = true; } time_t now = time(nullptr); FlagSpecificData &thisflag = perflag[requestedFlags]; thisflag.cacheHits++; if (force || thisflag.cacheHits * 400 > (thisflag.cache.size() * thisflag.cache.size()) || (thisflag.cacheHits * thisflag.cacheHits * 20 > thisflag.cache.size() && (now - thisflag.cacheTime > 5))) { std::set ips; db.GetIPs(ips, requestedFlags, 1000, nets); dbQueries++; thisflag.cache.clear(); thisflag.nIPv4 = 0; thisflag.nIPv6 = 0; thisflag.cache.reserve(ips.size()); for (auto &ip : ips) { struct in_addr addr; struct in6_addr addr6; if (ip.GetInAddr(&addr)) { addr_t a; a.v = 4; memcpy(&a.data.v4, &addr, 4); thisflag.cache.push_back(a); thisflag.nIPv4++; } else if (ip.GetIn6Addr(&addr6)) { addr_t a; a.v = 6; memcpy(&a.data.v6, &addr6, 16); thisflag.cache.push_back(a); thisflag.nIPv6++; } } thisflag.cacheHits = 0; thisflag.cacheTime = now; } } CDnsThread(CDnsSeedOpts *opts, int idIn) : id(idIn) { dns_opt.host = opts->host; dns_opt.ns = opts->ns; dns_opt.mbox = opts->mbox; dns_opt.datattl = 3600; dns_opt.nsttl = 40000; dns_opt.cb = GetIPList; dns_opt.port = opts->nPort; dns_opt.nRequests = 0; dbQueries = 0; perflag.clear(); filterWhitelist = opts->filter_whitelist; } void run() { dnsserver(&dns_opt); } }; -extern "C" int GetIPList(void *data, char *requestedHostname, addr_t *addr, - int max, int ipv4, int ipv6) { +extern "C" uint32_t GetIPList(void *data, char *requestedHostname, addr_t *addr, + uint32_t max, uint32_t ipv4, uint32_t ipv6) { CDnsThread *thread = (CDnsThread *)data; uint64_t requestedFlags = 0; int hostlen = strlen(requestedHostname); if (hostlen > 1 && requestedHostname[0] == 'x' && requestedHostname[1] != '0') { char *pEnd; uint64_t flags = (uint64_t)strtoull(requestedHostname + 1, &pEnd, 16); if (*pEnd == '.' && pEnd <= requestedHostname + 17 && std::find(thread->filterWhitelist.begin(), thread->filterWhitelist.end(), - flags) != thread->filterWhitelist.end()) + flags) != thread->filterWhitelist.end()) { requestedFlags = flags; - else + } else { return 0; - } else if (strcasecmp(requestedHostname, thread->dns_opt.host)) + } + } else if (strcasecmp(requestedHostname, thread->dns_opt.host)) { return 0; + } thread->cacheHit(requestedFlags); auto &thisflag = thread->perflag[requestedFlags]; - unsigned int size = thisflag.cache.size(); - unsigned int maxmax = - (ipv4 ? thisflag.nIPv4 : 0) + (ipv6 ? thisflag.nIPv6 : 0); - if (max > size) max = size; - if (max > maxmax) max = maxmax; - int i = 0; + uint32_t size = thisflag.cache.size(); + uint32_t maxmax = (ipv4 ? thisflag.nIPv4 : 0) + (ipv6 ? thisflag.nIPv6 : 0); + if (max > size) { + max = size; + } + if (max > maxmax) { + max = maxmax; + } + uint32_t i = 0; while (i < max) { - int j = i + (rand() % (size - i)); + uint32_t j = i + (rand() % (size - i)); do { bool ok = (ipv4 && thisflag.cache[j].v == 4) || (ipv6 && thisflag.cache[j].v == 6); - if (ok) break; + if (ok) { + break; + } j++; - if (j == size) j = i; + if (j == size) { + j = i; + } } while (1); addr[i] = thisflag.cache[j]; thisflag.cache[j] = thisflag.cache[i]; thisflag.cache[i] = addr[i]; i++; } return max; } std::vector dnsThread; extern "C" void *ThreadDNS(void *arg) { CDnsThread *thread = (CDnsThread *)arg; thread->run(); return nullptr; } int StatCompare(const CAddrReport &a, const CAddrReport &b) { if (a.uptime[4] == b.uptime[4]) { if (a.uptime[3] == b.uptime[3]) { return a.clientVersion > b.clientVersion; } else { return a.uptime[3] > b.uptime[3]; } } else { return a.uptime[4] > b.uptime[4]; } } extern "C" void *ThreadDumper(void *) { int count = 0; do { // First 100s, than 200s, 400s, 800s, 1600s, and then 3200s forever Sleep(100000 << count); if (count < 5) { count++; } { std::vector v = db.GetAll(); sort(v.begin(), v.end(), StatCompare); FILE *f = fopen("dnsseed.dat.new", "w+"); if (f) { { CAutoFile cf(f, SER_DISK, CLIENT_VERSION); cf << db; } rename("dnsseed.dat.new", "dnsseed.dat"); } FILE *d = fopen("dnsseed.dump", "w"); fprintf(d, "# address good " "lastSuccess %%(2h) %%(8h) %%(1d) %%(7d) " "%%(30d) blocks svcs version\n"); double stat[5] = {0, 0, 0, 0, 0}; for (CAddrReport rep : v) { fprintf( d, "%-47s %4d %11" PRId64 " %6.2f%% %6.2f%% %6.2f%% %6.2f%% %6.2f%% %6i %08" PRIx64 " %5i \"%s\"\n", rep.ip.ToString().c_str(), (int)rep.fGood, rep.lastSuccess, 100.0 * rep.uptime[0], 100.0 * rep.uptime[1], 100.0 * rep.uptime[2], 100.0 * rep.uptime[3], 100.0 * rep.uptime[4], rep.blocks, rep.services, rep.clientVersion, rep.clientSubVersion.c_str()); stat[0] += rep.uptime[0]; stat[1] += rep.uptime[1]; stat[2] += rep.uptime[2]; stat[3] += rep.uptime[3]; stat[4] += rep.uptime[4]; } fclose(d); FILE *ff = fopen("dnsstats.log", "a"); fprintf(ff, "%llu %g %g %g %g %g\n", (unsigned long long)(time(nullptr)), stat[0], stat[1], stat[2], stat[3], stat[4]); fclose(ff); } } while (1); return nullptr; } extern "C" void *ThreadStats(void *) { bool first = true; do { char c[256]; time_t tim = time(nullptr); struct tm *tmp = localtime(&tim); strftime(c, 256, "[%y-%m-%d %H:%M:%S]", tmp); CAddrDbStats stats; db.GetStats(stats); if (first) { first = false; printf("\n\n\n\x1b[3A"); } else printf("\x1b[2K\x1b[u"); printf("\x1b[s"); uint64_t requests = 0; uint64_t queries = 0; for (unsigned int i = 0; i < dnsThread.size(); i++) { requests += dnsThread[i]->dns_opt.nRequests; queries += dnsThread[i]->dbQueries; } printf("%s %i/%i available (%i tried in %is, %i new, %i active), %i " "banned; %llu DNS requests, %llu db queries", c, stats.nGood, stats.nAvail, stats.nTracked, stats.nAge, stats.nNew, stats.nAvail - stats.nTracked - stats.nNew, stats.nBanned, (unsigned long long)requests, (unsigned long long)queries); Sleep(1000); } while (1); return nullptr; } static const std::string mainnet_seeds[] = { "seed.bitcoinabc.org", "seed-abc.bitcoinforks.org", "seed.bitprim.org", "seed.deadalnix.me", "seeder.criptolayer.net", ""}; static const std::string testnet_seeds[] = { "testnet-seed.bitcoinabc.org", "testnet-seed-abc.bitcoinforks.org", "testnet-seed.bitprim.org", "testnet-seed.deadalnix.me", "testnet-seeder.criptolayer.net", ""}; static const std::string *seeds = mainnet_seeds; extern "C" void *ThreadSeeder(void *) { if (!fTestNet) { db.Add(CService("kjy2eqzk4zwi5zd3.onion", 8333), true); } do { for (int i = 0; seeds[i] != ""; i++) { std::vector ips; LookupHost(seeds[i].c_str(), ips); for (auto &ip : ips) { db.Add(CService(ip, GetDefaultPort()), true); } } Sleep(1800000); } while (1); return nullptr; } int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); setbuf(stdout, nullptr); CDnsSeedOpts opts; opts.ParseCommandLine(argc, argv); printf("Supporting whitelisted filters: "); for (std::set::const_iterator it = opts.filter_whitelist.begin(); it != opts.filter_whitelist.end(); it++) { if (it != opts.filter_whitelist.begin()) { printf(","); } printf("0x%lx", (unsigned long)*it); } printf("\n"); if (opts.tor) { CService service(opts.tor, 9050); if (service.IsValid()) { printf("Using Tor proxy at %s\n", service.ToStringIPPort().c_str()); SetProxy(NET_TOR, service); } } if (opts.ipv4_proxy) { CService service(opts.ipv4_proxy, 9050); if (service.IsValid()) { printf("Using IPv4 proxy at %s\n", service.ToStringIPPort().c_str()); SetProxy(NET_IPV4, service); } } if (opts.ipv6_proxy) { CService service(opts.ipv6_proxy, 9050); if (service.IsValid()) { printf("Using IPv6 proxy at %s\n", service.ToStringIPPort().c_str()); SetProxy(NET_IPV6, service); } } bool fDNS = true; if (opts.fUseTestNet) { printf("Using testnet.\n"); pchMessageStart[0] = 0xf4; pchMessageStart[1] = 0xe5; pchMessageStart[2] = 0xf3; pchMessageStart[3] = 0xf4; seeds = testnet_seeds; fTestNet = true; } if (!opts.ns) { printf("No nameserver set. Not starting DNS server.\n"); fDNS = false; } if (fDNS && !opts.host) { fprintf(stderr, "No hostname set. Please use -h.\n"); exit(1); } if (fDNS && !opts.mbox) { fprintf(stderr, "No e-mail address set. Please use -m.\n"); exit(1); } FILE *f = fopen("dnsseed.dat", "r"); if (f) { printf("Loading dnsseed.dat..."); CAutoFile cf(f, SER_DISK, CLIENT_VERSION); cf >> db; if (opts.fWipeBan) db.banned.clear(); if (opts.fWipeIgnore) db.ResetIgnores(); printf("done\n"); } pthread_t threadDns, threadSeed, threadDump, threadStats; if (fDNS) { printf("Starting %i DNS threads for %s on %s (port %i)...", opts.nDnsThreads, opts.host, opts.ns, opts.nPort); dnsThread.clear(); for (int i = 0; i < opts.nDnsThreads; i++) { dnsThread.push_back(new CDnsThread(&opts, i)); pthread_create(&threadDns, nullptr, ThreadDNS, dnsThread[i]); printf("."); Sleep(20); } printf("done\n"); } printf("Starting seeder..."); pthread_create(&threadSeed, nullptr, ThreadSeeder, nullptr); printf("done\n"); printf("Starting %i crawler threads...", opts.nThreads); pthread_attr_t attr_crawler; pthread_attr_init(&attr_crawler); pthread_attr_setstacksize(&attr_crawler, 0x20000); for (int i = 0; i < opts.nThreads; i++) { pthread_t thread; pthread_create(&thread, &attr_crawler, ThreadCrawler, &opts.nThreads); } pthread_attr_destroy(&attr_crawler); printf("done\n"); pthread_create(&threadStats, nullptr, ThreadStats, nullptr); pthread_create(&threadDump, nullptr, ThreadDumper, nullptr); void *res; pthread_join(threadDump, &res); return 0; } diff --git a/src/seeder/protocol.cpp b/src/seeder/protocol.cpp index 33f6d64d4..009c53fad 100644 --- a/src/seeder/protocol.cpp +++ b/src/seeder/protocol.cpp @@ -1,134 +1,137 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2011 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "protocol.h" #include "netbase.h" #include "util.h" #include #include #ifndef WIN32 #include #endif static const char *ppszTypeName[] = { "ERROR", "tx", "block", }; uint8_t pchMessageStart[4] = {0xe3, 0xe1, 0xf3, 0xe8}; CMessageHeader::CMessageHeader() { memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)); memset(pchCommand, 0, sizeof(pchCommand)); pchCommand[1] = 1; nMessageSize = -1; nChecksum = 0; } CMessageHeader::CMessageHeader(const char *pszCommand, unsigned int nMessageSizeIn) { memcpy(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)); strncpy(pchCommand, pszCommand, COMMAND_SIZE); nMessageSize = nMessageSizeIn; nChecksum = 0; } std::string CMessageHeader::GetCommand() const { if (pchCommand[COMMAND_SIZE - 1] == 0) return std::string(pchCommand, pchCommand + strlen(pchCommand)); else return std::string(pchCommand, pchCommand + COMMAND_SIZE); } bool CMessageHeader::IsValid() const { // Check start string if (memcmp(pchMessageStart, ::pchMessageStart, sizeof(pchMessageStart)) != 0) return false; // Check the command string for errors for (const char *p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++) { if (*p1 == 0) { // Must be all zeros after the first zero for (; p1 < pchCommand + COMMAND_SIZE; p1++) if (*p1 != 0) return false; } else if (*p1 < ' ' || *p1 > 0x7E) return false; } // Message size if (nMessageSize > MAX_SIZE) { printf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > " "MAX_SIZE\n", GetCommand().c_str(), nMessageSize); return false; } return true; } CAddress::CAddress() : CService() { Init(); } CAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn) { Init(); nServices = nServicesIn; } void CAddress::Init() { nServices = NODE_NETWORK | NODE_BITCOIN_CASH; nTime = 100000000; } void CAddress::print() const { printf("CAddress(%s)\n", ToString().c_str()); } CInv::CInv() { type = 0; hash.SetNull(); } -CInv::CInv(int typeIn, const uint256 &hashIn) { +CInv::CInv(uint32_t typeIn, const uint256 &hashIn) { type = typeIn; hash = hashIn; } CInv::CInv(const std::string &strType, const uint256 &hashIn) { - int i; + size_t i; for (i = 1; i < ARRAYLEN(ppszTypeName); i++) { if (strType == ppszTypeName[i]) { type = i; break; } } - if (i == ARRAYLEN(ppszTypeName)) + + if (i == ARRAYLEN(ppszTypeName)) { throw std::out_of_range("CInv::CInv(string, uint256) : unknown type"); + } + hash = hashIn; } bool operator<(const CInv &a, const CInv &b) { return (a.type < b.type || (a.type == b.type && a.hash < b.hash)); } bool CInv::IsKnownType() const { return (type >= 1 && type < ARRAYLEN(ppszTypeName)); } const char *CInv::GetCommand() const { if (!IsKnownType()) throw std::out_of_range("CInv::GetCommand() : unknown type"); return ppszTypeName[type]; } std::string CInv::ToString() const { return "CInv()"; } void CInv::print() const { printf("CInv\n"); } diff --git a/src/seeder/protocol.h b/src/seeder/protocol.h index 29509f7c1..319667d5e 100644 --- a/src/seeder/protocol.h +++ b/src/seeder/protocol.h @@ -1,136 +1,136 @@ // Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2011 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #ifndef __cplusplus #error This header can only be compiled as C++. #endif #ifndef BITCOIN_SEEDER_PROTOCOL_H #define BITCOIN_SEEDER_PROTOCOL_H #include "netbase.h" #include "serialize.h" #include "uint256.h" #include #include extern bool fTestNet; static inline unsigned short GetDefaultPort(const bool testnet = fTestNet) { return testnet ? 18333 : 8333; } // // Message header // (4) message start // (12) command // (4) size // (4) checksum extern uint8_t pchMessageStart[4]; class CMessageHeader { public: CMessageHeader(); CMessageHeader(const char *pszCommand, unsigned int nMessageSizeIn); std::string GetCommand() const; bool IsValid() const; ADD_SERIALIZE_METHODS; template inline void SerializationOp(Stream &s, Operation ser_action) { READWRITE(FLATDATA(pchMessageStart)); READWRITE(FLATDATA(pchCommand)); READWRITE(nMessageSize); if (s.GetVersion() >= 209) { READWRITE(nChecksum); } } // TODO: make private (improves encapsulation) public: enum { COMMAND_SIZE = 12 }; char pchMessageStart[sizeof(::pchMessageStart)]; char pchCommand[COMMAND_SIZE]; unsigned int nMessageSize; unsigned int nChecksum; }; enum ServiceFlags : uint64_t { NODE_NETWORK = (1 << 0), NODE_BLOOM = (1 << 2), NODE_XTHIN = (1 << 4), NODE_BITCOIN_CASH = (1 << 5), }; class CAddress : public CService { public: CAddress(); CAddress(CService ipIn, uint64_t nServicesIn = NODE_NETWORK | NODE_BITCOIN_CASH); void Init(); ADD_SERIALIZE_METHODS; template inline void SerializationOp(Stream &s, Operation ser_action) { int nVersion = s.GetVersion(); CAddress *pthis = const_cast(this); CService *pip = (CService *)pthis; if (ser_action.ForRead()) { pthis->Init(); } if (s.GetType() & SER_DISK) { READWRITE(nVersion); } if ((s.GetType() & SER_DISK) || (nVersion >= 31402 && !(s.GetType() & SER_GETHASH))) { READWRITE(nTime); } READWRITE(nServices); READWRITE(*pip); } void print() const; // TODO: make private (improves encapsulation) public: uint64_t nServices; // disk and network only unsigned int nTime; }; class CInv { public: CInv(); - CInv(int typeIn, const uint256 &hashIn); + CInv(uint32_t typeIn, const uint256 &hashIn); CInv(const std::string &strType, const uint256 &hashIn); ADD_SERIALIZE_METHODS; template inline void SerializationOp(Stream &s, Operation ser_action) { READWRITE(type); READWRITE(hash); } friend bool operator<(const CInv &a, const CInv &b); bool IsKnownType() const; const char *GetCommand() const; std::string ToString() const; void print() const; // TODO: make private (improves encapsulation) public: - int type; + uint32_t type; uint256 hash; }; #endif // __INCLUDED_PROTOCOL_H__