Skip to main content

rootchain_core/
genesis.rs

1#[cfg(feature = "std")]
2use crate::types::{Address, Balance, Block, BlockHeader, Hash, Signature, Timestamp};
3#[cfg(feature = "std")]
4use serde::{Deserialize, Serialize};
5#[cfg(feature = "std")]
6use std::fs;
7#[cfg(feature = "std")]
8use std::path::Path;
9
10#[cfg(feature = "std")]
11#[derive(Debug, Clone, Serialize, Deserialize)]
12pub struct ValidatorInfo {
13    pub address: String, // String representation for json
14    pub name: String,
15}
16
17#[cfg(feature = "std")]
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct InitialBalance {
20    pub address: String,
21    pub balance: String, // string to avoid js limits
22}
23
24#[cfg(feature = "std")]
25#[derive(Debug, Clone, Serialize, Deserialize)]
26pub struct ChainParams {
27    pub block_time_secs: u64,
28    pub max_tx_per_block: u64,
29    pub max_tx_payload_bytes: u64,
30    pub min_fee: Balance,
31}
32
33#[cfg(feature = "std")]
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct GenesisConfig {
36    pub chain_id: u32,
37    pub chain_name: String,
38    pub timestamp: Timestamp,
39    pub validators: Vec<ValidatorInfo>,
40    pub initial_balances: Vec<InitialBalance>,
41    pub params: ChainParams,
42}
43
44#[cfg(feature = "std")]
45impl GenesisConfig {
46    pub fn load_from_file(path: &Path) -> Result<Self, std::io::Error> {
47        let content = fs::read_to_string(path)?;
48        let config: GenesisConfig = serde_json::from_str(&content)
49            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
50        Ok(config)
51    }
52
53    pub fn to_genesis_block(&self, state_root: Hash) -> Block {
54        Block {
55            header: BlockHeader {
56                height: 0,
57                prev_hash: Hash::zero(),
58                merkle_root: Hash::zero(),
59                state_root,
60                proposer: Address([0; 32]), // Dummy for genesis
61                timestamp: self.timestamp,
62                signature: Signature([0; 64]), // Genesis has no valid sig
63            },
64            transactions: vec![],
65        }
66    }
67}