Skip to content

Commit

Permalink
feat: dynamically generate erigon config
Browse files Browse the repository at this point in the history
  • Loading branch information
vcastellm committed Sep 18, 2024
1 parent 002612c commit 396a7ab
Show file tree
Hide file tree
Showing 4 changed files with 197 additions and 17 deletions.
2 changes: 2 additions & 0 deletions crates/cdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }


cdk-config = { path = "../cdk-config" }
serde.workspace = true
serde_json.workspace = true
69 changes: 69 additions & 0 deletions crates/cdk/src/allocs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{self, Value};
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
use std::path::Path;

#[derive(Serialize, Deserialize, Debug)]
struct Input {
#[serde(rename = "contractName", skip_serializing_if = "Option::is_none")]
contract_name: Option<String>,
#[serde(rename = "accountName", skip_serializing_if = "Option::is_none")]
account_name: Option<String>,
balance: String,
nonce: String,
address: String,
#[serde(skip_serializing_if = "Option::is_none")]
bytecode: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
storage: Option<HashMap<String, String>>,
}

#[derive(Serialize, Deserialize, Debug)]
struct Wrapper {
root: String,
genesis: Vec<Input>,
}

#[derive(Serialize, Deserialize, Debug)]
struct Output {
#[serde(rename = "contractName")]
contract_name: Option<String>,
balance: Option<String>,
nonce: Option<String>,
code: Option<String>,
storage: Option<Value>,
}

pub fn render_allocs(genesis_file_path: &str) -> Result<String> {
let path = Path::new(genesis_file_path);
let display = path.display();

let mut file = File::open(&path).with_context(|| format!("couldn't open {}", display))?;

let mut data = String::new();
file.read_to_string(&mut data)
.with_context(|| format!("couldn't read {}", display))?;

let wrapper: Wrapper = serde_json::from_str(&data)
.with_context(|| format!("couldn't parse JSON from {}", display))?;

let mut outputs: Vec<Output> = Vec::new();

for input in wrapper.genesis {
let output = Output {
contract_name: input.contract_name,
balance: Some(input.balance),
nonce: Some(input.nonce),
code: input.bytecode,
storage: input.storage.map(|s| serde_json::to_value(s).unwrap()),
};
outputs.push(output);
}

outputs.sort_by(|a, b| a.contract_name.cmp(&b.contract_name));

serde_json::to_string_pretty(&outputs).with_context(|| "couldn't serialize outputs to JSON")
}
110 changes: 110 additions & 0 deletions crates/cdk/src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
use std::fs;

pub fn render_config() -> anyhow::Result<()> {
let name = "kurtosis".to_string();
let chain_id = 10101;

let res = crate::allocs::render_allocs("./tmp/cdk/genesis/genesis.json")?;

// Write the three files to disk
fs::write(format!("dynamic-{}-allocs.json", name.clone()), res)?;
fs::write(
format!("dynamic-{}-chainspec.json", name.clone()),
render_chainspec(name.clone(), chain_id),
)?;
fs::write(
format!("dynamic-{}-conf.json", name.clone()),
render_conf(name.clone(), 1000000000000000000),
)?;
fs::write(
format!("dynamic-{}.toml", name.clone()),
render_yaml(name.clone(), chain_id),
)?;

Ok(())
}

fn render_chainspec(name: String, chain_id: i64) -> String {
format!(
r#"
{{
"ChainName": "dynamic-{}",
"chainId": {},
"consensus": "ethash",
"homesteadBlock": 0,
"daoForkBlock": 0,
"eip150Block": 0,
"eip155Block": 0,
"byzantiumBlock": 0,
"constantinopleBlock": 0,
"petersburgBlock": 0,
"istanbulBlock": 0,
"muirGlacierBlock": 0,
"berlinBlock": 0,
"londonBlock": 9999999999999999999999999999999999999999999999999,
"arrowGlacierBlock": 9999999999999999999999999999999999999999999999999,
"grayGlacierBlock": 9999999999999999999999999999999999999999999999999,
"terminalTotalDifficulty": 58750000000000000000000,
"terminalTotalDifficultyPassed": false,
"shanghaiTime": 9999999999999999999999999999999999999999999999999,
"cancunTime": 9999999999999999999999999999999999999999999999999,
"pragueTime": 9999999999999999999999999999999999999999999999999,
"ethash": {{}}
}}
"#,
name, chain_id
)
}

