lighthouse-pulse/lighthouse/state/common/delegation/block_hash.rs

63 lines
1.7 KiB
Rust
Raw Normal View History

2018-09-19 06:27:19 +00:00
use super::utils::errors::ParameterError;
use super::utils::types::Hash256;
/*
2018-09-25 02:32:51 +00:00
* Work-in-progress function: not ready for review.
*/
2018-09-19 06:27:19 +00:00
pub fn get_block_hash(
2018-09-26 01:53:15 +00:00
active_state_recent_block_hashes: &[Hash256],
current_block_slot: u64,
slot: u64,
cycle_length: u64, // convert from standard u8
2018-09-19 06:27:19 +00:00
) -> Result<Hash256, ParameterError> {
// active_state must have at 2*cycle_length hashes
assert_error!(
active_state_recent_block_hashes.len() as u64 == cycle_length * 2,
ParameterError::InvalidInput(String::from(
"active state has incorrect number of block hashes"
))
);
2018-09-26 01:53:15 +00:00
let state_start_slot = (current_block_slot)
2018-09-19 06:27:19 +00:00
.checked_sub(cycle_length * 2)
.unwrap_or(0);
assert_error!(
2018-09-26 01:53:15 +00:00
(state_start_slot <= slot) && (slot < current_block_slot),
2018-09-19 06:27:19 +00:00
ParameterError::InvalidInput(String::from("incorrect slot number"))
);
2018-09-26 01:53:15 +00:00
let index = 2 * cycle_length + slot - current_block_slot; // should always be positive
2018-09-19 06:27:19 +00:00
Ok(active_state_recent_block_hashes[index as usize])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_block_hash() {
let block_slot: u64 = 10;
let slot: u64 = 3;
let cycle_length: u64 = 8;
let mut block_hashes: Vec<Hash256> = Vec::new();
for _i in 0..2 * cycle_length {
block_hashes.push(Hash256::random());
}
2018-09-26 01:53:15 +00:00
let result = get_block_hash(
&block_hashes,
block_slot,
slot,
cycle_length)
.unwrap();
2018-09-19 06:27:19 +00:00
assert_eq!(
result,
block_hashes[(2 * cycle_length + slot - block_slot) as usize]
);
}
}