Skip to main content

miden_node_store/genesis/config/
mod.rs

1//! Additional accounts for the genesis state.
2
3use std::cmp::Ordering;
4use std::path::{Path, PathBuf};
5use std::str::FromStr;
6
7use indexmap::IndexMap;
8use miden_node_tracing::debug;
9use miden_objects::account_file::AccountFile;
10use miden_protocol::account::auth::{AuthScheme, AuthSecretKey};
11use miden_protocol::account::{Account, AccountBuilder, AccountId, AccountType};
12use miden_protocol::asset::{Asset, AssetAmount, AssetId, FungibleAsset, TokenSymbol};
13use miden_protocol::block::{FeeParameters, ValidatorConfig};
14use miden_protocol::crypto::dsa::falcon512_poseidon2::SecretKey as RpoSecretKey;
15use miden_protocol::errors::TokenSymbolError;
16use miden_protocol::protocol_config::ProtocolConfig;
17use miden_protocol::{Felt, ONE};
18use miden_standards::account::auth::{Approver, AuthSingleSig};
19use miden_standards::account::faucets::{FungibleFaucet, TokenName};
20use miden_standards::account::policies::{BurnPolicy, MintPolicy, TokenPolicyManager};
21use miden_standards::account::wallets::create_basic_wallet;
22use rand::distr::weighted::Weight;
23use rand::rngs::SysRng;
24use rand::{RngExt, SeedableRng};
25use rand_chacha::ChaCha20Rng;
26use serde::{Deserialize, Serialize};
27
28use crate::GenesisState;
29
30mod errors;
31use self::errors::GenesisConfigError;
32
33#[cfg(test)]
34mod tests;
35
36/// Required inputs for the genesis state.
37#[derive(Debug, Clone)]
38pub struct GenesisInputs {
39    pub native_faucet: Account,
40    pub funding_account: Account,
41    pub fee_parameters: FeeParameters,
42    pub timestamp: u32,
43    pub validator_config: ValidatorConfig,
44}
45
46// GENESIS CONFIG
47// ================================================================================================
48
49/// An account loaded from a `.mac` file (path relative to genesis config directory).
50///
51/// Notice: Generic accounts are not validated (e.g. that their vault assets reference known
52/// faucets), leaving the responsibility of ensuring valid genesis state to the operator.
53#[derive(Debug, Clone, serde::Deserialize)]
54#[serde(deny_unknown_fields)]
55struct GenericAccountConfig {
56    name: String,
57    path: PathBuf,
58}
59
60/// Additional faucets, wallets, and account files to include in genesis.
61#[derive(Debug, Clone, Default, serde::Deserialize)]
62#[serde(deny_unknown_fields)]
63pub struct GenesisConfig {
64    #[serde(default)]
65    wallet: Vec<WalletConfig>,
66    #[serde(default)]
67    fungible_faucet: Vec<FungibleFaucetConfig>,
68    #[serde(default)]
69    account: Vec<GenericAccountConfig>,
70    #[serde(skip)]
71    config_dir: PathBuf,
72}
73
74impl GenesisConfig {
75    /// Read additional accounts from a TOML file.
76    ///
77    /// The parent directory of `path` is used to resolve relative paths for account files
78    /// referenced in the configuration (e.g., `[[account]]` entries with `path` fields).
79    pub fn read_toml_file(path: &Path) -> Result<Self, GenesisConfigError> {
80        let toml_str = fs_err::read_to_string(path)
81            .map_err(|e| GenesisConfigError::ConfigFileRead(e, path.to_path_buf()))?;
82        let config_dir = path.parent().expect("config file path must have a parent directory");
83        Self::read_toml(&toml_str, config_dir)
84    }
85
86    /// Parse additional accounts and resolve file paths relative to `config_dir`.
87    fn read_toml(toml_str: &str, config_dir: &Path) -> Result<Self, GenesisConfigError> {
88        let mut config: Self = toml::from_str(toml_str)?;
89        if config.account.iter().any(|account| account.name.trim().is_empty()) {
90            return Err(GenesisConfigError::EmptyImportedAccountName);
91        }
92        config.config_dir = config_dir.to_path_buf();
93        Ok(config)
94    }
95
96    /// Build the genesis state from the required inputs and additional accounts.
97    ///
98    /// The genesis header commits to the validator set in `inputs`.
99    /// That set must sign every block after genesis.
100    ///
101    /// Also returns account names and the keys for generated accounts.
102    #[expect(clippy::too_many_lines)]
103    pub fn into_state(
104        self,
105        inputs: GenesisInputs,
106    ) -> Result<(GenesisState, GenesisAccountMetadata), GenesisConfigError> {
107        let GenesisInputs {
108            native_faucet,
109            funding_account,
110            fee_parameters,
111            timestamp,
112            validator_config,
113        } = inputs;
114        let GenesisConfig {
115            fungible_faucet: fungible_faucet_configs,
116            wallet: wallet_configs,
117            account: account_entries,
118            config_dir,
119        } = self;
120
121        let mut names = IndexMap::from([
122            (native_faucet.id(), "Native faucet".to_owned()),
123            (funding_account.id(), "Funding".to_owned()),
124        ]);
125
126        // Load account files from disk.
127        let file_loaded_accounts = account_entries
128            .into_iter()
129            .map(|acc| {
130                let full_path = config_dir.join(&acc.path);
131                let account_file = AccountFile::read(&full_path)
132                    .map_err(|e| GenesisConfigError::AccountFileRead(e, full_path.clone()))?;
133                names.insert(account_file.account().id(), acc.name);
134                Ok(account_file.into_parts().0)
135            })
136            .collect::<Result<Vec<_>, GenesisConfigError>>()?;
137
138        let mut wallet_accounts = Vec::<Account>::new();
139        // Every asset sitting in a wallet, has to reference a faucet for that asset
140        let mut faucet_accounts = IndexMap::<TokenSymbolStr, Account>::new();
141
142        // Keep the generated keys for account file exports.
143        let mut secrets = Vec::new();
144
145        let native_faucet_account_id = native_faucet.id();
146        let faucet = FungibleFaucet::try_from(&native_faucet).map_err(|_| {
147            GenesisConfigError::NativeFaucetNotFungible { account_id: native_faucet_account_id }
148        })?;
149        if funding_account.id().account_type() != AccountType::Public {
150            return Err(GenesisConfigError::FundingAccountNotPublic {
151                account_id: funding_account.id(),
152            });
153        }
154        for account in [&native_faucet, &funding_account] {
155            if account.nonce() == Felt::ZERO {
156                return Err(GenesisConfigError::UndeployedAccount { account_id: account.id() });
157            }
158        }
159
160        // Additional wallet allocations increase the imported supply. The funding account balance
161        // does not determine that supply.
162        let mut faucet_issuance = IndexMap::<AccountId, u64>::new();
163        faucet_issuance.insert(native_faucet_account_id, faucet.token_supply().as_u64());
164        faucet_accounts.insert(TokenSymbolStr::from(faucet.symbol().clone()), native_faucet);
165
166        // Setup additional fungible faucets from parameters
167        for fungible_faucet_config in fungible_faucet_configs {
168            let symbol = fungible_faucet_config.symbol.clone();
169            let (faucet_account, secret_key) = fungible_faucet_config.build_account()?;
170
171            if faucet_accounts.insert(symbol.clone(), faucet_account.clone()).is_some() {
172                return Err(GenesisConfigError::DuplicateFaucetDefinition { symbol });
173            }
174
175            secrets.push((
176                format!("faucet_{symbol}.mac", symbol = symbol.to_string().to_lowercase()),
177                faucet_account.id(),
178                Some(AuthSecretKey::Falcon512Poseidon2(secret_key)),
179            ));
180        }
181
182        let protocol_config =
183            ProtocolConfig::current(AssetId::new_fungible(native_faucet_account_id))?;
184
185        // Setup all wallet accounts, which reference the faucet's for their provided assets.
186        for (index, WalletConfig { name, account_type, auth_scheme, assets }) in
187            wallet_configs.into_iter().enumerate()
188        {
189            debug!(
190                "Adding wallet account",
191                account.index = index,
192                account.assets.count = assets.len()
193            );
194
195            // The name is joined onto the accounts directory, so it must be a plain file name.
196            if Path::new(&name).file_name() != Some(name.as_ref()) {
197                return Err(GenesisConfigError::InvalidAccountFileName { name });
198            }
199
200            let auth_scheme = auth_scheme
201                .as_deref()
202                .map(AuthScheme::from_str)
203                .transpose()?
204                .unwrap_or(AuthScheme::Falcon512Poseidon2);
205
206            let mut rng = genesis_rng()?;
207            let secret_key = AuthSecretKey::with_scheme_and_rng(auth_scheme, &mut rng)?;
208            let auth = Approver::from(&secret_key.public_key());
209            let init_seed: [u8; 32] = rng.random();
210
211            let mut wallet_account = create_basic_wallet(init_seed, auth, account_type.into())?;
212
213            // Add fungible assets and track the faucet adjustments per faucet/asset.
214            let wallet_assets =
215                prepare_fungible_asset_update(assets, &faucet_accounts, &mut faucet_issuance)?;
216            for asset in wallet_assets {
217                wallet_account.vault_mut().add_asset(asset)?;
218            }
219
220            // Force the account nonce to 1.
221            //
222            // By convention, a nonce of zero indicates a freshly generated local account that has
223            // yet to be deployed. An account is deployed onchain along with its first
224            // transaction which results in a non-zero nonce onchain.
225            //
226            // The genesis block is special in that accounts are "deployed" without transactions and
227            // therefore we need bump the nonce manually to uphold this invariant.
228            wallet_account.set_nonce(ONE)?;
229
230            debug_assert_eq!(wallet_account.nonce(), ONE);
231
232            secrets.push((format!("{name}.mac"), wallet_account.id(), Some(secret_key)));
233
234            wallet_accounts.push(wallet_account);
235        }
236
237        let mut all_accounts = Vec::<Account>::new();
238        // Set each faucet supply after all wallet allocations are known.
239        for (symbol, mut faucet_account) in faucet_accounts {
240            let faucet_id = faucet_account.id();
241            // The native supply includes the amount recorded in the imported faucet.
242            let total_issuance = faucet_issuance.get(&faucet_id).copied().unwrap_or_default();
243
244            if total_issuance != 0 {
245                let current_faucet = FungibleFaucet::try_from(faucet_account.storage())?;
246                let new_token_supply = AssetAmount::new(total_issuance)?;
247                let max_supply = current_faucet.max_supply().as_u64();
248                if max_supply < total_issuance {
249                    return Err(GenesisConfigError::MaxIssuanceExceeded {
250                        max_supply,
251                        symbol: symbol.clone(),
252                        total_issuance,
253                    });
254                }
255                let updated_faucet = current_faucet.with_token_supply(new_token_supply)?;
256                let slot = updated_faucet.token_config_slot_value();
257                faucet_account.storage_mut().set_item(slot.name(), slot.value())?;
258                debug!(
259                    "Setting faucet account issuance",
260                    account.id = faucet_id,
261                    asset.symbol = symbol.to_string(),
262                    asset.amount = total_issuance
263                );
264            } else {
265                debug!(
266                    "No wallet references faucet asset",
267                    account.id = faucet_id,
268                    asset.symbol = symbol.to_string()
269                );
270            }
271
272            if faucet_id != native_faucet_account_id {
273                faucet_account.set_nonce(ONE)?;
274            }
275
276            all_accounts.push(faucet_account);
277        }
278        all_accounts.push(funding_account);
279
280        // Ensure the faucets always precede the wallets referencing them
281        all_accounts.extend(wallet_accounts);
282
283        // Append file-loaded accounts as-is
284        all_accounts.extend(file_loaded_accounts);
285
286        let mut account_ids = std::collections::HashSet::new();
287        for account in &all_accounts {
288            if !account_ids.insert(account.id()) {
289                return Err(GenesisConfigError::DuplicateAccount { account_id: account.id() });
290            }
291        }
292
293        // Each generated account needs a distinct output file.
294        let mut file_names: Vec<&str> = secrets.iter().map(|(name, ..)| name.as_str()).collect();
295        file_names.sort_unstable();
296        if let Some(pair) = file_names.windows(2).find(|pair| pair[0] == pair[1]) {
297            return Err(GenesisConfigError::DuplicateAccountFileName { name: pair[0].to_string() });
298        }
299        names.extend(secrets.iter().map(|(name, id, _)| (*id, name.clone())));
300
301        Ok((
302            GenesisState {
303                fee_parameters,
304                accounts: all_accounts,
305                timestamp,
306                validator_config,
307                protocol_config,
308            },
309            GenesisAccountMetadata { names, secrets },
310        ))
311    }
312}
313
314// FUNGIBLE FAUCET CONFIG
315// ================================================================================================
316
317/// Represents a faucet with asset specific properties
318#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
319#[serde(deny_unknown_fields)]
320pub struct FungibleFaucetConfig {
321    symbol: TokenSymbolStr,
322    decimals: u8,
323    /// Max supply in full token units
324    ///
325    /// It will be converted internally to the smallest representable unit,
326    /// using based `10.powi(decimals)` as a multiplier.
327    max_supply: u64,
328    #[serde(default)]
329    account_type: AccountTypeConfig,
330}
331
332impl FungibleFaucetConfig {
333    /// Create a fungible faucet from a config entry
334    fn build_account(self) -> Result<(Account, RpoSecretKey), GenesisConfigError> {
335        let FungibleFaucetConfig {
336            symbol,
337            decimals,
338            max_supply,
339            account_type,
340        } = self;
341        let mut rng = genesis_rng()?;
342        let secret_key = RpoSecretKey::with_rng(&mut rng);
343        let auth = AuthSingleSig::new(Approver::new(
344            secret_key.public_key().into(),
345            AuthScheme::Falcon512Poseidon2,
346        ));
347        let init_seed: [u8; 32] = rng.random();
348
349        let faucet = FungibleFaucet::builder()
350            .name(
351                TokenName::new(&symbol.to_string())
352                    .expect("token symbol fits within token name byte limit"),
353            )
354            .symbol(symbol.as_ref().clone())
355            .decimals(decimals)
356            .max_supply(AssetAmount::new(max_supply)?)
357            .build()?;
358
359        // It's similar to `fn create_basic_fungible_faucet`, but we need to cover more cases.
360        let faucet_account = AccountBuilder::new(init_seed)
361            .account_type(account_type.into())
362            .with_component(auth)
363            .with_component(faucet)
364            .with_components(
365                TokenPolicyManager::builder()
366                    .active_mint_policy(MintPolicy::allow_all())
367                    .active_burn_policy(BurnPolicy::allow_all())
368                    .build(),
369            )
370            .build()?;
371
372        debug_assert_eq!(faucet_account.nonce(), Felt::ZERO);
373
374        Ok((faucet_account, secret_key))
375    }
376}
377
378// WALLET CONFIG
379// ================================================================================================
380
381/// Represents a wallet, containing a set of assets
382#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
383#[serde(deny_unknown_fields)]
384pub struct WalletConfig {
385    /// Stem of the account file written for this wallet.
386    name: String,
387    #[serde(default)]
388    account_type: AccountTypeConfig,
389    /// Signature scheme of the account's authentication component, named as [`AuthScheme`] writes
390    /// it. Defaults to `Falcon512Poseidon2`.
391    #[serde(default)]
392    auth_scheme: Option<String>,
393    assets: Vec<AssetEntry>,
394}
395
396#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
397struct AssetEntry {
398    symbol: TokenSymbolStr,
399    /// The amount of the given asset, in base units.
400    amount: u64,
401}
402
403// ACCOUNT TYPE CONFIG
404// ================================================================================================
405
406/// See the [full description](https://0xmiden.github.io/miden-protocol/account.html?highlight=Accoun#account-storage-mode)
407/// for details
408#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
409pub enum AccountTypeConfig {
410    /// A publicly stored account, lives on-chain.
411    #[serde(alias = "public")]
412    Public,
413    /// A private account, which must be known by interactors.
414    #[serde(alias = "private")]
415    #[default]
416    Private,
417}
418
419impl From<AccountTypeConfig> for AccountType {
420    fn from(value: AccountTypeConfig) -> AccountType {
421        match value {
422            AccountTypeConfig::Public => AccountType::Public,
423            AccountTypeConfig::Private => AccountType::Private,
424        }
425    }
426}
427
428// ACCOUNTS
429// ================================================================================================
430
431#[derive(Debug, Clone)]
432pub struct AccountFileWithName {
433    pub name: String,
434    pub account_file: AccountFile,
435}
436
437/// Account names and generated signing keys for genesis.
438#[derive(Debug, Clone)]
439pub struct GenesisAccountMetadata {
440    pub names: IndexMap<AccountId, String>,
441    // name, account, private key of the account, if it has one
442    pub secrets: Vec<(String, AccountId, Option<AuthSecretKey>)>,
443}
444
445impl GenesisAccountMetadata {
446    /// Export generated accounts with their signing keys.
447    pub fn as_account_files(
448        &self,
449        genesis_state: &GenesisState,
450    ) -> impl Iterator<Item = Result<AccountFileWithName, GenesisConfigError>> + '_ {
451        let account_lut = genesis_state
452            .accounts
453            .iter()
454            .map(|account| (account.id(), account.clone()))
455            .collect::<IndexMap<AccountId, Account>>();
456        self.secrets.iter().cloned().map(move |(name, account_id, secret_key)| {
457            let account = account_lut
458                .get(&account_id)
459                .ok_or(GenesisConfigError::MissingGenesisAccount { account_id })?;
460            let auth_secret_keys = secret_key.into_iter().collect();
461            let account_file = AccountFile::new(account.clone(), auth_secret_keys);
462            Ok(AccountFileWithName { name, account_file })
463        })
464    }
465}
466
467/// Creates a [`ChaCha20Rng`] seeded from the operating system's entropy source.
468///
469/// Unlike `rand::random()`, this returns an error instead of panicking when the entropy source
470/// fails, so genesis can abort before writing any account files.
471fn genesis_rng() -> Result<ChaCha20Rng, GenesisConfigError> {
472    ChaCha20Rng::try_from_rng(&mut SysRng).map_err(GenesisConfigError::Entropy)
473}
474
475// HELPERS
476// ================================================================================================
477
478/// Build wallet assets and add their amounts to each faucet's supply.
479fn prepare_fungible_asset_update(
480    assets: impl IntoIterator<Item = AssetEntry>,
481    faucets: &IndexMap<TokenSymbolStr, Account>,
482    faucet_issuance: &mut IndexMap<AccountId, u64>,
483) -> Result<Vec<Asset>, GenesisConfigError> {
484    assets
485        .into_iter()
486        .map(|AssetEntry { amount, symbol }| {
487            let faucet_account = faucets.get(&symbol).ok_or_else(|| {
488                GenesisConfigError::MissingFaucetDefinition { symbol: symbol.clone() }
489            })?;
490            let faucet_id = faucet_account.id();
491
492            let issuance: &mut u64 = faucet_issuance.entry(faucet_id).or_default();
493            debug!(
494                "Updating faucet issuance",
495                account.id = faucet_id,
496                asset.symbol = symbol.to_string(),
497                asset.amount = amount
498            );
499            issuance
500                .checked_add_assign(&amount)
501                .map_err(|_| GenesisConfigError::IssuanceOverflow)?;
502
503            Ok(FungibleAsset::new(faucet_id, amount)?.into())
504        })
505        .collect()
506}
507
508/// Wrapper type used for configuration representation.
509///
510/// Required since `Felt` does not implement `Hash` or `Eq`, but both are useful and necessary for a
511/// coherent model construction.
512#[derive(Debug, Clone, PartialEq)]
513pub struct TokenSymbolStr {
514    /// The raw representation, used for `Hash` and `Eq`.
515    raw: String,
516    /// Maintain the duality with the actual implementation.
517    encoded: TokenSymbol,
518}
519
520impl AsRef<TokenSymbol> for TokenSymbolStr {
521    fn as_ref(&self) -> &TokenSymbol {
522        &self.encoded
523    }
524}
525
526impl std::fmt::Display for TokenSymbolStr {
527    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528        f.write_str(&self.raw)
529    }
530}
531
532impl FromStr for TokenSymbolStr {
533    // note: we re-use the error type
534    type Err = TokenSymbolError;
535    fn from_str(s: &str) -> Result<Self, Self::Err> {
536        Ok(Self {
537            encoded: TokenSymbol::new(s)?,
538            raw: s.to_string(),
539        })
540    }
541}
542
543impl Eq for TokenSymbolStr {}
544
545impl From<TokenSymbolStr> for TokenSymbol {
546    fn from(value: TokenSymbolStr) -> Self {
547        value.encoded
548    }
549}
550
551impl From<TokenSymbol> for TokenSymbolStr {
552    fn from(symbol: TokenSymbol) -> Self {
553        let raw = symbol.to_string();
554        Self { raw, encoded: symbol }
555    }
556}
557
558impl Ord for TokenSymbolStr {
559    fn cmp(&self, other: &Self) -> Ordering {
560        self.raw.cmp(&other.raw)
561    }
562}
563
564impl PartialOrd for TokenSymbolStr {
565    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
566        Some(self.cmp(other))
567    }
568}
569
570impl std::hash::Hash for TokenSymbolStr {
571    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
572        self.raw.hash::<H>(state);
573    }
574}
575
576impl Serialize for TokenSymbolStr {
577    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
578    where
579        S: serde::Serializer,
580    {
581        serializer.serialize_str(&self.raw)
582    }
583}
584
585impl<'de> Deserialize<'de> for TokenSymbolStr {
586    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
587    where
588        D: serde::Deserializer<'de>,
589    {
590        deserializer.deserialize_str(TokenSymbolVisitor)
591    }
592}
593
594use serde::de::Visitor;
595
596struct TokenSymbolVisitor;
597
598impl Visitor<'_> for TokenSymbolVisitor {
599    type Value = TokenSymbolStr;
600
601    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
602        formatter.write_str("1 to 6 uppercase ascii letters")
603    }
604
605    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
606    where
607        E: serde::de::Error,
608    {
609        let encoded = TokenSymbol::new(v).map_err(|e| E::custom(format!("{e}")))?;
610        let raw = v.to_string();
611        Ok(TokenSymbolStr { raw, encoded })
612    }
613}