Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Drand Beacon Cache #586

Merged
merged 4 commits into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions blockchain/beacon/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ edition = "2018"
features = ["json"]

[dependencies]
ahash = "0.4"
async-std = { version = "1.6.0", features = ["unstable"] }
snaumov marked this conversation as resolved.
Show resolved Hide resolved
grpc = "0.8"
grpc-protobuf = "0.8"
protobuf = "2.14.0"
Expand Down
41 changes: 29 additions & 12 deletions blockchain/beacon/src/drand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use super::drand_api::api_grpc::PublicClient;
use super::drand_api::common::GroupRequest;
use super::group::Group;

use ahash::AHashMap;
use async_std::sync::RwLock;
use async_trait::async_trait;
use bls_signatures::{PublicKey, Serialize, Signature};
use byteorder::{BigEndian, WriteBytesExt};
Expand Down Expand Up @@ -39,7 +41,7 @@ where
Self: Sized,
{
/// Verify a new beacon entry against the most recent one before it.
fn verify_entry(
async fn verify_entry(
&self,
curr: &BeaconEntry,
prev: &BeaconEntry,
Expand All @@ -59,6 +61,9 @@ pub struct DrandBeacon {
drand_gen_time: u64,
fil_gen_time: u64,
fil_round_time: u64,

/// Keeps track of computed beacon entries.
local_cache: RwLock<AHashMap<u64, BeaconEntry>>,
}

impl DrandBeacon {
Expand Down Expand Up @@ -95,14 +100,15 @@ impl DrandBeacon {
drand_gen_time: group.genesis_time,
fil_round_time: interval,
fil_gen_time: genesis_ts,
local_cache: Default::default(),
})
}
}
/// This struct allows you to talk to a Drand node over GRPC.
/// Use this to source randomness and to verify Drand beacon entries.
#[async_trait]
impl Beacon for DrandBeacon {
fn verify_entry(
async fn verify_entry(
&self,
curr: &BeaconEntry,
prev: &BeaconEntry,
Expand All @@ -123,21 +129,32 @@ impl Beacon for DrandBeacon {
// Signature
let sig = Signature::from_bytes(curr.data())?;
let sig_match = bls_signatures::verify(&sig, &[digest], &[self.pub_key.key()]);
// TODO: Cache this result

// Cache the result
if sig_match && !self.local_cache.read().await.contains_key(&curr.round()) {
self.local_cache
.write()
.await
.insert(curr.round(), curr.clone());
}
Ok(sig_match)
}

async fn entry(&self, round: u64) -> Result<BeaconEntry, Box<dyn error::Error>> {
// TODO: Cache values into a database
let mut req = PublicRandRequest::new();
req.round = round;
let resp = self
.client
.public_rand(grpc::RequestOptions::new(), req)
.drop_metadata()
.await?;
match self.local_cache.read().await.get(&round) {
Some(cached_entry) => Ok(cached_entry.clone()),
None => {
let mut req = PublicRandRequest::new();
req.round = round;
let resp = self
.client
.public_rand(grpc::RequestOptions::new(), req)
.drop_metadata()
.await?;

Ok(BeaconEntry::new(resp.round, resp.signature))
Ok(BeaconEntry::new(resp.round, resp.signature))
}
}
}

fn max_beacon_round_for_epoch(&self, fil_epoch: ChainEpoch) -> u64 {
Expand Down
6 changes: 5 additions & 1 deletion blockchain/beacon/src/mock_beacon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ impl MockBeacon {

#[async_trait]
impl Beacon for MockBeacon {
fn verify_entry(&self, curr: &BeaconEntry, prev: &BeaconEntry) -> Result<bool, Box<dyn Error>> {
async fn verify_entry(
&self,
curr: &BeaconEntry,
prev: &BeaconEntry,
) -> Result<bool, Box<dyn Error>> {
let oe = Self::entry_for_index(prev.round());
Ok(oe.data() == curr.data())
}
Expand Down
4 changes: 2 additions & 2 deletions blockchain/beacon/tests/drand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async fn ask_and_verify_beacon_entry() {

let e2 = beacon.entry(2).await.unwrap();
let e3 = beacon.entry(3).await.unwrap();
assert!(beacon.verify_entry(&e3, &e2).unwrap());
assert!(beacon.verify_entry(&e3, &e2).await.unwrap());
}

#[ignore]
Expand All @@ -40,5 +40,5 @@ async fn ask_and_verify_beacon_entry_fail() {

let e2 = beacon.entry(2).await.unwrap();
let e3 = beacon.entry(3).await.unwrap();
assert!(!beacon.verify_entry(&e2, &e3).unwrap());
assert!(!beacon.verify_entry(&e2, &e3).await.unwrap());
}
30 changes: 15 additions & 15 deletions blockchain/blocks/src/header/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,21 +390,21 @@ impl BlockHeader {
last.round()
)));
}
self.beacon_entries.iter().try_fold(
&prev_entry,
|prev, curr| -> Result<&BeaconEntry, Error> {
if !beacon
.verify_entry(curr, &prev)
.map_err(|e| Error::Validation(e.to_string()))?
{
return Err(Error::Validation(format!(
"beacon entry was invalid: curr:{:?}, prev: {:?}",
curr, prev
)));
}
Ok(curr)
},
)?;

let mut prev = &prev_entry;
for curr in &self.beacon_entries {
if !beacon
.verify_entry(&curr, &prev)
.await
.map_err(|e| Error::Validation(e.to_string()))?
{
return Err(Error::Validation(format!(
"beacon entry was invalid: curr:{:?}, prev: {:?}",
curr, prev
)));
}
prev = &curr;
}
Ok(())
}
}
Expand Down