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

Implement Simperby API #433

Merged
merged 24 commits into from
May 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
29 changes: 29 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ members = [
"repository",
"consensus",
"governance",
"settlement"
"settlement",
"simperby"
]
1 change: 1 addition & 0 deletions consensus/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ simperby-core = { version = "0.1.0", path = "../core" }
simperby-network = { version = "0.1.0", path = "../network" }
vetomint = { version = "0.1.0", path = "../vetomint" }
parking_lot = "0.12.1"
hex = "0.4.3"

[dev-dependencies]
simperby-test-suite = { version = "0.1.0", path = "../test-suite" }
Expand Down
22 changes: 18 additions & 4 deletions consensus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use tokio::sync::RwLock;

pub type Error = eyre::Error;

pub use state::ConsensusMessage;
pub use vetomint::ConsensusParams;

const STATE_FILE_NAME: &str = "state.json";
Expand All @@ -23,10 +24,17 @@ pub enum ProgressResult {
NonNilPreCommitted(ConsensusRound, Hash256, Timestamp),
NilPreVoted(ConsensusRound, Timestamp),
NilPreCommitted(ConsensusRound, Timestamp),
Finalized(Hash256, Timestamp, FinalizationProof),
Finalized(Finalization),
ViolationReported(PublicKey, String, Timestamp),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Finalization {
pub block_hash: Hash256,
pub timestamp: Timestamp,
pub proof: FinalizationProof,
}

/// The consensus module
pub struct Consensus {
/// The distributed consensus message set.
Expand Down Expand Up @@ -91,7 +99,7 @@ impl Consensus {
}

/// Checks whether the consensus is finalized.
pub async fn check_finalized(&self) -> Result<Option<FinalizationProof>, Error> {
pub async fn check_finalized(&self) -> Result<Option<Finalization>, Error> {
let state = self.read_state().await?;
Ok(state.check_finalized())
}
Expand Down Expand Up @@ -140,6 +148,10 @@ impl Consensus {
Ok(())
}

pub fn get_dms(&self) -> Arc<RwLock<Dms<ConsensusMessage>>> {
Arc::clone(&self.dms)
}

pub async fn flush(&mut self) -> Result<(), Error> {
// TODO: filter unverified messages (due to the lack of the block verification)
let mut state = self.read_state().await?;
Expand Down Expand Up @@ -173,13 +185,15 @@ impl Consensus {
impl Consensus {
async fn read_state(&self) -> Result<State, Error> {
let raw_state = self.state_storage.read_file(STATE_FILE_NAME).await?;
let state: State = serde_spb::from_str(&raw_state)?;
let state: State = serde_spb::from_slice(&hex::decode(raw_state)?)?;
hataehyeok marked this conversation as resolved.
Show resolved Hide resolved
Ok(state)
}

async fn commit_state(&mut self, state: &State) -> Result<(), Error> {
// We can't use json because of a non-string map
let data = hex::encode(serde_spb::to_vec(state).unwrap());
hataehyeok marked this conversation as resolved.
Show resolved Hide resolved
self.state_storage
.add_or_overwrite_file(STATE_FILE_NAME, serde_spb::to_string(state).unwrap())
.add_or_overwrite_file(STATE_FILE_NAME, data)
.await
.map_err(|_| eyre!("failed to commit consensus state to the storage"))
}
Expand Down
28 changes: 14 additions & 14 deletions consensus/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use super::ProgressResult;
use super::*;
use eyre::eyre;
use serde::{Deserialize, Serialize};
use simperby_core::*;
Expand Down Expand Up @@ -108,7 +108,7 @@ pub struct State {
precommits: BTreeMap<(Hash256, ConsensusRound), Vec<TypedSignature<FinalizationSignTarget>>>,
/// If `Some`, any operation on the consensus module will fail;
/// the user must run `new()` with the next height info.
finalized: Option<FinalizationProof>,
finalized: Option<Finalization>,
}

impl State {
Expand All @@ -128,7 +128,7 @@ impl State {
vetomint: Vetomint::new(height_info),
block_header: block_header.clone(),
block_identifier_count: 0,
to_be_processed_events: Vec::new(),
to_be_processed_events: vec![(ConsensusEvent::Start, round_zero_timestamp)],
updated_events: BTreeSet::new(),
verified_block_hashes: BTreeMap::new(),
vetoed_block_hashes: BTreeSet::new(),
Expand All @@ -139,7 +139,7 @@ impl State {
Ok(state)
}

pub fn check_finalized(&self) -> Option<FinalizationProof> {
pub fn check_finalized(&self) -> Option<Finalization> {
self.finalized.clone()
}

Expand Down Expand Up @@ -208,7 +208,8 @@ impl State {
if let ConsensusMessage::NonNilPreCommitted(round, block_hash) = message {
self.precommits
.entry((block_hash, round))
.and_modify(|v| v.push(TypedSignature::new(signature, author)));
.and_modify(|v| v.push(TypedSignature::new(signature.clone(), author.clone())))
.or_insert(vec![TypedSignature::new(signature, author)]);
}
}
}
Expand Down Expand Up @@ -279,7 +280,7 @@ impl State {
}

fn process_consensus_response_to_progress_result(
&self,
&mut self,
response: ConsensusResponse,
timestamp: Timestamp,
) -> (ProgressResult, Option<ConsensusMessage>) {
Expand Down Expand Up @@ -345,14 +346,13 @@ impl State {
.get(&(block_hash, round))
.cloned()
.expect("there must be valid precommits for the finalized block");
(
ProgressResult::Finalized(
block_hash,
timestamp,
FinalizationProof { round, signatures },
),
None,
)
let finalization = Finalization {
block_hash,
timestamp,
proof: FinalizationProof { round, signatures },
};
self.finalized = Some(finalization.clone());
(ProgressResult::Finalized(finalization), None)
}
ConsensusResponse::ViolationReport {
violator,
Expand Down
Loading