Skip to content

Commit

Permalink
fix: avoid potential divide-by-zero in H/s stats calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
kwvg committed Dec 8, 2024
1 parent 7c00c86 commit b39c6b9
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions src/init.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -848,20 +848,23 @@ static void PeriodicStats(NodeContext& node)
LogPrintf("%s: GetUTXOStats failed\n", __func__);
}

// short version of GetNetworkHashPS(120, -1);
CBlockIndex *tip = chainman.ActiveChain().Tip();
CBlockIndex *pindex = tip;
int64_t minTime = pindex->GetBlockTime();
int64_t maxTime = minTime;
for (int i = 0; i < 120 && pindex->pprev != nullptr; i++) {
pindex = pindex->pprev;
int64_t time = pindex->GetBlockTime();
minTime = std::min(time, minTime);
maxTime = std::max(time, maxTime);
}
arith_uint256 workDiff = tip->nChainWork - pindex->nChainWork;
int64_t timeDiff = maxTime - minTime;
double nNetworkHashPS = workDiff.getdouble() / timeDiff;
double nNetworkHashPS = [&]() {
// Short version of GetNetworkHashPS(120, -1);
CBlockIndex *pindex = tip;
int64_t minTime = pindex->GetBlockTime();
int64_t maxTime = minTime;
for (int i = 0; i < 120 && pindex->pprev != nullptr; i++) {
pindex = pindex->pprev;
int64_t time = pindex->GetBlockTime();
minTime = std::min(time, minTime);
maxTime = std::max(time, maxTime);
}
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.terahashesPerSecond", nNetworkHashPS / 1e12);
Expand Down

0 comments on commit b39c6b9

Please sign in to comment.