From a7980740884e2383ba30436e7139f14d81a8ddf7 Mon Sep 17 00:00:00 2001 From: Jane Lusby Date: Wed, 11 Nov 2020 14:29:14 -0800 Subject: [PATCH] split conversion into a fn --- zebra-state/src/tests.rs | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/zebra-state/src/tests.rs b/zebra-state/src/tests.rs index d352fbdb9..f3067cf3b 100644 --- a/zebra-state/src/tests.rs +++ b/zebra-state/src/tests.rs @@ -1,11 +1,11 @@ -use std::{convert::TryFrom, mem, sync::Arc}; +use std::{mem, sync::Arc}; +use primitive_types::U256; use zebra_chain::{ block::{self, Block}, transaction::Transaction, transparent, work::difficulty::ExpandedDifficulty, - work::difficulty::Work, }; use super::*; @@ -43,18 +43,8 @@ impl FakeChainHelper for Arc { } fn set_work(mut self, work: u128) -> Arc { - use primitive_types::U256; let work: U256 = work.into(); - - // Work is calculated from expanded difficulty with the equation `work = 2^256 / (expanded + 1)` - // By balancing the equation we get `expanded = (2^256 / work) - 1` - // `2^256` is too large to represent, so we instead use the following equivalent equations - // `expanded = (2^256 / work) - (work / work)` - // `expanded = (2^256 - work) / work` - // `expanded = ((2^256 - 1) - work + 1) / work` - // `(2^256 - 1 - work)` is equivalent to `!work` when work is a U256 - let expanded = (!work + 1) / work; - let expanded = ExpandedDifficulty::from(expanded); + let expanded = work_to_expanded(work); let block = Arc::make_mut(&mut self); block.header.difficulty_threshold = expanded.into(); @@ -62,6 +52,18 @@ impl FakeChainHelper for Arc { } } +fn work_to_expanded(work: U256) -> ExpandedDifficulty { + // Work is calculated from expanded difficulty with the equation `work = 2^256 / (expanded + 1)` + // By balancing the equation we get `expanded = (2^256 / work) - 1` + // `2^256` is too large to represent, so we instead use the following equivalent equations + // `expanded = (2^256 / work) - (work / work)` + // `expanded = (2^256 - work) / work` + // `expanded = ((2^256 - 1) - work + 1) / work` + // `(2^256 - 1 - work)` is equivalent to `!work` when work is a U256 + let expanded = (!work + 1) / work; + ExpandedDifficulty::from(expanded) +} + /// Block heights, and the expected minimum block locator height static BLOCK_LOCATOR_CASES: &[(u32, u32)] = &[ (0, 0),