Move work conversion helpers to test code

This commit is contained in:
Jane Lusby 2020-11-11 14:23:23 -08:00 committed by Deirdre Connolly
parent beede1c03d
commit 1bc833dbcc
4 changed files with 10 additions and 29 deletions

1
Cargo.lock generated
View File

@ -3478,6 +3478,7 @@ dependencies = [
"lazy_static", "lazy_static",
"metrics", "metrics",
"once_cell", "once_cell",
"primitive-types",
"proptest", "proptest",
"serde", "serde",
"sled", "sled",

View File

@ -260,39 +260,12 @@ impl TryFrom<ExpandedDifficulty> for Work {
} }
} }
impl TryFrom<u128> for Work {
type Error = ();
fn try_from(value: u128) -> Result<Self, Self::Error> {
if value == 0 {
Err(())
} else {
Ok(Work(value))
}
}
}
impl From<ExpandedDifficulty> for CompactDifficulty { impl From<ExpandedDifficulty> for CompactDifficulty {
fn from(value: ExpandedDifficulty) -> Self { fn from(value: ExpandedDifficulty) -> Self {
value.to_compact() value.to_compact()
} }
} }
impl From<Work> for CompactDifficulty {
fn from(value: Work) -> Self {
let expanded = ExpandedDifficulty::from(value);
Self::from(expanded)
}
}
impl From<Work> for ExpandedDifficulty {
fn from(value: Work) -> Self {
let work: U256 = value.0.into();
let expanded = (!work + 1) / work;
ExpandedDifficulty(expanded)
}
}
impl ExpandedDifficulty { impl ExpandedDifficulty {
/// Returns the difficulty of the hash. /// Returns the difficulty of the hash.
/// ///

View File

@ -35,3 +35,4 @@ spandoc = "0.2"
tempdir = "0.3.7" tempdir = "0.3.7"
tokio = { version = "0.2.22", features = ["full"] } tokio = { version = "0.2.22", features = ["full"] }
proptest = "0.10.1" proptest = "0.10.1"
primitive-types = "0.7.2"

View File

@ -4,6 +4,7 @@ use zebra_chain::{
block::{self, Block}, block::{self, Block},
transaction::Transaction, transaction::Transaction,
transparent, transparent,
work::difficulty::ExpandedDifficulty,
work::difficulty::Work, work::difficulty::Work,
}; };
@ -42,9 +43,14 @@ impl FakeChainHelper for Arc<Block> {
} }
fn set_work(mut self, work: u128) -> Arc<Block> { fn set_work(mut self, work: u128) -> Arc<Block> {
let work = Work::try_from(work).expect("tests should only pass in valid work values"); use primitive_types::U256;
let work: U256 = work.into();
let expanded = (!work + 1) / work;
let expanded = ExpandedDifficulty::from(expanded);
let block = Arc::make_mut(&mut self); let block = Arc::make_mut(&mut self);
block.header.difficulty_threshold = work.into(); block.header.difficulty_threshold = expanded.into();
self self
} }
} }