Files
serai/substrate/tendermint/src/lib.rs

355 lines
9.7 KiB
Rust
Raw Normal View History

2022-10-16 07:30:11 -04:00
use std::{sync::Arc, time::Instant, collections::HashMap};
use tokio::{
task::{JoinHandle, yield_now},
sync::{
RwLock,
mpsc::{self, error::TryRecvError},
},
};
pub mod ext;
use ext::*;
2022-10-02 23:23:58 -04:00
mod message_log;
2022-10-16 07:30:11 -04:00
use message_log::MessageLog;
2022-10-12 21:36:40 -04:00
2022-10-02 23:23:58 -04:00
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum Step {
Propose,
Prevote,
Precommit,
}
2022-10-16 07:30:11 -04:00
#[derive(Clone, PartialEq, Debug)]
enum Data<B: Block> {
2022-10-16 07:30:11 -04:00
Proposal(Option<Round>, B),
Prevote(Option<B::Id>),
Precommit(Option<B::Id>),
2022-10-02 23:23:58 -04:00
}
impl<B: Block> Data<B> {
2022-10-02 23:23:58 -04:00
fn step(&self) -> Step {
match self {
Data::Proposal(..) => Step::Propose,
Data::Prevote(..) => Step::Prevote,
Data::Precommit(..) => Step::Precommit,
}
}
}
2022-10-16 07:30:11 -04:00
#[derive(Clone, PartialEq, Debug)]
pub struct Message<V: ValidatorId, B: Block> {
sender: V,
2022-10-02 23:23:58 -04:00
number: BlockNumber,
round: Round,
2022-10-02 23:23:58 -04:00
data: Data<B>,
2022-10-02 23:23:58 -04:00
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
2022-10-16 07:30:11 -04:00
pub enum TendermintError<V: ValidatorId> {
Malicious(V),
2022-10-02 23:23:58 -04:00
Temporal,
}
2022-10-16 07:30:11 -04:00
pub struct TendermintMachine<N: Network> {
network: Arc<RwLock<N>>,
weights: Arc<N::Weights>,
proposer: N::ValidatorId,
2022-10-02 23:23:58 -04:00
2022-10-16 07:30:11 -04:00
number: BlockNumber,
personal_proposal: N::Block,
2022-10-02 23:23:58 -04:00
2022-10-16 07:30:11 -04:00
log: MessageLog<N>,
round: Round,
2022-10-02 23:23:58 -04:00
step: Step,
2022-10-12 21:36:40 -04:00
2022-10-16 07:30:11 -04:00
locked: Option<(Round, N::Block)>,
valid: Option<(Round, N::Block)>,
timeouts: HashMap<Step, Instant>,
2022-10-12 21:36:40 -04:00
}
2022-10-16 07:30:11 -04:00
pub struct TendermintHandle<N: Network> {
// Messages received
pub messages: mpsc::Sender<Message<N::ValidatorId, N::Block>>,
// Async task executing the machine
pub handle: JoinHandle<()>,
2022-10-02 23:23:58 -04:00
}
2022-10-16 07:30:11 -04:00
impl<N: Network + 'static> TendermintMachine<N> {
fn timeout(&self, step: Step) -> Instant {
todo!()
}
#[async_recursion::async_recursion]
async fn broadcast(&mut self, data: Data<N::Block>) -> Option<N::Block> {
let msg = Message { sender: self.proposer, number: self.number, round: self.round, data };
2022-10-16 07:30:11 -04:00
let res = self.message(msg.clone()).await.unwrap();
self.network.write().await.broadcast(msg).await;
2022-10-02 23:23:58 -04:00
res
}
// 14-21
2022-10-16 07:30:11 -04:00
async fn round_propose(&mut self) {
if self.weights.proposer(self.number, self.round) == self.proposer {
let (round, block) = if let Some((round, block)) = &self.valid {
(Some(*round), block.clone())
2022-10-02 23:23:58 -04:00
} else {
2022-10-16 07:30:11 -04:00
(None, self.personal_proposal.clone())
2022-10-02 23:23:58 -04:00
};
2022-10-16 07:30:11 -04:00
debug_assert!(self.broadcast(Data::Proposal(round, block)).await.is_none());
2022-10-02 23:23:58 -04:00
} else {
2022-10-16 07:30:11 -04:00
self.timeouts.insert(Step::Propose, self.timeout(Step::Propose));
2022-10-02 23:23:58 -04:00
}
}
// 11-13
2022-10-16 07:30:11 -04:00
async fn round(&mut self, round: Round) {
2022-10-02 23:23:58 -04:00
self.round = round;
self.step = Step::Propose;
2022-10-16 07:30:11 -04:00
self.round_propose().await;
2022-10-02 23:23:58 -04:00
}
// 1-9
2022-10-16 07:30:11 -04:00
async fn reset(&mut self, proposal: N::Block) {
self.number.0 += 1;
self.personal_proposal = proposal;
2022-10-02 23:23:58 -04:00
2022-10-16 07:30:11 -04:00
self.log = MessageLog::new(self.network.read().await.weights());
2022-10-02 23:23:58 -04:00
self.locked = None;
self.valid = None;
2022-10-16 07:30:11 -04:00
self.timeouts = HashMap::new();
self.round(Round(0)).await;
2022-10-02 23:23:58 -04:00
}
// 10
2022-10-16 07:30:11 -04:00
pub fn new(
network: N,
proposer: N::ValidatorId,
number: BlockNumber,
proposal: N::Block,
) -> TendermintHandle<N> {
2022-10-12 21:36:40 -04:00
let (msg_send, mut msg_recv) = mpsc::channel(100); // Backlog to accept. Currently arbitrary
TendermintHandle {
messages: msg_send,
2022-10-16 07:30:11 -04:00
handle: tokio::spawn(async move {
let weights = network.weights();
let network = Arc::new(RwLock::new(network));
let mut machine = TendermintMachine {
network,
weights: weights.clone(),
2022-10-12 21:36:40 -04:00
proposer,
number,
2022-10-16 07:30:11 -04:00
personal_proposal: proposal,
2022-10-12 21:36:40 -04:00
2022-10-16 07:30:11 -04:00
log: MessageLog::new(weights),
round: Round(0),
step: Step::Propose,
2022-10-12 21:36:40 -04:00
locked: None,
valid: None,
2022-10-16 07:30:11 -04:00
timeouts: HashMap::new(),
2022-10-12 21:36:40 -04:00
};
2022-10-16 07:30:11 -04:00
dbg!("Proposing");
machine.round_propose().await;
2022-10-12 21:36:40 -04:00
loop {
2022-10-16 07:30:11 -04:00
// Check if any timeouts have been triggered
2022-10-12 21:36:40 -04:00
let now = Instant::now();
let (t1, t2, t3) = {
2022-10-16 07:30:11 -04:00
let ready = |step| machine.timeouts.get(&step).unwrap_or(&now) < &now;
(ready(Step::Propose), ready(Step::Prevote), ready(Step::Precommit))
};
2022-10-02 23:23:58 -04:00
2022-10-16 07:30:11 -04:00
// Propose timeout
if t1 {
todo!()
}
2022-10-16 07:30:11 -04:00
// Prevote timeout
if t2 {
todo!()
}
2022-10-16 07:30:11 -04:00
// Precommit timeout
if t3 {
todo!()
}
2022-10-02 23:23:58 -04:00
2022-10-16 07:30:11 -04:00
// If there's a message, handle it
match msg_recv.try_recv() {
Ok(msg) => match machine.message(msg).await {
Ok(None) => (),
Ok(Some(block)) => {
let proposal = machine.network.write().await.add_block(block);
machine.reset(proposal).await
}
Err(TendermintError::Malicious(validator)) => {
machine.network.write().await.slash(validator).await
}
Err(TendermintError::Temporal) => (),
},
Err(TryRecvError::Empty) => yield_now().await,
Err(TryRecvError::Disconnected) => break,
2022-10-12 21:36:40 -04:00
}
}
}),
2022-10-02 23:23:58 -04:00
}
}
// 49-54
2022-10-16 07:30:11 -04:00
fn check_committed(&mut self, round: Round) -> Option<N::Block> {
let proposer = self.weights.proposer(self.number, round);
2022-10-02 23:23:58 -04:00
// Get the proposal
2022-10-16 07:30:11 -04:00
if let Some(proposal) = self.log.get(round, proposer, Step::Propose) {
2022-10-02 23:23:58 -04:00
// Destructure
debug_assert!(matches!(proposal, Data::Proposal(..)));
if let Data::Proposal(_, block) = proposal {
// Check if it has gotten a sufficient amount of precommits
let (participants, weight) =
2022-10-16 07:30:11 -04:00
self.log.message_instances(round, Data::Precommit(Some(block.id())));
2022-10-02 23:23:58 -04:00
2022-10-16 07:30:11 -04:00
let threshold = self.weights.threshold();
if weight >= threshold {
return Some(block.clone());
2022-10-02 23:23:58 -04:00
}
// 47-48
2022-10-16 07:30:11 -04:00
if participants >= threshold {
let timeout = self.timeout(Step::Precommit);
self.timeouts.entry(Step::Precommit).or_insert(timeout);
2022-10-02 23:23:58 -04:00
}
}
}
None
}
2022-10-16 07:30:11 -04:00
async fn message(
&mut self,
msg: Message<N::ValidatorId, N::Block>,
) -> Result<Option<N::Block>, TendermintError<N::ValidatorId>> {
if msg.number != self.number {
2022-10-02 23:23:58 -04:00
Err(TendermintError::Temporal)?;
}
2022-10-16 07:30:11 -04:00
if matches!(msg.data, Data::Proposal(..)) &&
(msg.sender != self.weights.proposer(msg.number, msg.round))
{
Err(TendermintError::Malicious(msg.sender))?;
};
2022-10-16 07:30:11 -04:00
if !self.log.log(msg.clone())? {
2022-10-02 23:23:58 -04:00
return Ok(None);
}
// All functions, except for the finalizer and the jump, are locked to the current round
// Run the finalizer to see if it applies
if matches!(msg.data, Data::Proposal(..)) || matches!(msg.data, Data::Precommit(_)) {
let block = self.check_committed(msg.round);
if block.is_some() {
return Ok(block);
}
}
// Else, check if we need to jump ahead
2022-10-16 07:30:11 -04:00
if msg.round.0 < self.round.0 {
2022-10-02 23:23:58 -04:00
return Ok(None);
2022-10-16 07:30:11 -04:00
} else if msg.round.0 > self.round.0 {
2022-10-02 23:23:58 -04:00
// 55-56
2022-10-16 07:30:11 -04:00
if self.log.round_participation(self.round) > self.weights.fault_thresold() {
2022-10-02 23:23:58 -04:00
self.round(msg.round);
} else {
return Ok(None);
}
}
2022-10-16 07:30:11 -04:00
let proposal = self
.log
.get(self.round, self.weights.proposer(self.number, self.round), Step::Propose)
.cloned();
2022-10-02 23:23:58 -04:00
if self.step == Step::Propose {
2022-10-16 07:30:11 -04:00
if let Some(proposal) = &proposal {
2022-10-02 23:23:58 -04:00
debug_assert!(matches!(proposal, Data::Proposal(..)));
if let Data::Proposal(vr, block) = proposal {
if let Some(vr) = vr {
// 28-33
2022-10-16 07:30:11 -04:00
if (vr.0 < self.round.0) && self.log.has_consensus(*vr, Data::Prevote(Some(block.id())))
{
debug_assert!(self
2022-10-16 07:30:11 -04:00
.broadcast(Data::Prevote(Some(block.id()).filter(|_| {
self
.locked
2022-10-16 07:30:11 -04:00
.as_ref()
.map(|(round, value)| (round.0 <= vr.0) || (block.id() == value.id()))
.unwrap_or(true)
})))
2022-10-16 07:30:11 -04:00
.await
.is_none());
2022-10-02 23:23:58 -04:00
self.step = Step::Prevote;
} else {
Err(TendermintError::Malicious(msg.sender))?;
}
} else {
// 22-27
2022-10-16 07:30:11 -04:00
self
.network
.write()
.await
.validate(block)
.map_err(|_| TendermintError::Malicious(msg.sender))?;
debug_assert!(self
2022-10-16 07:30:11 -04:00
.broadcast(Data::Prevote(Some(block.id()).filter(|_| self.locked.is_none() ||
self.locked.as_ref().map(|locked| locked.1.id()) == Some(block.id()))))
.await
.is_none());
2022-10-02 23:23:58 -04:00
self.step = Step::Prevote;
}
}
}
}
if self.step == Step::Prevote {
2022-10-16 07:30:11 -04:00
let (participation, weight) = self.log.message_instances(self.round, Data::Prevote(None));
2022-10-02 23:23:58 -04:00
// 34-35
2022-10-16 07:30:11 -04:00
if participation > self.weights.threshold() {
let timeout = self.timeout(Step::Prevote);
self.timeouts.entry(Step::Prevote).or_insert(timeout);
2022-10-02 23:23:58 -04:00
}
// 44-46
2022-10-16 07:30:11 -04:00
if weight > self.weights.threshold() {
debug_assert!(self.broadcast(Data::Precommit(None)).await.is_none());
2022-10-02 23:23:58 -04:00
self.step = Step::Precommit;
}
}
2022-10-16 07:30:11 -04:00
if (self.valid.is_none()) && ((self.step == Step::Prevote) || (self.step == Step::Precommit)) {
if let Some(proposal) = proposal {
debug_assert!(matches!(proposal, Data::Proposal(..)));
if let Data::Proposal(_, block) = proposal {
if self.log.has_consensus(self.round, Data::Prevote(Some(block.id()))) {
self.valid = Some((self.round, block.clone()));
if self.step == Step::Prevote {
self.locked = self.valid.clone();
self.step = Step::Precommit;
return Ok(self.broadcast(Data::Precommit(Some(block.id()))).await);
}
}
}
}
}
2022-10-02 23:23:58 -04:00
Ok(None)
}
}