fn render_conf(root: String, gas_limit: i64) -> String {
format!(
r#"
{{
"root": "{:?}",
"timestamp": 0,
"gasLimit": {:?},
"difficulty": 0
}}
"#,
root, gas_limit
)
}

// render_config renders the configuration file for the Erigon node.
fn render_yaml(name: String, chain_id: i64) -> String {
format!(
r#"
datadir: ./data/dynamic-{}
chain: dynamic-{}
http: true
private.api.addr: localhost:9092
zkevm.l2-chain-id: {}
zkevm.l2-sequencer-rpc-url: http://localhost:32825/
zkevm.l2-datastreamer-url: localhost:32835
zkevm.l1-chain-id: 271828
zkevm.l1-rpc-url: http://localhost:32809/
zkevm.address-sequencer: "0x5b06837A43bdC3dD9F114558DAf4B26ed49842Ed"
zkevm.address-zkevm: "0x2F50ef6b8e8Ee4E579B17619A92dE3E2ffbD8AD2"
zkevm.address-admin: "0xE34aaF64b29273B7D567FCFc40544c014EEe9970"
zkevm.address-rollup: "0x1Fe038B54aeBf558638CA51C91bC8cCa06609e91"
zkevm.address-ger-manager: "0x1f7ad7caA53e35b4f0D138dC5CBF91aC108a2674"
zkevm.l1-rollup-id: 1
zkevm.l1-matic-contract-address: "0x5FbDB2315678afecb367f032d93F642f64180aa3"
zkevm.l1-first-block: 23
zkevm.rpc-ratelimit: 250
txpool.disable: true
torrent.port: 42070
zkevm.datastream-version: 2
externalcl: true
http.api: [eth, debug, net, trace, web3, erigon, zkevm]
http.addr: 0.0.0.0
http.vhosts: any
http.corsdomain: any
ws: true
"#,
name, name, chain_id
)
}
33 changes: 16 additions & 17 deletions crates/cdk/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;

pub mod allocs;
mod cli;
mod config;
mod logging;

const CDK_CLIENT_PATH: &str = "cdk-node";
const CDK_ERIGON_PATH: &str = "cdk-erigon";
const CDK_CLIENT_BIN: &str = "cdk-node";
const CDK_ERIGON_BIN: &str = "cdk-erigon";

fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
Expand Down Expand Up @@ -51,9 +53,11 @@ pub fn node(config_path: PathBuf) -> anyhow::Result<()> {
};
let config: Arc<Config> = Arc::new(toml::from_str(&toml_str)?);

let mut bin_path = env::var("CARGO_MANIFEST_DIR").unwrap_or(CDK_CLIENT_PATH.into());
if bin_path != CDK_CLIENT_PATH {
bin_path = format!("{}/../../{}", bin_path, CDK_CLIENT_PATH);
// This is to find the erigon binary when running in development mode
// otherwise it will use system path
let mut bin_path = env::var("CARGO_MANIFEST_DIR").unwrap_or(CDK_CLIENT_BIN.into());
if bin_path != CDK_CLIENT_BIN {
bin_path = format!("{}/../../{}", bin_path, CDK_CLIENT_BIN);
}

// Run the node passing the config file path as argument
Expand Down Expand Up @@ -91,23 +95,18 @@ pub fn node(config_path: PathBuf) -> anyhow::Result<()> {
/// This is the main erigon entrypoint.
/// This function starts everything needed to run an Erigon node.
pub fn erigon(config_path: PathBuf) -> anyhow::Result<()> {
config::render_config()?;

// Load the configuration file
let _config: Arc<Config> = Arc::new(toml::from_str(&std::fs::read_to_string(
config_path.clone(),
)?)?);

let mut bin_path = env::var("CARGO_MANIFEST_DIR").unwrap_or(CDK_ERIGON_PATH.into());
if bin_path != CDK_ERIGON_PATH {
bin_path = format!("{}/../../{}", bin_path, CDK_ERIGON_PATH);
}

let mut command = Command::new(bin_path);

// TODO: 1. Prepare erigon config files or flags

command.args(&["--config", config_path.to_str().unwrap()]);

let output = command.execute_output().unwrap();
// Run cdk-erigon in system path
let output = Command::new(CDK_ERIGON_BIN)
.args(&["--config", config_path.to_str().unwrap()])
.execute_output()
.unwrap();

if let Some(exit_code) = output.status.code() {
if exit_code == 0 {
Expand Down

0 comments on commit 396a7ab

Please sign in to comment.