From 9b7f778f60053054fdc9d7531ee4a27f543e82e3 Mon Sep 17 00:00:00 2001 From: Boog900 <54e72d8a-345f-4599-bd90-c6b9bc7d0ec5@aleeas.com> Date: Tue, 24 Oct 2023 15:34:41 +0100 Subject: [PATCH] fix getting the median timestamp we were excluding the genesis block --- consensus/src/context/difficulty.rs | 22 ++++++++++++++++------ consensus/src/context/weight.rs | 2 +- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/consensus/src/context/difficulty.rs b/consensus/src/context/difficulty.rs index 8ed8db51..d3d90d1f 100644 --- a/consensus/src/context/difficulty.rs +++ b/consensus/src/context/difficulty.rs @@ -166,17 +166,27 @@ impl DifficultyCache { (windowed_work * hf.block_time().as_secs() as u128 + time_span - 1) / time_span } - /// Returns the median timestamp over the last `numb_blocks`. + /// Returns the median timestamp over the last `numb_blocks`, including the genesis block if the block height is low enough. /// /// Will return [`None`] if there aren't enough blocks. pub fn median_timestamp(&self, numb_blocks: usize) -> Option { - Some(median( - &self - .timestamps + let timestamps = if self.last_accounted_height + 1 == u64::try_from(numb_blocks).unwrap() { + // if the chain height is equal to `numb_blocks` add the genesis block. + // otherwise if the chain height is less than `numb_blocks` None is returned + // and if its more than it would be excluded from calculations. + let mut timestamps = self.timestamps.clone(); + // all genesis blocks have a timestamp of 0. + // https://cuprate.github.io/monero-book/consensus_rules/genesis_block.html + timestamps.push_front(0); + timestamps.into() + } else { + self.timestamps .range(self.timestamps.len().checked_sub(numb_blocks)?..) .copied() - .collect::>(), - )) + .collect::>() + }; + + Some(median(×tamps)) } /// Returns the cumulative difficulty of the chain. diff --git a/consensus/src/context/weight.rs b/consensus/src/context/weight.rs index fe5b0a63..b2421003 100644 --- a/consensus/src/context/weight.rs +++ b/consensus/src/context/weight.rs @@ -197,7 +197,7 @@ impl BlockWeightsCache { self.short_term_block_weights.clone().into(); sorted_short_term_weights.par_sort_unstable(); - /// TODO: this sometimes takes a while (>5s) + // TODO: this sometimes takes a while (>5s) let mut sorted_long_term_weights: Vec = self.long_term_weights.clone().into(); sorted_long_term_weights.par_sort_unstable();