fix: avoid potential divide-by-zero in H/s stats calculation

This commit is contained in:
Kittywhiskers Van Gogh 2024-12-08 10:14:46 +00:00
parent 7c00c868d8
commit b39c6b9909
No known key found for this signature in database
GPG Key ID: 30CD0C065E5C4AAD

View File

@ -848,20 +848,23 @@ static void PeriodicStats(NodeContext& node)
LogPrintf("%s: GetUTXOStats failed\n", __func__); LogPrintf("%s: GetUTXOStats failed\n", __func__);
} }
// short version of GetNetworkHashPS(120, -1);
CBlockIndex *tip = chainman.ActiveChain().Tip(); CBlockIndex *tip = chainman.ActiveChain().Tip();
CBlockIndex *pindex = tip; double nNetworkHashPS = [&]() {
int64_t minTime = pindex->GetBlockTime(); // Short version of GetNetworkHashPS(120, -1);
int64_t maxTime = minTime; CBlockIndex *pindex = tip;
for (int i = 0; i < 120 && pindex->pprev != nullptr; i++) { int64_t minTime = pindex->GetBlockTime();
pindex = pindex->pprev; int64_t maxTime = minTime;
int64_t time = pindex->GetBlockTime(); for (int i = 0; i < 120 && pindex->pprev != nullptr; i++) {
minTime = std::min(time, minTime); pindex = pindex->pprev;
maxTime = std::max(time, maxTime); int64_t time = pindex->GetBlockTime();
} minTime = std::min(time, minTime);
arith_uint256 workDiff = tip->nChainWork - pindex->nChainWork; maxTime = std::max(time, maxTime);
int64_t timeDiff = maxTime - minTime; }
double nNetworkHashPS = workDiff.getdouble() / timeDiff; if (minTime == maxTime) return 0.0;
arith_uint256 workDiff = tip->nChainWork - pindex->nChainWork;
int64_t timeDiff = maxTime - minTime;
return workDiff.getdouble() / timeDiff;
}();
::g_stats_client->gaugeDouble("network.hashesPerSecond", nNetworkHashPS); ::g_stats_client->gaugeDouble("network.hashesPerSecond", nNetworkHashPS);
::g_stats_client->gaugeDouble("network.terahashesPerSecond", nNetworkHashPS / 1e12); ::g_stats_client->gaugeDouble("network.terahashesPerSecond", nNetworkHashPS / 1e12);