From 39293029c5f5aecdbae89d20308630f627f0144e Mon Sep 17 00:00:00 2001 From: DcruBro Date: Fri, 29 May 2026 13:51:34 +0200 Subject: [PATCH] recompute state bug fixed --- include/block/chain.h | 4 ++++ src/block/chain.c | 2 +- src/main.c | 5 +++++ 3 files changed, 10 insertions(+), 1 deletion(-) diff --git a/include/block/chain.h b/include/block/chain.h index caf9b89..35f9d60 100644 --- a/include/block/chain.h +++ b/include/block/chain.h @@ -28,6 +28,10 @@ void Chain_Wipe(blockchain_t* chain); // Returns true on success. bool Chain_RollbackToHeight(blockchain_t* chain, size_t height); +// Recompute `currentSupply` and `currentReward` from the in-memory chain blocks. +// Returns true on success and updates runtime state globals. +bool Chain_RecomputeRuntimeState(blockchain_t* chain); + // Retrieve a deep copy of the block at `index`. Caller must free with `Block_Destroy`. bool Chain_GetBlockCopy(blockchain_t* chain, size_t index, block_t** outCopy); diff --git a/src/block/chain.c b/src/block/chain.c index 539f926..408bbdc 100644 --- a/src/block/chain.c +++ b/src/block/chain.c @@ -97,7 +97,7 @@ static bool DebitAddress(const uint8_t address[32], const uint256_t* amount) { return BalanceSheet_Insert(entry) >= 0; } -static bool Chain_RecomputeRuntimeState(blockchain_t* chain) { +bool Chain_RecomputeRuntimeState(blockchain_t* chain) { if (!chain) { return false; } diff --git a/src/main.c b/src/main.c index 6cc3b5b..b13dde4 100644 --- a/src/main.c +++ b/src/main.c @@ -698,6 +698,11 @@ int main(int argc, char* argv[]) { uint8_t lastSavedHash[32] = {0}; if (!Chain_LoadFromFile(chain, chainDataDir, ¤tSupply, &difficultyTarget, ¤tReward, lastSavedHash, false)) { printf("No existing chain loaded from %s\n", chainDataDir); + } else { + // Recompute runtime supply/reward from loaded blocks to avoid trusting stale meta values. + if (!Chain_RecomputeRuntimeState(chain)) { + fprintf(stderr, "Failed to recompute runtime state from loaded chain\n"); + } } if (!BalanceSheet_LoadFromFile(chainDataDir)) {