diff --git a/base_layer/core/src/base_node/proto/chain_metadata.rs b/base_layer/core/src/base_node/proto/chain_metadata.rs index f3506967d6..702141d288 100644 --- a/base_layer/core/src/base_node/proto/chain_metadata.rs +++ b/base_layer/core/src/base_node/proto/chain_metadata.rs @@ -27,14 +27,15 @@ use tari_common_types::{chain_metadata::ChainMetadata, types::FixedHash}; use crate::proto::base_node as proto; +const ACCUMULATED_DIFFICULTY_BYTE_SIZE: usize = 32; impl TryFrom for ChainMetadata { type Error = String; fn try_from(metadata: proto::ChainMetadata) -> Result { - if metadata.accumulated_difficulty.len() != 32 { + if metadata.accumulated_difficulty.len() != ACCUMULATED_DIFFICULTY_BYTE_SIZE { return Err(format!( "Invalid accumulated difficulty byte length. {} was expected but the actual length was {}", - 32, + ACCUMULATED_DIFFICULTY_BYTE_SIZE, metadata.accumulated_difficulty.len() )); } @@ -68,7 +69,7 @@ impl TryFrom for ChainMetadata { impl From for proto::ChainMetadata { fn from(metadata: ChainMetadata) -> Self { - let mut accumulated_difficulty = [0u8; 32]; + let mut accumulated_difficulty = [0u8; ACCUMULATED_DIFFICULTY_BYTE_SIZE]; metadata .accumulated_difficulty() .to_big_endian(&mut accumulated_difficulty); diff --git a/base_layer/core/src/proof_of_work/accumulated_difficulty.rs b/base_layer/core/src/proof_of_work/accumulated_difficulty.rs index 3399853e32..cd5646590b 100644 --- a/base_layer/core/src/proof_of_work/accumulated_difficulty.rs +++ b/base_layer/core/src/proof_of_work/accumulated_difficulty.rs @@ -56,11 +56,7 @@ impl AccumulatedDifficulty { } pub fn checked_add_difficulty(&self, d: Difficulty) -> Option { - let difficulty = d.as_u64() as u128; - if u128::MAX - difficulty < self.0 { - return None; - } - Some(AccumulatedDifficulty(self.0 + difficulty)) + self.0.checked_add(u128::from(d.as_u64())).map(AccumulatedDifficulty) } pub fn to_be_bytes(&self) -> Vec {