From 5f60cb821ac55c87f59087329aba168515eb4042 Mon Sep 17 00:00:00 2001 From: Mononaut Date: Sun, 26 Mar 2023 07:27:11 +0900 Subject: [PATCH] Fix difficulty adjustment start-of-epoch edge cases --- backend/src/api/difficulty-adjustment.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/backend/src/api/difficulty-adjustment.ts b/backend/src/api/difficulty-adjustment.ts index c4e2abf31..0ddf2b540 100644 --- a/backend/src/api/difficulty-adjustment.ts +++ b/backend/src/api/difficulty-adjustment.ts @@ -29,7 +29,7 @@ export function calcDifficultyAdjustment( const BLOCK_SECONDS_TARGET = 600; // Bitcoin mainnet const TESTNET_MAX_BLOCK_SECONDS = 1200; // Bitcoin testnet - const diffSeconds = nowSeconds - DATime; + const diffSeconds = Math.max(0, nowSeconds - DATime); const blocksInEpoch = (blockHeight >= 0) ? blockHeight % EPOCH_BLOCK_LENGTH : 0; const progressPercent = (blockHeight >= 0) ? blocksInEpoch / EPOCH_BLOCK_LENGTH * 100 : 100; const remainingBlocks = EPOCH_BLOCK_LENGTH - blocksInEpoch; @@ -37,7 +37,7 @@ export function calcDifficultyAdjustment( const expectedBlocks = diffSeconds / BLOCK_SECONDS_TARGET; let difficultyChange = 0; - let timeAvgSecs = diffSeconds / blocksInEpoch; + let timeAvgSecs = blocksInEpoch ? diffSeconds / blocksInEpoch : BLOCK_SECONDS_TARGET; // Only calculate the estimate once we have 7.2% of blocks in current epoch if (blocksInEpoch >= ESTIMATE_LAG_BLOCKS) { difficultyChange = (BLOCK_SECONDS_TARGET / timeAvgSecs - 1) * 100;