Skip to content

Commit

Permalink
Small refactoring and cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
romac committed May 22, 2024
1 parent 4ae75b6 commit 66d70d2
Show file tree
Hide file tree
Showing 6 changed files with 179 additions and 138 deletions.
10 changes: 8 additions & 2 deletions code/cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use color_eyre::eyre::{eyre, Result};
use directories::BaseDirs;
use malachite_node::config::Config;
use malachite_test::{PrivateKey, ValidatorSet};
use tracing::info;

use crate::logging::DebugSection;

Expand Down Expand Up @@ -112,6 +113,7 @@ impl Args {
/// load_config returns a configuration compiled from the input parameters
pub fn load_config(&self) -> Result<Config> {
let config_file = self.get_config_file_path()?;
info!("Loading configuration from {:?}", config_file.display());
let mut config: Config = load_toml_file(&config_file)?;
if let Some(index) = self.index {
config.moniker = format!("test-{}", index);
Expand All @@ -121,7 +123,9 @@ impl Args {

/// load_genesis returns the validator set from the genesis file
pub fn load_genesis(&self) -> Result<ValidatorSet> {
load_json_file(&self.get_genesis_file_path()?)
let genesis_file = self.get_genesis_file_path()?;
info!("Loading genesis from {:?}", genesis_file.display());
load_json_file(&genesis_file)
}

/// load_private_key returns the private key either from the command-line parameter or
Expand All @@ -131,7 +135,9 @@ impl Args {
|| self.private_key == vec![0u8; 32]
|| self.private_key.len() < 32
{
load_json_file(&self.get_priv_validator_key_file_path()?)
let priv_key_file = self.get_priv_validator_key_file_path()?;
info!("Loading private key from {:?}", priv_key_file.display());
load_json_file(&priv_key_file)
} else {
let mut key: [u8; 32] = [0; 32];
key.copy_from_slice(&self.private_key);
Expand Down
111 changes: 111 additions & 0 deletions code/cli/src/cmd/init.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
//! Init command
use std::fs;
use std::path::Path;

use color_eyre::eyre::{eyre, Result};
use tracing::{info, warn};

use malachite_node::config::Config;
use malachite_test::PrivateKey;
use malachite_test::ValidatorSet as Genesis;

use crate::example::{generate_config, generate_genesis, generate_private_key};

/// Execute the init command
pub fn run(
config_file: &Path,
genesis_file: &Path,
priv_validator_key_file: &Path,
index: usize,
) -> Result<()> {
// Save default configuration
if config_file.exists() {
warn!(
"Configuration file already exists at {:?}, skipping.",
config_file.display()
)
} else {
info!("Saving configuration to {:?}.", config_file);
save_config(config_file, &generate_config(index))?;
}

// Save default genesis
if genesis_file.exists() {
warn!(
"Genesis file already exists at {:?}, skipping.",
genesis_file.display()
)
} else {
info!("Saving test genesis to {:?}.", genesis_file);
save_genesis(genesis_file, &generate_genesis())?;
}

// Save default priv_validator_key
if priv_validator_key_file.exists() {
warn!(
"Private key file already exists at {:?}, skipping.",
priv_validator_key_file.display()
)
} else {
info!("Saving private key to {:?}.", priv_validator_key_file);
save_priv_validator_key(priv_validator_key_file, &generate_private_key(index))?;
}

Ok(())
}

/// Save configuration to file
pub fn save_config(config_file: &Path, config: &Config) -> Result<()> {
save(config_file, &toml::to_string_pretty(config)?)
}

/// Save genesis to file
pub fn save_genesis(genesis_file: &Path, genesis: &Genesis) -> Result<()> {
save(genesis_file, &serde_json::to_string_pretty(genesis)?)
}

/// Save private_key validator key to file
pub fn save_priv_validator_key(
priv_validator_key_file: &Path,
private_key: &PrivateKey,
) -> Result<()> {
save(
priv_validator_key_file,
&serde_json::to_string_pretty(private_key)?,
)
}

fn save(path: &Path, data: &str) -> Result<()> {
use std::io::Write;

if let Some(parent_dir) = path.parent() {
fs::create_dir_all(parent_dir).map_err(|e| {
eyre!(
"Failed to create parent directory {:?}: {e:?}",
parent_dir.display()
)
})?;
}

let mut f = fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)
.map_err(|e| {
eyre!(
"Failed to crate configuration file at {:?}: {e:?}",
path.display()
)
})?;

f.write_all(data.as_bytes()).map_err(|e| {
eyre!(
"Failed to write configuration to {:?}: {e:?}",
path.display()
)
})?;

Ok(())
}
2 changes: 2 additions & 0 deletions code/cli/src/cmd/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub mod init;
pub mod start;
36 changes: 36 additions & 0 deletions code/cli/src/cmd/start.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use color_eyre::eyre::Result;

use malachite_actors::util::make_node_actor;
use malachite_node::config::Config;
use malachite_test::{Address, PrivateKey, ValidatorSet};
use tracing::info;

pub async fn run(sk: PrivateKey, cfg: Config, vs: ValidatorSet) -> Result<()> {
let val_address = Address::from_public_key(&sk.public_key());
let moniker = cfg.moniker.clone();

info!("[{}] Starting...", &cfg.moniker);

let (tx_decision, mut rx_decision) = tokio::sync::mpsc::channel(32);
let (actor, handle) = make_node_actor(vs, sk, val_address, tx_decision).await;

tokio::spawn({
let actor = actor.clone();
async move {
tokio::signal::ctrl_c().await.unwrap();
info!("[{moniker}] Shutting down...");
actor.stop(None);
}
});

while let Some((height, round, value)) = rx_decision.recv().await {
info!(
"[{}] Decision at height {height} and round {round}: {value:?}",
&cfg.moniker
);
}

handle.await?;

Ok(())
}
92 changes: 0 additions & 92 deletions code/cli/src/init.rs

This file was deleted.

66 changes: 22 additions & 44 deletions code/cli/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,43 @@
use color_eyre::eyre::Result;
use rand::rngs::OsRng;
use tracing::{debug, info};
use tracing::debug;

use malachite_actors::util::make_node_actor;
use malachite_node::config::Config;
use malachite_test::{Address, PrivateKey, ValidatorSet};

use args::Commands;
use example::{generate_config, generate_genesis, generate_private_key};
use malachite_test::{PrivateKey, ValidatorSet};

use crate::args::{Args, Commands};
use crate::example::{generate_config, generate_genesis, generate_private_key};
use crate::logging::LogLevel;

mod args;
mod cmd;
mod example;
mod init;
mod logging;

#[tokio::main(flavor = "current_thread")]
pub async fn main() -> Result<()> {
let args = args::Args::new();
let args = Args::new();

logging::init(LogLevel::Debug, &args.debug);
debug!("Command-line parameters: {:?}", args);

if let Commands::Init = args.command {
init::run(
args.get_config_file_path()?,
args.get_genesis_file_path()?,
args.get_priv_validator_key_file_path()?,
args.index.unwrap_or(0),
)?;
debug!("Command-line parameters: {args:?}");

return Ok(());
match args.command {
Commands::Init => init(&args),
Commands::Start => start(&args).await,
}
}

fn init(args: &Args) -> Result<()> {
cmd::init::run(
&args.get_config_file_path()?,
&args.get_genesis_file_path()?,
&args.get_priv_validator_key_file_path()?,
args.index.unwrap_or(0),
)
}

async fn start(args: &Args) -> Result<()> {
let cfg: Config = match args.index {
None => args.load_config()?,
Some(index) => generate_config(index),
Expand All @@ -51,31 +55,5 @@ pub async fn main() -> Result<()> {
Some(_) => generate_genesis(),
};

let val_address = Address::from_public_key(&sk.public_key());
let moniker = cfg.moniker.clone();

info!("[{}] Starting...", &cfg.moniker);

let (tx_decision, mut rx_decision) = tokio::sync::mpsc::channel(32);
let (actor, handle) = make_node_actor(vs, sk, val_address, tx_decision).await;

tokio::spawn({
let actor = actor.clone();
async move {
tokio::signal::ctrl_c().await.unwrap();
info!("[{moniker}] Shutting down...");
actor.stop(None);
}
});

while let Some((height, round, value)) = rx_decision.recv().await {
info!(
"[{}] Decision at height {height} and round {round}: {value:?}",
&cfg.moniker
);
}

handle.await?;

Ok(())
cmd::start::run(sk, cfg, vs).await
}

0 comments on commit 66d70d2

Please sign in to comment.