From 318fecc029f9867dccfaacedf56b7cb87f3164eb Mon Sep 17 00:00:00 2001 From: DcruBro Date: Sun, 3 May 2026 13:58:06 +0200 Subject: [PATCH] millisecond timestamps --- include/utils.h | 10 ++++++++++ src/block/chain.c | 3 ++- src/main.c | 2 +- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/include/utils.h b/include/utils.h index dbd4eb2..1a37466 100644 --- a/include/utils.h +++ b/include/utils.h @@ -8,6 +8,7 @@ #include #include #include +#include typedef struct { uint8_t bytes[32]; @@ -26,6 +27,15 @@ static inline int eq_key32(key32_t a, key32_t b) { return memcmp(a.bytes, b.bytes, 32) == 0; } +static inline uint64_t get_current_time_ms(void) { + struct timespec spec; + if (clock_gettime(CLOCK_REALTIME, &spec) == -1) { + return 0; // Handle error + } + // Convert seconds to milliseconds and add nanoseconds converted to milliseconds + return (spec.tv_sec * 1000) + (spec.tv_nsec / 1000000); +} + static inline void AddressToHexString(const uint8_t address[32], char out[65]) { if (!address || !out) { return; diff --git a/src/block/chain.c b/src/block/chain.c index 036317d..f1da979 100644 --- a/src/block/chain.c +++ b/src/block/chain.c @@ -804,6 +804,7 @@ uint32_t Chain_ComputeNextTarget(blockchain_t* chain, uint32_t currentTarget) { // Retarget uses whole-window span. Per-block average is implicit: // (actualTime / interval) / targetBlockTime == actualTime / targetTime. + // Block timestamps are stored in milliseconds, so the target window must be ms too. uint64_t actualTime = 0; if (lastBlock->header.timestamp > adjustmentBlock->header.timestamp) { actualTime = lastBlock->header.timestamp - adjustmentBlock->header.timestamp; @@ -812,7 +813,7 @@ uint32_t Chain_ComputeNextTarget(blockchain_t* chain, uint32_t currentTarget) { return currentTarget; // Invalid/non-increasing time window; keep current target } - const uint64_t targetTime = (uint64_t)TARGET_BLOCK_TIME * (uint64_t)DIFFICULTY_ADJUSTMENT_INTERVAL; + const uint64_t targetTime = (uint64_t)TARGET_BLOCK_TIME * 1000ULL * (uint64_t)DIFFICULTY_ADJUSTMENT_INTERVAL; double timeRatio = (double)actualTime / (double)targetTime; // Clamp per-epoch target movement: at most x2 easier or x2 harder. TODO: Check if the clamp should be more aggressive or looser diff --git a/src/main.c b/src/main.c index f72f9fd..acf840d 100644 --- a/src/main.c +++ b/src/main.c @@ -85,7 +85,7 @@ static block_t* BuildNextBlock(blockchain_t* chain, uint32_t difficultyTarget) { } else { memset(block->header.prevHash, 0, sizeof(block->header.prevHash)); } - block->header.timestamp = (uint64_t)time(NULL); + block->header.timestamp = (uint64_t)get_current_time_ms(); block->header.difficultyTarget = difficultyTarget; block->header.nonce = 0;