split conversion into a fn

This commit is contained in:
Jane Lusby 2020-11-11 14:29:14 -08:00 committed by Deirdre Connolly
parent ae843d856f
commit a798074088
1 changed files with 15 additions and 13 deletions

View File

@ -1,11 +1,11 @@
use std::{convert::TryFrom, mem, sync::Arc}; use std::{mem, sync::Arc};
use primitive_types::U256;
use zebra_chain::{ use zebra_chain::{
block::{self, Block}, block::{self, Block},
transaction::Transaction, transaction::Transaction,
transparent, transparent,
work::difficulty::ExpandedDifficulty, work::difficulty::ExpandedDifficulty,
work::difficulty::Work,
}; };
use super::*; use super::*;
@ -43,9 +43,16 @@ impl FakeChainHelper for Arc<Block> {
} }
fn set_work(mut self, work: u128) -> Arc<Block> { fn set_work(mut self, work: u128) -> Arc<Block> {
use primitive_types::U256;
let work: U256 = work.into(); let work: U256 = work.into();
let expanded = work_to_expanded(work);
let block = Arc::make_mut(&mut self);
block.header.difficulty_threshold = expanded.into();
self
}
}
fn work_to_expanded(work: U256) -> ExpandedDifficulty {
// Work is calculated from expanded difficulty with the equation `work = 2^256 / (expanded + 1)` // 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` // 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 // `2^256` is too large to represent, so we instead use the following equivalent equations
@ -54,12 +61,7 @@ impl FakeChainHelper for Arc<Block> {
// `expanded = ((2^256 - 1) - work + 1) / work` // `expanded = ((2^256 - 1) - work + 1) / work`
// `(2^256 - 1 - work)` is equivalent to `!work` when work is a U256 // `(2^256 - 1 - work)` is equivalent to `!work` when work is a U256
let expanded = (!work + 1) / work; let expanded = (!work + 1) / work;
let expanded = ExpandedDifficulty::from(expanded); ExpandedDifficulty::from(expanded)
let block = Arc::make_mut(&mut self);
block.header.difficulty_threshold = expanded.into();
self
}
} }
/// Block heights, and the expected minimum block locator height /// Block heights, and the expected minimum block locator height