1use 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, LOG_TARGET};
29
30mod errors;
31use self::errors::GenesisConfigError;
32
33#[cfg(test)]
34mod tests;
35
36#[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#[derive(Debug, Clone, serde::Deserialize)]
54#[serde(deny_unknown_fields)]
55struct GenericAccountConfig {
56 name: String,
57 path: PathBuf,
58}
59
60#[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 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 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 #[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 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 let mut faucet_accounts = IndexMap::<TokenSymbolStr, Account>::new();
141
142 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 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 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 for (index, WalletConfig { name, account_type, auth_scheme, assets }) in
187 wallet_configs.into_iter().enumerate()
188 {
189 debug!(
190 target: LOG_TARGET,
191 "Adding wallet account",
192 account.index = index,
193 account.assets.count = assets.len()
194 );
195
196 if Path::new(&name).file_name() != Some(name.as_ref()) {
198 return Err(GenesisConfigError::InvalidAccountFileName { name });
199 }
200
201 let auth_scheme = auth_scheme
202 .as_deref()
203 .map(AuthScheme::from_str)
204 .transpose()?
205 .unwrap_or(AuthScheme::Falcon512Poseidon2);
206
207 let mut rng = genesis_rng()?;
208 let secret_key = AuthSecretKey::with_scheme_and_rng(auth_scheme, &mut rng)?;
209 let auth = Approver::from(&secret_key.public_key());
210 let init_seed: [u8; 32] = rng.random();
211
212 let mut wallet_account = create_basic_wallet(init_seed, auth, account_type.into())?;
213
214 let wallet_assets =
216 prepare_fungible_asset_update(assets, &faucet_accounts, &mut faucet_issuance)?;
217 for asset in wallet_assets {
218 wallet_account.vault_mut().add_asset(asset)?;
219 }
220
221 wallet_account.set_nonce(ONE)?;
230
231 debug_assert_eq!(wallet_account.nonce(), ONE);
232
233 secrets.push((format!("{name}.mac"), wallet_account.id(), Some(secret_key)));
234
235 wallet_accounts.push(wallet_account);
236 }
237
238 let mut all_accounts = Vec::<Account>::new();
239 for (symbol, mut faucet_account) in faucet_accounts {
241 let faucet_id = faucet_account.id();
242 let total_issuance = faucet_issuance.get(&faucet_id).copied().unwrap_or_default();
244
245 if total_issuance != 0 {
246 let current_faucet = FungibleFaucet::try_from(faucet_account.storage())?;
247 let new_token_supply = AssetAmount::new(total_issuance)?;
248 let max_supply = current_faucet.max_supply().as_u64();
249 if max_supply < total_issuance {
250 return Err(GenesisConfigError::MaxIssuanceExceeded {
251 max_supply,
252 symbol: symbol.clone(),
253 total_issuance,
254 });
255 }
256 let updated_faucet = current_faucet.with_token_supply(new_token_supply)?;
257 let slot = updated_faucet.token_config_slot_value();
258 faucet_account.storage_mut().set_item(slot.name(), slot.value())?;
259 debug!(
260 target: LOG_TARGET,
261 "Setting faucet account issuance",
262 account.id = faucet_id,
263 asset.symbol = symbol.to_string(),
264 asset.amount = total_issuance
265 );
266 } else {
267 debug!(
268 target: LOG_TARGET,
269 "No wallet references faucet asset",
270 account.id = faucet_id,
271 asset.symbol = symbol.to_string()
272 );
273 }
274
275 if faucet_id != native_faucet_account_id {
276 faucet_account.set_nonce(ONE)?;
277 }
278
279 all_accounts.push(faucet_account);
280 }
281 all_accounts.push(funding_account);
282
283 all_accounts.extend(wallet_accounts);
285
286 all_accounts.extend(file_loaded_accounts);
288
289 let mut account_ids = std::collections::HashSet::new();
290 for account in &all_accounts {
291 if !account_ids.insert(account.id()) {
292 return Err(GenesisConfigError::DuplicateAccount { account_id: account.id() });
293 }
294 }
295
296 let mut file_names: Vec<&str> = secrets.iter().map(|(name, ..)| name.as_str()).collect();
298 file_names.sort_unstable();
299 if let Some(pair) = file_names.windows(2).find(|pair| pair[0] == pair[1]) {
300 return Err(GenesisConfigError::DuplicateAccountFileName { name: pair[0].to_string() });
301 }
302 names.extend(secrets.iter().map(|(name, id, _)| (*id, name.clone())));
303
304 Ok((
305 GenesisState {
306 fee_parameters,
307 accounts: all_accounts,
308 timestamp,
309 validator_config,
310 protocol_config,
311 },
312 GenesisAccountMetadata { names, secrets },
313 ))
314 }
315}
316
317#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
322#[serde(deny_unknown_fields)]
323pub struct FungibleFaucetConfig {
324 symbol: TokenSymbolStr,
325 decimals: u8,
326 max_supply: u64,
331 #[serde(default)]
332 account_type: AccountTypeConfig,
333}
334
335impl FungibleFaucetConfig {
336 fn build_account(self) -> Result<(Account, RpoSecretKey), GenesisConfigError> {
338 let FungibleFaucetConfig {
339 symbol,
340 decimals,
341 max_supply,
342 account_type,
343 } = self;
344 let mut rng = genesis_rng()?;
345 let secret_key = RpoSecretKey::with_rng(&mut rng);
346 let auth = AuthSingleSig::new(Approver::new(
347 secret_key.public_key().into(),
348 AuthScheme::Falcon512Poseidon2,
349 ));
350 let init_seed: [u8; 32] = rng.random();
351
352 let faucet = FungibleFaucet::builder()
353 .name(
354 TokenName::new(&symbol.to_string())
355 .expect("token symbol fits within token name byte limit"),
356 )
357 .symbol(symbol.as_ref().clone())
358 .decimals(decimals)
359 .max_supply(AssetAmount::new(max_supply)?)
360 .build()?;
361
362 let faucet_account = AccountBuilder::new(init_seed)
364 .account_type(account_type.into())
365 .with_component(auth)
366 .with_component(faucet)
367 .with_components(
368 TokenPolicyManager::builder()
369 .active_mint_policy(MintPolicy::allow_all())
370 .active_burn_policy(BurnPolicy::allow_all())
371 .build(),
372 )
373 .build()?;
374
375 debug_assert_eq!(faucet_account.nonce(), Felt::ZERO);
376
377 Ok((faucet_account, secret_key))
378 }
379}
380
381#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
386#[serde(deny_unknown_fields)]
387pub struct WalletConfig {
388 name: String,
390 #[serde(default)]
391 account_type: AccountTypeConfig,
392 #[serde(default)]
395 auth_scheme: Option<String>,
396 assets: Vec<AssetEntry>,
397}
398
399#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
400struct AssetEntry {
401 symbol: TokenSymbolStr,
402 amount: u64,
404}
405
406#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, Default)]
412pub enum AccountTypeConfig {
413 #[serde(alias = "public")]
415 Public,
416 #[serde(alias = "private")]
418 #[default]
419 Private,
420}
421
422impl From<AccountTypeConfig> for AccountType {
423 fn from(value: AccountTypeConfig) -> AccountType {
424 match value {
425 AccountTypeConfig::Public => AccountType::Public,
426 AccountTypeConfig::Private => AccountType::Private,
427 }
428 }
429}
430
431#[derive(Debug, Clone)]
435pub struct AccountFileWithName {
436 pub name: String,
437 pub account_file: AccountFile,
438}
439
440#[derive(Debug, Clone)]
442pub struct GenesisAccountMetadata {
443 pub names: IndexMap<AccountId, String>,
444 pub secrets: Vec<(String, AccountId, Option<AuthSecretKey>)>,
446}
447
448impl GenesisAccountMetadata {
449 pub fn as_account_files(
451 &self,
452 genesis_state: &GenesisState,
453 ) -> impl Iterator<Item = Result<AccountFileWithName, GenesisConfigError>> + '_ {
454 let account_lut = genesis_state
455 .accounts
456 .iter()
457 .map(|account| (account.id(), account.clone()))
458 .collect::<IndexMap<AccountId, Account>>();
459 self.secrets.iter().cloned().map(move |(name, account_id, secret_key)| {
460 let account = account_lut
461 .get(&account_id)
462 .ok_or(GenesisConfigError::MissingGenesisAccount { account_id })?;
463 let auth_secret_keys = secret_key.into_iter().collect();
464 let account_file = AccountFile::new(account.clone(), auth_secret_keys);
465 Ok(AccountFileWithName { name, account_file })
466 })
467 }
468}
469
470fn genesis_rng() -> Result<ChaCha20Rng, GenesisConfigError> {
475 ChaCha20Rng::try_from_rng(&mut SysRng).map_err(GenesisConfigError::Entropy)
476}
477
478fn prepare_fungible_asset_update(
483 assets: impl IntoIterator<Item = AssetEntry>,
484 faucets: &IndexMap<TokenSymbolStr, Account>,
485 faucet_issuance: &mut IndexMap<AccountId, u64>,
486) -> Result<Vec<Asset>, GenesisConfigError> {
487 assets
488 .into_iter()
489 .map(|AssetEntry { amount, symbol }| {
490 let faucet_account = faucets.get(&symbol).ok_or_else(|| {
491 GenesisConfigError::MissingFaucetDefinition { symbol: symbol.clone() }
492 })?;
493 let faucet_id = faucet_account.id();
494
495 let issuance: &mut u64 = faucet_issuance.entry(faucet_id).or_default();
496 debug!(
497 target: LOG_TARGET,
498 "Updating faucet issuance",
499 account.id = faucet_id,
500 asset.symbol = symbol.to_string(),
501 asset.amount = amount
502 );
503 issuance
504 .checked_add_assign(&amount)
505 .map_err(|_| GenesisConfigError::IssuanceOverflow)?;
506
507 Ok(FungibleAsset::new(faucet_id, amount)?.into())
508 })
509 .collect()
510}
511
512#[derive(Debug, Clone, PartialEq)]
517pub struct TokenSymbolStr {
518 raw: String,
520 encoded: TokenSymbol,
522}
523
524impl AsRef<TokenSymbol> for TokenSymbolStr {
525 fn as_ref(&self) -> &TokenSymbol {
526 &self.encoded
527 }
528}
529
530impl std::fmt::Display for TokenSymbolStr {
531 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
532 f.write_str(&self.raw)
533 }
534}
535
536impl FromStr for TokenSymbolStr {
537 type Err = TokenSymbolError;
539 fn from_str(s: &str) -> Result<Self, Self::Err> {
540 Ok(Self {
541 encoded: TokenSymbol::new(s)?,
542 raw: s.to_string(),
543 })
544 }
545}
546
547impl Eq for TokenSymbolStr {}
548
549impl From<TokenSymbolStr> for TokenSymbol {
550 fn from(value: TokenSymbolStr) -> Self {
551 value.encoded
552 }
553}
554
555impl From<TokenSymbol> for TokenSymbolStr {
556 fn from(symbol: TokenSymbol) -> Self {
557 let raw = symbol.to_string();
558 Self { raw, encoded: symbol }
559 }
560}
561
562impl Ord for TokenSymbolStr {
563 fn cmp(&self, other: &Self) -> Ordering {
564 self.raw.cmp(&other.raw)
565 }
566}
567
568impl PartialOrd for TokenSymbolStr {
569 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
570 Some(self.cmp(other))
571 }
572}
573
574impl std::hash::Hash for TokenSymbolStr {
575 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
576 self.raw.hash::<H>(state);
577 }
578}
579
580impl Serialize for TokenSymbolStr {
581 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
582 where
583 S: serde::Serializer,
584 {
585 serializer.serialize_str(&self.raw)
586 }
587}
588
589impl<'de> Deserialize<'de> for TokenSymbolStr {
590 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
591 where
592 D: serde::Deserializer<'de>,
593 {
594 deserializer.deserialize_str(TokenSymbolVisitor)
595 }
596}
597
598use serde::de::Visitor;
599
600struct TokenSymbolVisitor;
601
602impl Visitor<'_> for TokenSymbolVisitor {
603 type Value = TokenSymbolStr;
604
605 fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
606 formatter.write_str("1 to 6 uppercase ascii letters")
607 }
608
609 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
610 where
611 E: serde::de::Error,
612 {
613 let encoded = TokenSymbol::new(v).map_err(|e| E::custom(format!("{e}")))?;
614 let raw = v.to_string();
615 Ok(TokenSymbolStr { raw, encoded })
616 }
617}