Merge pull request #286 from ethcore/difficulty

Chain current difficulty calculation
This commit is contained in:
Nikolay Volf 2016-12-10 13:24:59 +01:00 committed by GitHub
commit cfc90b79aa
3 changed files with 45 additions and 1 deletions

View File

@ -307,7 +307,7 @@ impl Storage {
self.read_meta_u32(KEY_BEST_BLOCK_NUMBER)
}
fn _best_hash(&self) -> Option<H256> {
fn best_hash(&self) -> Option<H256> {
self.get(COL_META, KEY_BEST_BLOCK_HASH).map(|val| H256::from(&**val))
}
@ -409,6 +409,14 @@ impl Storage {
best_number -= 1;
result.push(next);
}
}
pub fn difficulty(&self) -> f64 {
self.best_hash()
.and_then(|h| self.block_header_by_hash(&h))
.map(|header| header.bits.to_f64())
.unwrap_or(1.0f64)
}
}
@ -722,6 +730,7 @@ mod tests {
use chain::Block;
use super::super::{BlockRef, BlockLocation};
use test_data;
use primitives::Compact;
#[test]
fn open_store() {
@ -1282,6 +1291,27 @@ mod tests {
assert_eq!(inserted_chain, BlockInsertedChain::Main, "h1 should become main chain");
}
#[test]
fn difficulty() {
let path = RandomTempPath::create_dir();
let store = Storage::new(path.as_path()).unwrap();
let genesis = test_data::genesis();
store.insert_block(&genesis)
.expect("Genesis should be inserted with no issues");
assert_eq!(1f64, store.difficulty(), "There should be minimum 1 difficulty for just the genesis block");
let block = test_data::block_builder()
.header().parent(genesis.hash()).bits(Compact::new(0x1b0404cb)).build()
.transaction().coinbase().build()
.build();
store.insert_block(&block)
.expect("Nest block with just nbits should be inserted with no issues");
assert_eq!(16307.420938523994f64, store.difficulty(), "There should be minimum updated difficulty for new best block");
}
#[test]
fn chain_for_side() {

View File

@ -76,6 +76,14 @@ impl Compact {
assert!(size < 256);
Compact(compact | (size << 24) as u32)
}
pub fn to_f64(&self) -> f64 {
let max_body = f64::from(0x00ffff).ln();
let scaland = f64::from(256).ln();
let ln1 = f64::from(self.0 & 0x00ffffff).ln();
let s1 = scaland * f64::from(0x1d - ((self.0 & 0xff000000) >> 24));
(max_body - ln1 + s1).exp()
}
}
#[cfg(test)]
@ -113,6 +121,11 @@ mod tests {
let compact = Compact::new(0x05009234);
let compact2 = Compact::from_u256(compact.to_u256().unwrap());
assert_eq!(compact, compact2);
}
#[test]
fn difficulty() {
let nbits = Compact::new(0x1b0404cb);
assert_eq!(nbits.to_f64(), 16307.420938523994f64);
}
}

View File

@ -13,3 +13,4 @@ pub use rustc_serialize::hex;
pub use uint::U256;
pub use hash::{H160, H256};
pub use bytes::Bytes;
pub use compact::Compact;