Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
herr-seppia committed Dec 18, 2024
1 parent 39fcb60 commit bab1167
Show file tree
Hide file tree
Showing 9 changed files with 60 additions and 20 deletions.
2 changes: 2 additions & 0 deletions consensus/src/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use std::cmp;
use std::sync::Arc;
use std::time::Duration;

use node_data::message::{AsyncQueue, Message, Payload};
use tokio::sync::{oneshot, Mutex};
Expand Down Expand Up @@ -106,6 +107,7 @@ impl<T: Operations + 'static, D: Database + 'static> Consensus<T, D> {
}
};

tokio::time::sleep(Duration::from_secs(1)).await;
// Tear-down procedure
abort(&mut handle).await;

Expand Down
10 changes: 9 additions & 1 deletion consensus/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ impl From<BlsSigError> for ConsensusError {
#[derive(Debug, Error)]
pub enum OperationError {
#[error("failed to call VST {0}")]
InvalidVST(anyhow::Error),
InvalidVST(VstError),
#[error("failed to call EST {0}")]
InvalidEST(anyhow::Error),
#[error("failed to verify header {0}")]
Expand Down Expand Up @@ -116,6 +116,14 @@ pub enum HeaderError {
Storage(&'static str, anyhow::Error),
}

#[derive(Debug, Error)]
pub enum VstError {
#[error("invalid previous block hash")]
PrevBlockHash,
#[error("Generic error in vst: {0}")]
Generic(String),
}

impl HeaderError {
pub fn must_vote(&self) -> bool {
match self {
Expand Down
2 changes: 1 addition & 1 deletion consensus/src/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ pub trait Operations: Send + Sync {
prev_commit: StateRoot,
blk: &Block,
voters: &[Voter],
) -> Result<VerificationOutput, OperationError>;
) -> Result<VerificationOutput, VstError>;

async fn execute_state_transition(
&self,
Expand Down
21 changes: 14 additions & 7 deletions consensus/src/validation/step.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

use std::sync::Arc;

use anyhow::anyhow;
use node_data::bls::PublicKeyBytes;
use node_data::ledger::{to_str, Block};
use node_data::message::payload::{Validation, Vote};
Expand All @@ -19,6 +18,7 @@ use tracing::{debug, error, info, Instrument};

use crate::commons::{Database, RoundUpdate};
use crate::config::is_emergency_iter;
use crate::errors::VstError;
use crate::execution_ctx::ExecutionCtx;
use crate::msg_handler::StepOutcome;
use crate::operations::{Operations, Voter};
Expand Down Expand Up @@ -112,6 +112,13 @@ impl<T: Operations + 'static, D: Database> ValidationStep<T, D> {
.await
{
Ok(_) => Vote::Valid(header.hash),
Err(VstError::PrevBlockHash) => {
error!(
event =
"skip vote due to invalid_prev_block_hash",
);
return;
}
Err(err) => {
error!(event = "failed_vst_call", ?err);
Vote::Invalid(header.hash)
Expand Down Expand Up @@ -165,7 +172,7 @@ impl<T: Operations + 'static, D: Database> ValidationStep<T, D> {
candidate: &Block,
voters: &[Voter],
executor: &Arc<T>,
) -> anyhow::Result<()> {
) -> Result<(), VstError> {
match executor
.verify_state_transition(prev_commit, candidate, voters)
.await
Expand All @@ -176,23 +183,23 @@ impl<T: Operations + 'static, D: Database> ValidationStep<T, D> {
// ones we expect to have with the
// current candidate block.
if output.event_bloom != candidate.header().event_bloom {
return Err(anyhow!(
return Err(VstError::Generic(format!(
"mismatch, event_bloom: {}, candidate_event_bloom: {}",
hex::encode(output.event_bloom),
hex::encode(candidate.header().event_bloom)
));
)));
}

if output.state_root != candidate.header().state_hash {
return Err(anyhow!(
return Err(VstError::Generic(format!(
"mismatch, state_hash: {}, candidate_state_hash: {}",
hex::encode(output.state_root),
hex::encode(candidate.header().state_hash)
));
)));
}
}
Err(err) => {
return Err(anyhow!("vm_err: {:?}", err));
return Err(err);
}
};

Expand Down
7 changes: 4 additions & 3 deletions node/src/chain/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ use std::time::Duration;
use async_trait::async_trait;
use dusk_consensus::commons::{RoundUpdate, TimeoutSet};
use dusk_consensus::consensus::Consensus;
use dusk_consensus::errors::{ConsensusError, HeaderError, OperationError};
use dusk_consensus::errors::{
ConsensusError, HeaderError, OperationError, VstError,
};
use dusk_consensus::operations::{
CallParams, Operations, Output, VerificationOutput, Voter,
};
Expand Down Expand Up @@ -318,13 +320,12 @@ impl<DB: database::DB, VM: vm::VMExecution> Operations for Executor<DB, VM> {
prev_root: [u8; 32],
blk: &Block,
voters: &[Voter],
) -> Result<VerificationOutput, OperationError> {
) -> Result<VerificationOutput, VstError> {
info!("verifying state");

let vm = self.vm.read().await;

vm.verify_state_transition(prev_root, blk, voters)
.map_err(OperationError::InvalidVST)
}

async fn execute_state_transition(
Expand Down
3 changes: 2 additions & 1 deletion node/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use dusk_consensus::errors::VstError;
use dusk_consensus::operations::{CallParams, VerificationOutput, Voter};
use dusk_consensus::user::provisioners::Provisioners;
use dusk_consensus::user::stake::Stake;
Expand Down Expand Up @@ -32,7 +33,7 @@ pub trait VMExecution: Send + Sync + 'static {
prev_root: [u8; 32],
blk: &Block,
voters: &[Voter],
) -> anyhow::Result<VerificationOutput>;
) -> Result<VerificationOutput, VstError>;

fn accept(
&self,
Expand Down
5 changes: 5 additions & 0 deletions rusk/src/lib/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ pub enum Error {
InvalidCreditsCount(u64, usize),
/// Memo too large
MemoTooLarge(usize),
/// Chain tip different from the expected one
TipChanged,
}

impl std::error::Error for Error {}
Expand Down Expand Up @@ -182,6 +184,9 @@ impl fmt::Display for Error {
Error::MemoTooLarge(size) => {
write!(f, "The memo size {size} is too large")
}
Error::TipChanged => {
write!(f, "Chain tip different from the expected one")
}
}
}
}
8 changes: 6 additions & 2 deletions rusk/src/lib/node/rusk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use std::path::Path;
use std::sync::{mpsc, Arc, LazyLock};
use std::time::{Duration, Instant};
use std::{fs, io};
use std::{fs, io, thread};

use execution_core::stake::StakeKeys;
use execution_core::transfer::PANIC_NONCE_NOT_READY;
Expand Down Expand Up @@ -271,6 +271,7 @@ impl Rusk {
slashing: Vec<Slash>,
voters: &[Voter],
) -> Result<(Vec<SpentTransaction>, VerificationOutput)> {
thread::sleep(Duration::from_secs(1));
let session = self.new_block_session(block_height, prev_commit)?;

accept(
Expand Down Expand Up @@ -479,7 +480,10 @@ impl Rusk {
block_height: u64,
commit: [u8; 32],
) -> Result<Session> {
let mut session = self._session(block_height, Some(commit))?;
let mut session = self._session(block_height, None)?;
if session.root() != commit {
return Err(Error::TipChanged);
}
let _: CallReceipt<()> = session
.call(STAKE_CONTRACT, "before_state_transition", &(), u64::MAX)
.expect("before_state_transition to success");
Expand Down
22 changes: 17 additions & 5 deletions rusk/src/lib/node/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

mod query;

use dusk_consensus::errors::VstError;
use node_data::events::contract::ContractEvent;
use tracing::info;

Expand Down Expand Up @@ -48,13 +49,18 @@ impl VMExecution for Rusk {
prev_commit: [u8; 32],
blk: &Block,
voters: &[Voter],
) -> anyhow::Result<VerificationOutput> {
) -> Result<VerificationOutput, VstError> {
info!("Received verify_state_transition request");
let generator = blk.header().generator_bls_pubkey;
let generator = BlsPublicKey::from_slice(&generator.0)
.map_err(|e| anyhow::anyhow!("Error in from_slice {e:?}"))?;
let generator =
BlsPublicKey::from_slice(&generator.0).map_err(|e| {
VstError::Generic(format!("Error in from_slice {e:?}"))
})?;
// .map_err(|e| anyhow::anyhow!("Error in from_slice {e:?}"))?;

let slashing = Slash::from_block(blk)?;
let slashing = Slash::from_block(blk).map_err(|e| {
VstError::Generic(format!("Error in from_block {e:?}"))
})?;

let (_, verification_output) = self
.verify_transactions(
Expand All @@ -67,7 +73,13 @@ impl VMExecution for Rusk {
slashing,
voters,
)
.map_err(|inner| anyhow::anyhow!("Cannot verify txs: {inner}!!"))?;
.map_err(|inner| {
if let crate::Error::TipChanged = inner {
VstError::PrevBlockHash
} else {
VstError::Generic(format!("Cannot verify txs: {inner}!!"))
}
})?;

Ok(verification_output)
}
Expand Down

0 comments on commit bab1167

Please sign in to comment.