From f6435eb9bad21629be5262aad4d9a188001102e7 Mon Sep 17 00:00:00 2001 From: danda Date: Fri, 25 Nov 2022 22:25:40 -0800 Subject: [PATCH] feat(cli): git init installs genesis file kindelia_core: * genesis.kdl file removed. (moved into kindelia/genesis/networks) * genesis Statements are passed to kindelia_core api, not network_id * added kindelia_core/genesis-tests.kdl for core test cases * updated test cases * remove empty constants.rs * remove genesis_path(). (moved into kindelia/src/genesis.rs) kindelia: * all genesis files get compiled into kindelia executable * latest (by name) genesis file gets installed by kindelia init * add kindelia/genesis/README.md * add genesis.rs and move some util fn into it * cargo add include_dir * cargo fmt fixes * parse genesis statements in 'node start' and 'test' * update test(s) --- Cargo.lock | 31 ++++ kindelia/Cargo.toml | 3 + kindelia/genesis/README.md | 18 +++ .../genesis/networks/0xCAFE0006.kdl | 0 kindelia/src/genesis.rs | 79 +++++++++ kindelia/src/main.rs | 26 ++- kindelia/tests/cli.rs | 2 +- kindelia_core/benches/bench.rs | 7 +- kindelia_core/genesis-tests.kdl | 150 ++++++++++++++++++ kindelia_core/src/constants.rs | 5 - kindelia_core/src/hvm.rs | 17 +- kindelia_core/src/lib.rs | 1 - kindelia_core/src/node.rs | 8 +- kindelia_core/src/test/network.rs | 6 + kindelia_core/src/test/util.rs | 5 +- kindelia_core/src/util.rs | 34 ---- 16 files changed, 330 insertions(+), 62 deletions(-) create mode 100644 kindelia/genesis/README.md rename kindelia_core/genesis.kdl => kindelia/genesis/networks/0xCAFE0006.kdl (100%) create mode 100644 kindelia/src/genesis.rs create mode 100644 kindelia_core/genesis-tests.kdl delete mode 100644 kindelia_core/src/constants.rs diff --git a/Cargo.lock b/Cargo.lock index 71b24b34..7302ff2c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -439,6 +439,15 @@ dependencies = [ "termcolor", ] +[[package]] +name = "clap-num" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488557e97528174edaa2ee268b23a809e0c598213a4bbcb4f34575a46fda147e" +dependencies = [ + "num-traits", +] + [[package]] name = "clap_complete" version = "4.0.5" @@ -1347,6 +1356,25 @@ dependencies = [ "syn", ] +[[package]] +name = "include_dir" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18762faeff7122e89e0857b02f7ce6fcc0d101d5e9ad2ad7846cc01d61b7f19e" +dependencies = [ + "include_dir_macros", +] + +[[package]] +name = "include_dir_macros" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b139284b5cf57ecfa712bcc66950bb635b31aff41c188e8a4cfc758eca374a3f" +dependencies = [ + "proc-macro2", + "quote", +] + [[package]] name = "indexmap" version = "1.9.1" @@ -1442,12 +1470,14 @@ version = "0.1.5" dependencies = [ "assert_cmd", "clap 4.0.22", + "clap-num", "clap_complete", "derive_builder", "dirs", "fastrand", "hex", "httpmock", + "include_dir", "kindelia_client", "kindelia_common", "kindelia_core", @@ -1457,6 +1487,7 @@ dependencies = [ "rstest", "serde", "serde_json", + "thiserror", "tokio", "toml", ] diff --git a/kindelia/Cargo.toml b/kindelia/Cargo.toml index 621194cc..fa8cdf16 100644 --- a/kindelia/Cargo.toml +++ b/kindelia/Cargo.toml @@ -32,6 +32,7 @@ fastrand = "1.7.0" dirs = "4.0.0" hex = "0.4" derive_builder = "0.11.2" +include_dir = "0.7.3" # CLI / configuration clap = { version = "4.0.18", features = ["derive"] } @@ -49,6 +50,8 @@ serde_json = "1.0" # Events API tokio = { version = "1.19.1", features = ["sync"] } +# Errors +thiserror = "1.0.37" [dev-dependencies] assert_cmd = "1.0.1" diff --git a/kindelia/genesis/README.md b/kindelia/genesis/README.md new file mode 100644 index 00000000..42e93247 --- /dev/null +++ b/kindelia/genesis/README.md @@ -0,0 +1,18 @@ +# About this directory + +The `genesis/networks` directory holds genesis block files, one per network. + +Important! All files inside the `networks` sub-directory get compiled into the +`kindelia` executable. So please do not put any other type of file inside and +observe the naming convention. + +The files are named to match hexadecimal network identifiers as specified +in the config file with extension `.kdl`. For example, `network/0xCAFE0006.kdl` corresponds to network `0xCAFE0006`. + +Typically a new network is created by bumping this value, eg creating the +file `networks/0xCAFE0007.kdl`. Also `../default.toml` should be updated to match. + +The genesis file with the highest hex value is installed into the +user's home directory when `kindelia init` is run. + + diff --git a/kindelia_core/genesis.kdl b/kindelia/genesis/networks/0xCAFE0006.kdl similarity index 100% rename from kindelia_core/genesis.kdl rename to kindelia/genesis/networks/0xCAFE0006.kdl diff --git a/kindelia/src/genesis.rs b/kindelia/src/genesis.rs new file mode 100644 index 00000000..e9b80fc4 --- /dev/null +++ b/kindelia/src/genesis.rs @@ -0,0 +1,79 @@ +use include_dir::{include_dir, Dir, File}; +use std::path::{Path, PathBuf}; +use thiserror::Error; + +#[derive(Error, Debug)] +pub enum GenesisPathError { + #[error("Home directory not found")] + HomeDirNotFound, + #[error("File not found in {0}")] + FileNotFound(PathBuf), +} + +pub fn genesis_path(network_id: u32) -> Result { + let path = dirs::home_dir() + .ok_or(GenesisPathError::HomeDirNotFound)? + .join(".kindelia") + .join("genesis") + .join(format!("{:#02X}.kdl", network_id)); + match path.exists() { + true => Ok(path), + false => Err(GenesisPathError::FileNotFound(path)), + } +} + +#[derive(Error, Debug)] +pub enum GenesisCodeError { + #[error(transparent)] + PathError(#[from] GenesisPathError), + + #[error("Genesis block could not be read from {path:?}.")] + ReadError { path: PathBuf, cause: std::io::Error }, +} + +pub fn genesis_code(network_id: u32) -> Result { + let path = genesis_path(network_id)?; + std::fs::read_to_string(&path) + .map_err(|e| GenesisCodeError::ReadError { path, cause: e }) +} + +#[derive(Error, Debug)] +pub enum InitGenesisError { + #[error("Could not create directory: {path:?}")] + DirNotCreated { path: std::path::PathBuf, cause: std::io::Error }, + #[error("Unable to write genesis file: {path:?}")] + FileNotWritten { path: std::path::PathBuf, cause: std::io::Error }, + #[error("Genesis file is missing from the executable")] + Missing, +} + +static GENESIS_DIR: Dir<'_> = + include_dir!("$CARGO_MANIFEST_DIR/genesis/networks"); + +/// Copies latest file from kindelia_core/genesis to /.kindelia/genesis +/// Creates target dir if not existing. +/// +/// The way this works is that all the files in kindelia_core/genesis get compiled +/// into the executable by the include_dir!() macro. With this trick we are able +/// to include files dynamically, whereas include_str!() requires a static str. +/// +/// note: we could copy over all files from kindelia_core/genesis instead. +pub fn init_genesis(dir_path: &Path) -> Result<(), InitGenesisError> { + let mut files: Vec<&File> = GENESIS_DIR.files().collect(); + + // files should be named as hex values, so we sort case insensitively + // The goal here is to find highest numeric (hex) value. + files.sort_by_cached_key(|f| f.path().as_os_str().to_ascii_uppercase()); + + let file = files.last().ok_or(InitGenesisError::Missing)?; + let fname = file.path().file_name().ok_or(InitGenesisError::Missing)?; + let fpath = dir_path.join(fname); + + let default_content = file.contents(); + std::fs::create_dir_all(dir_path).map_err(|e| { + InitGenesisError::DirNotCreated { path: dir_path.to_path_buf(), cause: e } + })?; + + std::fs::write(&fpath, default_content) + .map_err(|e| InitGenesisError::FileNotWritten { path: fpath, cause: e }) +} diff --git a/kindelia/src/main.rs b/kindelia/src/main.rs index e3584444..3809a489 100644 --- a/kindelia/src/main.rs +++ b/kindelia/src/main.rs @@ -1,6 +1,7 @@ mod cli; mod config; mod files; +mod genesis; mod util; use std::future::Future; @@ -38,6 +39,7 @@ use util::{ }; use crate::cli::{GetStatsKind, NodeCleanBlocksCommand, NodeCleanCommand}; +use crate::genesis::{genesis_code, init_genesis}; use crate::util::init_config_file; fn main() -> Result<(), String> { @@ -245,6 +247,8 @@ pub fn run_cli() -> Result<(), String> { let path = default_config_path()?; eprintln!("Writing default configuration to '{}'...", path.display()); init_config_file(&path)?; + init_genesis(&default_base_path()?.join("genesis")) + .map_err(|e| e.to_string())?; Ok(()) } CliCommand::Node { command, data_dir, network_id } => { @@ -552,12 +556,18 @@ pub fn sign_code( Ok(stat) } -fn load_code(file: FileInput, encoded: bool) -> Result, String> { +fn load_code( + file: FileInput, + encoded: bool, +) -> Result, String> { let code = file.read_to_string()?; handle_code(&code, encoded) } -fn handle_code(code: &str, encoded: bool) -> Result, String> { +fn handle_code( + code: &str, + encoded: bool, +) -> Result, String> { if encoded { statements_from_hex_seq(code) } else { @@ -664,7 +674,11 @@ async fn join_all( } pub fn test_code(network_id: u32, code: &str, sudo: bool) { - hvm::test_statements_from_code(network_id, code, sudo); + let genesis_stmts = + parser::parse_code(&genesis_code(network_id).expect("Genesis code loads")) + .expect("Genesis code parses"); + + hvm::test_statements_from_code(&genesis_stmts, code, sudo); } fn init_socket() -> Option { @@ -837,10 +851,16 @@ pub fn start_node( // File writter let file_writter = SimpleFileStorage::new(node_config.data_path.clone()); + let genesis_stmts = parser::parse_code( + &genesis_code(node_config.network_id).expect("Genesis code loads"), + ) + .expect("Genesis code parses"); + // Node state object let (node_query_sender, node) = Node::new( node_config.data_path, node_config.network_id, + &genesis_stmts, initial_peers, comm, miner_comm, diff --git a/kindelia/tests/cli.rs b/kindelia/tests/cli.rs index 1ae201e1..88c2b393 100644 --- a/kindelia/tests/cli.rs +++ b/kindelia/tests/cli.rs @@ -102,7 +102,7 @@ mod cli { #[case("../example/block_3.kdl")] #[case("../example/block_4.kdl")] #[case("../example/block_5.kdl")] - #[case("../kindelia_core/genesis.kdl")] + #[case("../kindelia_core/genesis-tests.kdl")] fn test_ser_deser(#[case] file: &str) { use kindelia_core::bits::ProtoSerialize; eprintln!("{}", file); diff --git a/kindelia_core/benches/bench.rs b/kindelia_core/benches/bench.rs index a7d92745..f876aece 100644 --- a/kindelia_core/benches/bench.rs +++ b/kindelia_core/benches/bench.rs @@ -8,7 +8,7 @@ use kindelia_lang::parser; use primitive_types::U256; use kindelia_core::bits::ProtoSerialize; -use kindelia_core::{constants, hvm, net, node, util}; +use kindelia_core::{hvm, net, node, util}; // KHVM // ==== @@ -24,8 +24,9 @@ pub fn temp_dir() -> PathBuf { } pub fn init_runtime(path: PathBuf) -> hvm::Runtime { + const GENESIS_CODE: &str = include_str!("../genesis-tests.kdl"); let genesis_stmts = - parser::parse_code(constants::GENESIS_CODE).expect("Genesis code parses."); + parser::parse_code(GENESIS_CODE).expect("Genesis code parses."); hvm::init_runtime(path, &genesis_stmts) } @@ -153,7 +154,7 @@ fn block_loading(c: &mut Criterion) { // create Node let (_, mut node) = - node::Node::new(dir.clone(), 0, vec![], comm, None, storage, None); + node::Node::new(dir.clone(), 0, &vec![], vec![], comm, None, storage, None); // benchmark block loading c.bench_function("block_loading", |b| b.iter(|| node.load_blocks())); diff --git a/kindelia_core/genesis-tests.kdl b/kindelia_core/genesis-tests.kdl new file mode 100644 index 00000000..4c0260d0 --- /dev/null +++ b/kindelia_core/genesis-tests.kdl @@ -0,0 +1,150 @@ +// T types +ctr {T0} +ctr {T1 x0} +ctr {T2 x0 x1} +ctr {T3 x0 x1 x2} +ctr {T4 x0 x1 x2 x3} +ctr {T5 x0 x1 x2 x3 x4} +ctr {T6 x0 x1 x2 x3 x4 x5} +ctr {T7 x0 x1 x2 x3 x4 x5 x6} +ctr {T8 x0 x1 x2 x3 x4 x5 x6 x7} +ctr {T9 x0 x1 x2 x3 x4 x5 x6 x7 x8} +ctr {TA x0 x1 x2 x3 x4 x5 x6 x7 x8 x9} +ctr {TB x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10} +ctr {TC x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11} +ctr {TD x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12} +ctr {TE x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13} +ctr {TF x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14} +ctr {TG x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13 x14 x15} + +// An if-then-else statement +fun (If cond t f) { + (If #0 ~ f) = f + (If ~ t ~) = t +} + +// Used to pretty-print names +ctr {Name name} + +// Below, we declare the built-in IO operations + +// DONE returns from an IO operation +ctr {DONE expr} +fun (Done expr) { + (Done expr) = {DONE expr} +} + +// TAKE recovers an app's stored state +ctr {TAKE cont} +fun (Take) { + (Take) = @cont {TAKE cont} +} + +// SAVE stores the app's state +ctr {SAVE expr cont} +fun (Save expr) { + (Save expr) = @cont {SAVE expr cont} +} + +// CALL calls another IO operation, assigning +// the caller name to the current subject name +ctr {CALL name argm cont} +fun (Call name argm) { + (Call name argm) = @cont {CALL name argm cont} +} + +// SUBJ returns the name of the current subject +ctr {SUBJ cont} +fun (Subj) { + (Subj) = @cont {SUBJ cont} +} + +// FROM returns the name of the current caller +ctr {FROM cont} +fun (From) { + (From) = @cont {FROM cont} +} + +// TICK returns the current block number +ctr {TICK cont} +fun (Tick) { + (Tick) = @cont {TICK cont} +} + +// GIDX returns the block number and statement index inside the block +// of a function, register or constructor. +// Returns in the form of a U120: +// - most significant 60 bits are the block index +// - less signficiant 60 bits are the statement index +ctr {GIDX name cont} +fun (GetIdx name) { + (GetIdx name) = @cont {GIDX name cont} +} + +// STH0 returns the less significant 120 bits hash of the statement at index idx +ctr {STH0 idx cont} +fun (GetStmHash0 idx) { + (GetStmHash0 idx) = @cont {STH0 idx cont} +} + +// STH0 returns the less significant 120 bits hash of the statement at index idx +ctr {STH1 idx cont} +fun (GetStmHash1 idx) { + (GetStmHash1 idx) = @cont {STH1 idx cont} +} + +// TIME returns the current block timestamp +ctr {TIME cont} +fun (Time) { + (Time) = @cont {TIME cont} +} + +// META returns the current block metadata +ctr {META cont} +fun (Meta) { + (Meta) = @cont {META cont} +} + +// HAX0 returns the current block metadata +ctr {HAX0 cont} +fun (Hax0) { + (Hax0) = @cont {HAX0 cont} +} + +// HAX1 returns the current block metadata +ctr {HAX1 cont} +fun (Hax1) { + (Hax1) = @cont {HAX1 cont} +} + +// FAIL fails a run statement +ctr {FAIL err} +fun (Fail err) { + (Fail err) = {FAIL err} +} + +// NORM fully normalizes a term +ctr {NORM term cont} +fun (Norm term) { + (Norm term) = @cont {NORM term cont} +} + +// LOAD works like TAKE, but clones the state +fun (Load) { + (Load) = @cont {TAKE @x dup x0 x1 = x; {SAVE x0 @~ (!cont x1)}} +} + +// This is here for debugging. Will be removed. +ctr {Inc} +ctr {Get} +fun (Count action) { + (Count {Inc}) = {TAKE @x {SAVE (+ x #1) @~ {DONE #0}}} + (Count {Get}) = (!(Load) @x {DONE x}) +} with { + #0 +} + +// Registers the empty namespace. +reg { + #x7e5f4552091a69125d5dfcb7b8c265 // secret_key = 0x1 +} diff --git a/kindelia_core/src/constants.rs b/kindelia_core/src/constants.rs deleted file mode 100644 index 0807dc7c..00000000 --- a/kindelia_core/src/constants.rs +++ /dev/null @@ -1,5 +0,0 @@ -// VM constants -// ============ - -/// Kdl code included on genesis block -pub const GENESIS_CODE: &str = include_str!("../genesis.kdl"); diff --git a/kindelia_core/src/hvm.rs b/kindelia_core/src/hvm.rs index 7ea365f1..342ff432 100644 --- a/kindelia_core/src/hvm.rs +++ b/kindelia_core/src/hvm.rs @@ -256,11 +256,11 @@ use kindelia_common::nohash_hasher::NoHashHasher; use kindelia_common::{crypto, nohash_hasher, Name, U120}; use kindelia_lang::ast; use kindelia_lang::ast::{Func, Oper, Statement, Term, Var}; -use kindelia_lang::parser::{parse_code, parse_statements, ParseErr}; +use kindelia_lang::parser::{parse_statements, ParseErr}; use crate::bits::ProtoSerialize; use crate::persistence::DiskSer; -use crate::util::{self, genesis_code, mask, U128_SIZE}; +use crate::util::{self, mask, U128_SIZE}; use crate::util::{LocMap, NameMap, U120Map, U128Map}; // Compiled information about a rewrite rule. @@ -4244,7 +4244,7 @@ pub fn print_io_consts() { } // Serializes, deserializes and evaluates statements -pub fn test_statements(network_id: u32, statements: &Vec, debug: bool) { +pub fn test_statements(genesis_stmts: &[Statement], statements: &Vec, debug: bool) { let str_0 = ast::view_statements(statements); let statements = &Vec::proto_deserialized(&statements.proto_serialized()).unwrap(); let str_1 = ast::view_statements(statements); @@ -4255,8 +4255,7 @@ pub fn test_statements(network_id: u32, statements: &Vec, debug: bool // TODO: code below does not need heaps_path at all. extract heap persistence out of Runtime. let heaps_path = dirs::home_dir().unwrap().join(".kindelia").join("state").join("heaps"); - let genesis_smts = parse_code(&genesis_code(network_id).unwrap()).expect("Genesis code parses"); - let mut rt = init_runtime(heaps_path, &genesis_smts); + let mut rt = init_runtime(heaps_path, genesis_stmts); let init = Instant::now(); rt.run_statements(&statements, false, debug); println!(); @@ -4271,16 +4270,16 @@ pub fn test_statements(network_id: u32, statements: &Vec, debug: bool println!("[time] {} ms", init.elapsed().as_millis()); } -pub fn test_statements_from_code(network_id: u32, code: &str, debug: bool) { +pub fn test_statements_from_code(genesis_stmts: &[Statement], code: &str, debug: bool) { let statments = parse_statements(code); match statments { - Ok((.., statements)) => test_statements(network_id, &statements, debug), + Ok((.., statements)) => test_statements(genesis_stmts, &statements, debug), Err(ParseErr { code, erro }) => println!("{}", erro), } } -pub fn test_statements_from_file(network_id: u32, file: &str, debug: bool) { - test_statements_from_code(network_id, &std::fs::read_to_string(file).expect("file not found"), debug); +pub fn test_statements_from_file(genesis_stmts: &[Statement], file: &str, debug: bool) { + test_statements_from_code(genesis_stmts, &std::fs::read_to_string(file).expect("file not found"), debug); } // Term Drop implementation diff --git a/kindelia_core/src/lib.rs b/kindelia_core/src/lib.rs index 99ccaa97..640eb9fc 100644 --- a/kindelia_core/src/lib.rs +++ b/kindelia_core/src/lib.rs @@ -4,7 +4,6 @@ pub mod api; pub mod bits; pub mod config; -pub mod constants; pub mod hvm; pub mod net; pub mod node; diff --git a/kindelia_core/src/node.rs b/kindelia_core/src/node.rs index ef468825..f54a1947 100644 --- a/kindelia_core/src/node.rs +++ b/kindelia_core/src/node.rs @@ -759,9 +759,11 @@ pub fn miner_loop( // ---- impl Node { + #[allow(clippy::too_many_arguments)] pub fn new( data_path: PathBuf, network_id: u32, + genesis_stmts: &[Statement], initial_peers: Vec, comm: C, miner_comm: Option, @@ -772,13 +774,11 @@ impl Node { ) -> (mpsc::SyncSender>, Self) { let (query_sender, query_receiver) = mpsc::sync_channel(1); - let genesis_stmts = - parser::parse_code(&genesis_code(network_id).unwrap()).expect("Genesis code parses"); - let genesis_block = build_genesis_block(&genesis_stmts); + let genesis_block = build_genesis_block(genesis_stmts); let genesis_block = genesis_block.hashed(); let genesis_hash = genesis_block.get_hash().into(); - let runtime = init_runtime(data_path.join("heaps"), &genesis_stmts); + let runtime = init_runtime(data_path.join("heaps"), genesis_stmts); #[rustfmt::skip] let mut node = Node { diff --git a/kindelia_core/src/test/network.rs b/kindelia_core/src/test/network.rs index 3fdf1018..02127507 100644 --- a/kindelia_core/src/test/network.rs +++ b/kindelia_core/src/test/network.rs @@ -11,6 +11,7 @@ use crate::events; use crate::net::{self, ProtoComm}; use crate::node; use crate::{bits, persistence}; +use kindelia_lang::parser; use super::util::temp_dir; @@ -116,11 +117,16 @@ fn start_simulation( // Storage let storage = persistence::EmptyStorage; + let GENESIS_CODE = include_str!("../../genesis-tests.kdl"); + let genesis_stmts = + parser::parse_code(GENESIS_CODE).expect("Genesis code parses."); + // Node let node_thread = { let (node_query_sender, node) = node::Node::new( node_config.data_path, node_config.network_id, + &genesis_stmts, initial_peers, comm, miner_comm, diff --git a/kindelia_core/src/test/util.rs b/kindelia_core/src/test/util.rs index d398e12f..259b3de4 100644 --- a/kindelia_core/src/test/util.rs +++ b/kindelia_core/src/test/util.rs @@ -5,7 +5,6 @@ use std::sync::Arc; use rstest::fixture; -use crate::constants; use crate::hvm::{ self, show_term, Rollback, Runtime, StatementInfo, U128_NONE, U64_NONE, }; @@ -14,11 +13,13 @@ use kindelia_common::{Name, U120}; use kindelia_lang::{ast, parser}; pub fn init_runtime(path: &PathBuf) -> hvm::Runtime { + const GENESIS_CODE: &str = include_str!("../../genesis-tests.kdl"); let genesis_stmts = - parser::parse_code(constants::GENESIS_CODE).expect("Genesis code parses."); + parser::parse_code(GENESIS_CODE).expect("Genesis code parses."); hvm::init_runtime(path.clone(), &genesis_stmts) } + // =========================================================== // Aux types diff --git a/kindelia_core/src/util.rs b/kindelia_core/src/util.rs index bcca08f4..6131ff94 100644 --- a/kindelia_core/src/util.rs +++ b/kindelia_core/src/util.rs @@ -5,8 +5,6 @@ // #![allow(clippy::style)] use std::collections::HashMap; -use std::path::PathBuf; -use thiserror::Error; use bit_vec::BitVec; @@ -184,35 +182,3 @@ macro_rules! print_with_timestamp { }; } -#[derive(Error, Debug)] -pub(crate) enum GenesisPathError { - #[error("Home directory not found")] - HomeDirNotFound, - #[error("File not found in {0}")] - FileNotFound(PathBuf) -} - -pub(crate) fn genesis_path(network_id: u32) -> Result { - let path = dirs::home_dir().ok_or(GenesisPathError::HomeDirNotFound)?.join(".kindelia").join("genesis").join(format!("{:#02X}.kdl", network_id)); - match path.exists() { - true => Ok(path), - false => Err(GenesisPathError::FileNotFound(path)), - } -} - -#[derive(Error, Debug)] -pub(crate) enum GenesisCodeError { - #[error(transparent)] - PathError(#[from] GenesisPathError), - - #[error("Genesis block could not be read from {path:?}.")] - ReadError { - path: PathBuf, - cause: std::io::Error, - } -} - -pub(crate) fn genesis_code(network_id: u32) -> Result { - let path = genesis_path(network_id)?; - std::fs::read_to_string(&path).map_err(|e| GenesisCodeError::ReadError{path, cause: e}) -}