solana/src/poh.rs

107 lines
2.3 KiB
Rust
Raw Normal View History

//! The `Poh` module provides an object for generating a Proof of History.
//! It records Hashes items on behalf of its users.
2018-11-16 08:04:46 -08:00
use solana_sdk::hash::{hash, hashv, Hash};
pub struct Poh {
id: Hash,
num_hashes: u64,
pub tick_height: u64,
}
#[derive(Debug)]
pub struct PohEntry {
pub tick_height: u64,
pub num_hashes: u64,
pub id: Hash,
pub mixin: Option<Hash>,
}
impl Poh {
2018-12-13 09:24:38 -08:00
pub fn new(id: Hash, tick_height: u64) -> Self {
Poh {
num_hashes: 0,
2018-12-13 09:24:38 -08:00
id,
tick_height,
}
}
pub fn hash(&mut self) {
self.id = hash(&self.id.as_ref());
self.num_hashes += 1;
}
pub fn record(&mut self, mixin: Hash) -> PohEntry {
self.id = hashv(&[&self.id.as_ref(), &mixin.as_ref()]);
let num_hashes = self.num_hashes + 1;
self.num_hashes = 0;
PohEntry {
tick_height: self.tick_height,
num_hashes,
id: self.id,
mixin: Some(mixin),
}
}
// emissions of Ticks (i.e. PohEntries without a mixin) allows
// validators to parallelize the work of catching up
pub fn tick(&mut self) -> PohEntry {
self.hash();
let num_hashes = self.num_hashes;
self.num_hashes = 0;
self.tick_height += 1;
PohEntry {
tick_height: self.tick_height,
num_hashes,
id: self.id,
mixin: None,
}
}
}
#[cfg(test)]
pub fn verify(initial: Hash, entries: &[PohEntry]) -> bool {
2018-12-13 09:24:38 -08:00
let mut id = initial;
for entry in entries {
assert!(entry.num_hashes != 0);
for _ in 1..entry.num_hashes {
2018-12-13 09:24:38 -08:00
id = hash(&id.as_ref());
}
2018-12-13 09:24:38 -08:00
id = match entry.mixin {
Some(mixin) => hashv(&[&id.as_ref(), &mixin.as_ref()]),
None => hash(&id.as_ref()),
};
2018-12-13 09:24:38 -08:00
if id != entry.id {
return false;
}
}
2018-09-23 14:38:17 -07:00
true
}
#[cfg(test)]
mod tests {
2018-12-07 19:16:27 -08:00
use crate::poh::{self, PohEntry};
2018-11-16 08:04:46 -08:00
use solana_sdk::hash::Hash;
#[test]
#[should_panic]
fn test_poh_verify_assert() {
poh::verify(
Hash::default(),
&[PohEntry {
tick_height: 0,
num_hashes: 0,
id: Hash::default(),
mixin: None,
}],
);
}
}