2022-10-16 03:29:55 -04:00
|
|
|
use core::{hash::Hash, fmt::Debug};
|
2022-10-16 07:30:11 -04:00
|
|
|
use std::sync::Arc;
|
2022-10-16 03:29:55 -04:00
|
|
|
|
2022-10-16 07:30:11 -04:00
|
|
|
use crate::Message;
|
|
|
|
|
|
|
|
|
|
pub trait ValidatorId: Send + Sync + Clone + Copy + PartialEq + Eq + Hash + Debug {}
|
|
|
|
|
impl<V: Send + Sync + Clone + Copy + PartialEq + Eq + Hash + Debug> ValidatorId for V {}
|
2022-10-16 03:29:55 -04:00
|
|
|
|
2022-10-16 03:55:39 -04:00
|
|
|
// Type aliases which are distinct according to the type system
|
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
|
|
|
|
pub struct BlockNumber(pub u32);
|
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
|
|
|
|
|
pub struct Round(pub u16);
|
|
|
|
|
|
2022-10-16 03:29:55 -04:00
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
|
|
|
pub enum BlockError {
|
|
|
|
|
// Invalid behavior entirely
|
|
|
|
|
Fatal,
|
|
|
|
|
// Potentially valid behavior dependent on unsynchronized state
|
|
|
|
|
Temporal,
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-16 07:30:11 -04:00
|
|
|
pub trait Block: Send + Sync + Clone + PartialEq + Debug {
|
|
|
|
|
type Id: Send + Sync + Copy + Clone + PartialEq + Debug;
|
2022-10-16 03:29:55 -04:00
|
|
|
|
|
|
|
|
fn id(&self) -> Self::Id;
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-16 07:30:11 -04:00
|
|
|
pub trait Weights: Send + Sync {
|
2022-10-16 03:55:39 -04:00
|
|
|
type ValidatorId: ValidatorId;
|
|
|
|
|
|
2022-10-16 03:29:55 -04:00
|
|
|
fn total_weight(&self) -> u64;
|
2022-10-16 03:55:39 -04:00
|
|
|
fn weight(&self, validator: Self::ValidatorId) -> u64;
|
2022-10-16 03:29:55 -04:00
|
|
|
fn threshold(&self) -> u64 {
|
|
|
|
|
((self.total_weight() * 2) / 3) + 1
|
|
|
|
|
}
|
2022-10-16 07:30:11 -04:00
|
|
|
fn fault_thresold(&self) -> u64 {
|
|
|
|
|
(self.total_weight() - self.threshold()) + 1
|
|
|
|
|
}
|
2022-10-16 03:29:55 -04:00
|
|
|
|
2022-10-16 07:30:11 -04:00
|
|
|
/// Weighted round robin function.
|
2022-10-16 03:55:39 -04:00
|
|
|
fn proposer(&self, number: BlockNumber, round: Round) -> Self::ValidatorId;
|
2022-10-16 07:30:11 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[async_trait::async_trait]
|
|
|
|
|
pub trait Network: Send + Sync {
|
|
|
|
|
type ValidatorId: ValidatorId;
|
|
|
|
|
type Weights: Weights<ValidatorId = Self::ValidatorId>;
|
|
|
|
|
type Block: Block;
|
|
|
|
|
|
|
|
|
|
fn weights(&self) -> Arc<Self::Weights>;
|
|
|
|
|
|
|
|
|
|
async fn broadcast(&mut self, msg: Message<Self::ValidatorId, Self::Block>);
|
|
|
|
|
|
|
|
|
|
// TODO: Should this take a verifiable reason?
|
|
|
|
|
async fn slash(&mut self, validator: Self::ValidatorId);
|
2022-10-16 03:55:39 -04:00
|
|
|
|
2022-10-16 07:30:11 -04:00
|
|
|
fn validate(&mut self, block: &Self::Block) -> Result<(), BlockError>;
|
|
|
|
|
// Add a block and return the proposal for the next one
|
|
|
|
|
fn add_block(&mut self, block: Self::Block) -> Self::Block;
|
2022-10-16 03:29:55 -04:00
|
|
|
}
|