1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use fuel_core_interfaces::common::{
    fuel_tx::ConsensusParameters,
    fuel_types::{
        Address,
        AssetId,
    },
    prelude::{
        Hasher,
        MerkleRoot,
    },
};
use itertools::Itertools;
use rand::{
    rngs::StdRng,
    SeedableRng,
};
use serde::{
    Deserialize,
    Serialize,
};
use serde_with::skip_serializing_none;

use std::{
    io::ErrorKind,
    path::PathBuf,
    str::FromStr,
};

use crate::GenesisCommitment;

use super::{
    coin::CoinConfig,
    state::StateConfig,
};

pub const LOCAL_TESTNET: &str = "local_testnet";
pub const TESTNET_INITIAL_BALANCE: u64 = 10_000_000;

// TODO: Remove not consensus/network fields from `ChainConfig` or create a new config only
//  for consensus/network fields.
#[skip_serializing_none]
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct ChainConfig {
    pub chain_name: String,
    pub block_production: BlockProduction,
    pub block_gas_limit: u64,
    #[serde(default)]
    pub initial_state: Option<StateConfig>,
    pub transaction_parameters: ConsensusParameters,
}

impl Default for ChainConfig {
    fn default() -> Self {
        Self {
            chain_name: "local".into(),
            block_production: BlockProduction::ProofOfAuthority {
                trigger: fuel_poa_coordinator::Trigger::Instant,
            },
            block_gas_limit: ConsensusParameters::DEFAULT.max_gas_per_tx * 10, /* TODO: Pick a sensible default */
            transaction_parameters: ConsensusParameters::DEFAULT,
            initial_state: None,
        }
    }
}

impl ChainConfig {
    pub const BASE_ASSET: AssetId = AssetId::zeroed();

    pub fn local_testnet() -> Self {
        // endow some preset accounts with an initial balance
        tracing::info!("Initial Accounts");
        let mut rng = StdRng::seed_from_u64(10);
        let initial_coins = (0..5)
            .map(|_| {
                let secret = fuel_core_interfaces::common::fuel_crypto::SecretKey::random(
                    &mut rng,
                );
                let address = Address::from(*secret.public_key().hash());
                tracing::info!(
                    "PrivateKey({:#x}), Address({:#x}), Balance({})",
                    secret,
                    address,
                    TESTNET_INITIAL_BALANCE
                );
                CoinConfig {
                    tx_id: None,
                    output_index: None,
                    block_created: None,
                    maturity: None,
                    owner: address,
                    amount: TESTNET_INITIAL_BALANCE,
                    asset_id: Default::default(),
                }
            })
            .collect_vec();

        Self {
            chain_name: LOCAL_TESTNET.to_string(),
            initial_state: Some(StateConfig {
                coins: Some(initial_coins),
                ..StateConfig::default()
            }),
            ..Default::default()
        }
    }
}

impl FromStr for ChainConfig {
    type Err = std::io::Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            LOCAL_TESTNET => Ok(Self::local_testnet()),
            s => {
                // Attempt to load chain config from path
                let path = PathBuf::from(s.to_string());
                let contents = std::fs::read(path)?;
                serde_json::from_slice(&contents).map_err(|e| {
                    std::io::Error::new(
                        ErrorKind::InvalidData,
                        anyhow::Error::new(e).context(format!(
                            "an error occurred while loading the chain config file {}",
                            s
                        )),
                    )
                })
            }
        }
    }
}

impl GenesisCommitment for ChainConfig {
    fn root(&mut self) -> anyhow::Result<MerkleRoot> {
        // TODO: Hash settlement configuration, consensus block production
        let config_hash = *Hasher::default()
            .chain(self.block_gas_limit.to_be_bytes())
            .chain(self.transaction_parameters.root()?)
            .chain(self.chain_name.as_bytes())
            .finalize();

        Ok(config_hash)
    }
}

impl GenesisCommitment for ConsensusParameters {
    fn root(&mut self) -> anyhow::Result<MerkleRoot> {
        // TODO: Define hash algorithm for `ConsensusParameters`
        let params_hash = Hasher::default()
            .chain(bincode::serialize(&self)?)
            .finalize();

        Ok(params_hash.into())
    }
}

/// Block production mode and settings
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum BlockProduction {
    /// Proof-of-authority modes
    ProofOfAuthority {
        #[serde(flatten)]
        trigger: fuel_poa_coordinator::Trigger,
    },
    // TODO:
    // RoundRobin,
    // ProofOfStake,
}