Skip to content

Commit

Permalink
block-mode
Browse files Browse the repository at this point in the history
  • Loading branch information
dinhani-cw committed May 22, 2024
1 parent 503310e commit 6ac1727
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 33 deletions.
4 changes: 2 additions & 2 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ e2e-clock-stratus:
#!/bin/bash
echo "-> Starting Stratus"
just build || exit 1
cargo run --release --bin stratus --features dev, -- --block-time 1000 -a 0.0.0.0:3000 > stratus.log &
cargo run --release --bin stratus --features dev, -- --block-mode 1s -a 0.0.0.0:3000 > stratus.log &

echo "-> Waiting Stratus to start"
wait-service --tcp 0.0.0.0:3000 -t {{ wait_service_timeout }} -- echo
Expand All @@ -295,7 +295,7 @@ e2e-clock-stratus-rocks:
#!/bin/bash
echo "-> Starting Stratus"
just build || exit 1
cargo run --release --bin stratus --features dev, -- --block-time 1000 --perm-storage=rocks -a 0.0.0.0:3000 > stratus.log &
cargo run --release --bin stratus --features dev, -- --block-mode 1s --perm-storage=rocks -a 0.0.0.0:3000 > stratus.log &

echo "-> Waiting Stratus to start"
wait-service --tcp 0.0.0.0:3000 -t {{ wait_service_timeout }} -- echo
Expand Down
36 changes: 8 additions & 28 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ use crate::eth::Consensus;
use crate::eth::EvmTask;
use crate::eth::Executor;
use crate::eth::TransactionRelayer;
use crate::ext::parse_duration;
use crate::infra::tracing::warn_task_tx_closed;
use crate::infra::BlockchainClient;
use crate::GlobalState;
Expand Down Expand Up @@ -231,8 +232,8 @@ impl ExecutorConfig {
#[derive(Parser, DebugAsJson, Clone, serde::Serialize)]
pub struct MinerConfig {
/// Target block time.
#[arg(long = "block-time", value_parser=parse_duration, env = "BLOCK_TIME")]
pub block_time: Option<Duration>,
#[arg(long = "block-mode", env = "BLOCK_MODE", default_value = "automine")]
pub block_mode: BlockMinerMode,

/// Generates genesis block on startup when it does not exist.
#[arg(long = "enable-genesis", env = "ENABLE_GENESIS", default_value = "false")]
Expand All @@ -247,19 +248,15 @@ pub struct MinerConfig {
impl MinerConfig {
/// Inits [`BlockMiner`] in external mining mode.
pub async fn init_external_mode(&self, storage: Arc<StratusStorage>, consensus: Option<Arc<Consensus>>) -> anyhow::Result<Arc<BlockMiner>> {
self.init(BlockMinerMode::External, storage, consensus).await
self.init_with_mode(BlockMinerMode::External, storage, consensus).await
}

/// Inits [`BlockMiner`] in automine or interval miner mode.
pub async fn init_automine_or_interval_mode(&self, storage: Arc<StratusStorage>, consensus: Option<Arc<Consensus>>) -> anyhow::Result<Arc<BlockMiner>> {
let mode = match self.block_time {
Some(block_time) => BlockMinerMode::Interval(block_time),
None => BlockMinerMode::Automine,
};
self.init(mode, storage, consensus).await
/// Inits [`BlockMiner`] in the configured mining mode.
pub async fn init(&self, storage: Arc<StratusStorage>, consensus: Option<Arc<Consensus>>) -> anyhow::Result<Arc<BlockMiner>> {
self.init_with_mode(self.block_mode, storage, consensus).await
}

async fn init(&self, mode: BlockMinerMode, storage: Arc<StratusStorage>, consensus: Option<Arc<Consensus>>) -> anyhow::Result<Arc<BlockMiner>> {
async fn init_with_mode(&self, mode: BlockMinerMode, storage: Arc<StratusStorage>, consensus: Option<Arc<Consensus>>) -> anyhow::Result<Arc<BlockMiner>> {
tracing::info!(config = ?self, "starting block miner");

// create miner
Expand Down Expand Up @@ -812,23 +809,6 @@ impl FromStr for ValidatorMethodConfig {
// Helpers
// -----------------------------------------------------------------------------

/// Parses a duration specified using human-time notation or fallback to milliseconds.
fn parse_duration(s: &str) -> anyhow::Result<Duration> {
// try millis
let millis: Result<u64, _> = s.parse();
if let Ok(millis) = millis {
return Ok(Duration::from_millis(millis));
}

// try humantime
if let Ok(parsed) = humantime::parse_duration(s) {
return Ok(parsed);
}

// error
Err(anyhow!("invalid duration format: {}", s))
}

/// Gets the current binary basename.
fn binary_name() -> String {
let binary = std::env::current_exe().unwrap();
Expand Down
23 changes: 21 additions & 2 deletions src/eth/block_miner.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;

use anyhow::Ok;
use ethereum_types::BloomInput;
use keccak_hasher::KeccakHasher;
use nonempty::NonEmpty;
Expand All @@ -22,6 +24,7 @@ use crate::eth::primitives::TransactionExecution;
use crate::eth::primitives::TransactionMined;
use crate::eth::storage::StratusStorage;
use crate::ext::not;
use crate::ext::parse_duration;
use crate::ext::spawn_named;
use crate::ext::DisplayExt;
use crate::log_and_err;
Expand Down Expand Up @@ -89,9 +92,10 @@ impl BlockMiner {
// decide what to do based on mining mode
match self.mode {
// * do not consensus transactions
// * do not notify pending transactions
// * notify pending transactions
// * mine block immediately
BlockMinerMode::Automine => {
let _ = self.notifier_pending_txs.send(tx_hash);
self.mine_local_and_commit().await?;
}
// * consensus transactions
Expand Down Expand Up @@ -411,7 +415,7 @@ mod interval_miner_ticker {
}

/// Indicates when the miner will mine new blocks.
#[derive(Debug, strum::EnumIs)]
#[derive(Debug, Clone, Copy, strum::EnumIs, serde::Serialize)]
pub enum BlockMinerMode {
/// Mines a new block for each transaction execution.
Automine,
Expand All @@ -422,3 +426,18 @@ pub enum BlockMinerMode {
/// Does not automatically mines a new block. A call to `mine_*` must be executed to mine a new block.
External,
}

impl FromStr for BlockMinerMode {
type Err = anyhow::Error;

fn from_str(s: &str) -> anyhow::Result<Self, Self::Err> {
match s {
"automine" => Ok(Self::Automine),
"external" => Ok(Self::External),
s => {
let block_time = parse_duration(s)?;
Ok(Self::Interval(block_time))
}
}
}
}
25 changes: 25 additions & 0 deletions src/ext.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
//! Standard library extensions.
use std::time::Duration;

use anyhow::anyhow;

// -----------------------------------------------------------------------------
// Macros
// -----------------------------------------------------------------------------
Expand Down Expand Up @@ -97,6 +101,27 @@ macro_rules! log_and_err {
};
}

// -----------------------------------------------------------------------------
// Duration
// -----------------------------------------------------------------------------

/// Parses a duration specified using human-time notation or fallback to milliseconds.
pub fn parse_duration(s: &str) -> anyhow::Result<Duration> {
// try millis
let millis: Result<u64, _> = s.parse();
if let Ok(millis) = millis {
return Ok(Duration::from_millis(millis));
}

// try humantime
if let Ok(parsed) = humantime::parse_duration(s) {
return Ok(parsed);
}

// error
Err(anyhow!("invalid duration format: {}", s))
}

// -----------------------------------------------------------------------------
// Option
// -----------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ async fn run(config: StratusConfig) -> anyhow::Result<()> {
// init services
let storage = config.storage.init().await?;
let relayer = config.relayer.init(Arc::clone(&storage)).await?;
let miner = config.miner.init_automine_or_interval_mode(Arc::clone(&storage), None).await?;
let miner = config.miner.init(Arc::clone(&storage), None).await?;
let executor = config.executor.init(Arc::clone(&storage), Arc::clone(&miner), relayer, None).await;

// start rpc server
Expand Down

0 comments on commit 6ac1727

Please sign in to comment.