Skip to main content

heika_state_transition/
config.rs

1//! ノードの設定ファイル(`config-network.properties`、`config-inflation.properties`、
2//! `config-finalization.properties`)から、状態遷移に要る値([`ChainConfig`])と、決め打ちのないネットワークの
3//! パラメーター([`network_parameters`])を読む。
4//!
5//! 読むのはテキストから。ファイルから読む口([`ChainConfig::load`]、[`load_network_parameters`])は、ノードの
6//! `resources` フォルダーを読んで渡すだけ。
7//!
8//! メインネットとテストネットの [`ChainConfig`] は、ファイルなしで使えるように決め打ちでも持つ
9//! ([`ChainConfig::mainnet`]、[`ChainConfig::testnet`])。`examples/builtin_config.rs` で、ファイルから作る。
10
11use std::collections::HashMap;
12use std::fmt;
13use std::fs;
14use std::path::Path;
15use std::time::Duration;
16
17use heika_block::finalization::proof::ProofParameters;
18use heika_core::address::Address;
19use heika_core::hash::Hash256;
20use heika_core::key::PublicKey;
21use heika_core::network::{ForkHeights, GenerationHashSeed, NetworkIdentifier, NetworkParameters};
22use heika_core::signature::Signature;
23use heika_transaction::NamespaceId;
24
25mod mainnet;
26mod testnet;
27
28const NETWORK_FILE: &str = "config-network.properties";
29const INFLATION_FILE: &str = "config-inflation.properties";
30const FINALIZATION_FILE: &str = "config-finalization.properties";
31
32fn read(resources: &Path, name: &str) -> Result<String, ConfigError> {
33    let path = resources.join(name);
34    fs::read_to_string(&path)
35        .map_err(|error| ConfigError(format!("{} を読めません: {error}", path.display())))
36}
37
38/// 設定が読めなかったわけ。
39#[derive(Debug)]
40pub struct ConfigError(String);
41
42impl fmt::Display for ConfigError {
43    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44        write!(f, "設定: {}", self.0)
45    }
46}
47
48impl std::error::Error for ConfigError {}
49
50/// `[セクション]` と `キー = 値` の並び。値の `'` は桁の区切りなので外す。
51struct Properties {
52    values: HashMap<(String, String), String>,
53    name: String,
54}
55
56impl Properties {
57    /// `name` は、読めないときに出す名前
58    fn parse(name: &str, text: &str) -> Self {
59        let mut values = HashMap::new();
60        let mut section = String::new();
61        for line in text.lines().map(str::trim) {
62            if line.is_empty() || line.starts_with('#') {
63                continue;
64            }
65            if let Some(name) = line
66                .strip_prefix('[')
67                .and_then(|line| line.strip_suffix(']'))
68            {
69                section = name.to_owned();
70            } else if let Some((key, value)) = line.split_once('=') {
71                values.insert(
72                    (section.clone(), key.trim().to_owned()),
73                    value.trim().replace('\'', ""),
74                );
75            }
76        }
77        Self {
78            values,
79            name: name.to_owned(),
80        }
81    }
82
83    fn get(&self, section: &str, key: &str) -> Result<&str, ConfigError> {
84        self.values
85            .get(&(section.to_owned(), key.to_owned()))
86            .map(String::as_str)
87            .ok_or_else(|| ConfigError(format!("{} に [{section}] {key} がありません", self.name)))
88    }
89
90    fn number(&self, section: &str, key: &str) -> Result<u64, ConfigError> {
91        let value = self.get(section, key)?;
92        let parsed = match value.strip_prefix("0x") {
93            Some(hex) => u64::from_str_radix(hex, 16),
94            None => value.parse(),
95        };
96        parsed.map_err(|_| ConfigError(format!("[{section}] {key} が数ではありません: {value}")))
97    }
98
99    /// 無ければ `None` の [`Properties::number`]
100    fn optional_number(&self, section: &str, key: &str) -> Result<Option<u64>, ConfigError> {
101        if self
102            .values
103            .contains_key(&(section.to_owned(), key.to_owned()))
104        {
105            self.number(section, key).map(Some)
106        } else {
107            Ok(None)
108        }
109    }
110
111    /// `,` で区切った数の並び。空なら空の並び(テストネットの `skipSecretLockExpirations =` など)
112    fn numbers(&self, section: &str, key: &str) -> Result<Vec<u64>, ConfigError> {
113        let value = self.get(section, key)?;
114        if value.is_empty() {
115            return Ok(Vec::new());
116        }
117        value
118            .split(',')
119            .map(|value| {
120                value
121                    .trim()
122                    .parse()
123                    .map_err(|_| ConfigError(format!("[{section}] {key} が数の並びではありません")))
124            })
125            .collect()
126    }
127
128    fn address(&self, section: &str, key: &str) -> Result<Address, ConfigError> {
129        let value = self.get(section, key)?;
130        value.parse().map_err(|_| {
131            ConfigError(format!(
132                "[{section}] {key} がアドレスではありません: {value}"
133            ))
134        })
135    }
136
137    fn size(&self, section: &str, key: &str) -> Result<usize, ConfigError> {
138        self.number(section, key)?
139            .try_into()
140            .map_err(|_| ConfigError(format!("[{section}] {key} が大きすぎます")))
141    }
142
143    /// `30s`、`1d` のような期間を、ブロックの数ではなく秒で読む
144    fn seconds(&self, section: &str, key: &str) -> Result<u64, ConfigError> {
145        Ok(self.milliseconds(section, key)? / 1000)
146    }
147
148    /// `300ms`、`30s` のような期間を、ミリ秒で読む
149    fn milliseconds(&self, section: &str, key: &str) -> Result<u64, ConfigError> {
150        let value = self.get(section, key)?;
151        let split = value
152            .find(|c: char| !c.is_ascii_digit())
153            .ok_or_else(|| ConfigError(format!("[{section}] {key} に単位がありません: {value}")))?;
154        let (number, unit) = value.split_at(split);
155        let number: u64 = number
156            .parse()
157            .map_err(|_| ConfigError(format!("[{section}] {key} が期間ではありません: {value}")))?;
158        let unit = match unit {
159            "ms" => 1,
160            "s" => 1000,
161            "m" => 60 * 1000,
162            "h" => 60 * 60 * 1000,
163            "d" => 24 * 60 * 60 * 1000,
164            _ => {
165                return Err(ConfigError(format!(
166                    "[{section}] {key} の単位が分かりません: {value}"
167                )));
168            }
169        };
170        Ok(number * unit)
171    }
172}
173
174/// ファイナライズの設定。config-network の `votingSetGrouping` と `minVoterBalance`、config-finalization から
175#[derive(Clone, Debug)]
176pub struct FinalizationConfig {
177    pub voting_set_grouping: u64,
178    pub min_voter_balance: u64,
179    /// 閾値は、重みの合計 × `threshold` / `size`
180    pub size: u64,
181    pub threshold: u64,
182    pub max_hashes_per_point: u64,
183    /// `stepDuration`(ミリ秒)。投票の段取りで、prevote と precommit を待つ長さの単位
184    pub step_duration: u64,
185    /// `prevoteBlocksMultiple`。prevote の最後の高さを、この倍数にそろえる
186    pub prevote_blocks_multiple: u64,
187    /// `enableRevoteOnBoot`。起動したときに、前に書いた投票状況を使わず、最後の確定の次のポイントで投票し直す。
188    /// 投票者がそろって起動し直すと、前のラウンドのメッセージを誰も持たずに止まるのを防ぐ(プライベートなネットワーク用)
189    pub enable_revote_on_boot: bool,
190    /// このエポックから、`ineligible_voters` を投票者から外す
191    pub treasury_reissuance_epoch: u32,
192    pub ineligible_voters: Vec<[u8; 24]>,
193}
194
195impl FinalizationConfig {
196    /// 証明を確かめるのに要る分
197    pub fn proof_parameters(&self) -> ProofParameters {
198        ProofParameters {
199            voting_set_grouping: self.voting_set_grouping,
200            size: self.size,
201            threshold: self.threshold,
202            max_hashes_per_point: self.max_hashes_per_point,
203        }
204    }
205
206    /// エポック `epoch` の最後の高さ([`ProofParameters::voting_set_end_height`])
207    pub fn voting_set_end_height(&self, epoch: u32) -> u64 {
208        self.proof_parameters().voting_set_end_height(epoch)
209    }
210}
211
212/// 高さによって替わるアドレス。`V1` は fork の高さより前に使う。
213#[derive(Clone, Copy, Debug)]
214pub struct HeightDependentAddress {
215    pub before: Address,
216    pub after: Address,
217    pub fork_height: u64,
218}
219
220impl HeightDependentAddress {
221    pub fn at(&self, height: u64) -> Address {
222        if height < self.fork_height {
223            self.before
224        } else {
225            self.after
226        }
227    }
228}
229
230/// 実行に要る、チェーンの設定。
231#[derive(Clone, Debug)]
232pub struct ChainConfig {
233    pub currency_mosaic_id: u64,
234    pub harvesting_mosaic_id: u64,
235    /// ブロックの間隔(秒)
236    pub block_generation_target_time: u64,
237    pub importance_grouping: u64,
238    pub importance_activity_percentage: u64,
239    pub max_difficulty_blocks: u64,
240    pub default_dynamic_fee_multiplier: u32,
241    pub total_chain_importance: u64,
242    pub min_harvester_balance: u64,
243    pub max_harvester_balance: u64,
244    pub harvest_beneficiary_percentage: u64,
245    pub harvest_network_percentage: u64,
246    pub harvest_network_fee_sink: HeightDependentAddress,
247    pub mosaic_rental_fee: u64,
248    pub mosaic_rental_fee_sink: HeightDependentAddress,
249    pub root_namespace_rental_fee_per_block: u64,
250    pub child_namespace_rental_fee: u64,
251    pub namespace_rental_fee_sink: HeightDependentAddress,
252    /// ネームスペースの猶予(ブロック)
253    pub namespace_grace_period: u64,
254    /// (この高さから、1ブロックあたりのインフレ)を高さの順に
255    pub inflation: Vec<(u64, u64)>,
256    /// シークレットロックの重なりを確かめない高さ(`skipSecretLockUniquenessChecks`)
257    pub skip_secret_lock_uniqueness_checks: Vec<u64>,
258    /// シークレットロックの期限切れを処理しない高さ(`skipSecretLockExpirations`)
259    pub skip_secret_lock_expirations: Vec<u64>,
260    /// シークレットロックの期限切れを、終わりの高さでなくても処理する高さ(`forceSecretLockExpirations`)
261    pub force_secret_lock_expirations: Vec<u64>,
262    /// この高さから、importance ブロックの投票の残高の合計を、そのエポックに鍵のあるアカウントだけで数える
263    /// (`totalVotingBalanceCalculationFix`)
264    pub total_voting_balance_calculation_fix: u64,
265    /// この高さから、VRF の鍵に使えない公開鍵はリンクできない(`vrfGammaSubgroupCheck`、catapult 1.0.3.11 から。
266    /// 設定に無ければフォークしない)
267    pub vrf_gamma_subgroup_check: u64,
268    /// `nemesisSignerPublicKey`。Nemesis のあとは、これで署名できない(`NemesisSink`)
269    pub nemesis_signer_public_key: PublicKey,
270    /// 国庫の再発行の高さでだけ、Nemesis の鍵で署名してよい署名(`[treasury_reissuance_transaction_signatures]`)
271    pub treasury_reissuance_transaction_signatures: Vec<Signature>,
272    /// 国庫の再発行の高さ(`treasuryReissuance`)。Revokable のモザイクもここから作れる
273    pub treasury_reissuance_height: u64,
274    /// 受け取った枝の最後のブロックの時刻の、今からの上限(ミリ秒、`maxBlockFutureTime`)
275    pub max_block_future_time: u64,
276    /// トランザクションの期限の、ブロックの時刻からの上限(ミリ秒)。ボンデッドは別
277    pub max_transaction_lifetime: u64,
278    pub max_bonded_transaction_lifetime: u64,
279    pub min_proof_size: u64,
280    pub max_proof_size: u64,
281    pub max_mosaic_atomic_units: u64,
282    pub max_namespace_depth: usize,
283    /// ルートの下に作れる子(孫も数える)の数(`maxChildNamespaces`)
284    pub max_child_namespaces: usize,
285    /// ネームスペースを持てる期間の、今の高さからの上限(ブロック、`maxNamespaceDuration`)
286    pub max_namespace_duration: u64,
287    /// Nemesis のあとは取れないルートの ID と、その直下に子を作れないもの(`reservedRootNamespaceNames`)
288    pub reserved_root_namespace_ids: Vec<u64>,
289    /// 1つのアカウントが持てるモザイクの種類(`maxMosaicsPerAccount`)
290    pub max_mosaics_per_account: usize,
291    /// モザイクを持てる期間の上限(ブロック、`maxMosaicDuration`)
292    pub max_mosaic_duration: u64,
293    pub max_mosaic_divisibility: u8,
294    /// ハッシュロックに預ける額(`lockedFundsPerAggregate`)
295    pub locked_funds_per_aggregate: u64,
296    pub max_multisig_depth: usize,
297    /// マルチシグの連署者の数と、1つのアカウントが連署できるマルチシグの数
298    pub max_cosignatories_per_account: usize,
299    pub max_cosigned_accounts_per_account: usize,
300    /// アカウントの制限の値の数(`maxAccountRestrictionValues`)
301    pub max_account_restriction_values: usize,
302    /// モザイクの制限の値の数(`maxMosaicRestrictionValues`)
303    pub max_mosaic_restriction_values: usize,
304    pub finalization: FinalizationConfig,
305}
306
307impl ChainConfig {
308    /// メインネットの、決め打ちの設定
309    pub fn mainnet() -> Self {
310        mainnet::config()
311    }
312
313    /// テストネットの、決め打ちの設定
314    pub fn testnet() -> Self {
315        testnet::config()
316    }
317
318    /// ノードの `resources` フォルダーの3つのファイルから読む。
319    pub fn load(resources: &Path) -> Result<Self, ConfigError> {
320        Self::parse(
321            &read(resources, NETWORK_FILE)?,
322            &read(resources, INFLATION_FILE)?,
323            &read(resources, FINALIZATION_FILE)?,
324        )
325    }
326
327    /// `config-network.properties`、`config-inflation.properties`、`config-finalization.properties` のテキストから読む。
328    pub fn parse(network: &str, inflation: &str, finalization: &str) -> Result<Self, ConfigError> {
329        let network = Properties::parse(NETWORK_FILE, network);
330        let inflation = Properties::parse(INFLATION_FILE, inflation);
331        let finalization = Properties::parse(FINALIZATION_FILE, finalization);
332        let chain = "chain";
333        let treasury = network.number("fork_heights", "treasuryReissuance")?;
334        let sink = |section: &str, key: &str| -> Result<HeightDependentAddress, ConfigError> {
335            Ok(HeightDependentAddress {
336                before: network.address(section, &format!("{key}V1"))?,
337                after: network.address(section, key)?,
338                fork_height: treasury,
339            })
340        };
341        let block_time = network.seconds(chain, "blockGenerationTargetTime")?;
342        let mosaic = "plugin:catapult.plugins.mosaic";
343        let namespace = "plugin:catapult.plugins.namespace";
344        let aggregate = "plugin:catapult.plugins.aggregate";
345        let lock_secret = "plugin:catapult.plugins.locksecret";
346        let multisig = "plugin:catapult.plugins.multisig";
347
348        let mut schedule = Vec::new();
349        for ((section, key), value) in &inflation.values {
350            if section != "inflation" {
351                continue;
352            }
353            let height = key
354                .strip_prefix("starting-at-height-")
355                .and_then(|height| height.parse().ok())
356                .ok_or_else(|| ConfigError(format!("インフレの高さが読めません: {key}")))?;
357            let amount = value
358                .parse()
359                .map_err(|_| ConfigError(format!("インフレの量が読めません: {value}")))?;
360            schedule.push((height, amount));
361        }
362        schedule.sort_unstable();
363
364        Ok(Self {
365            currency_mosaic_id: network.number(chain, "currencyMosaicId")?,
366            harvesting_mosaic_id: network.number(chain, "harvestingMosaicId")?,
367            block_generation_target_time: block_time,
368            importance_grouping: network.number(chain, "importanceGrouping")?,
369            importance_activity_percentage: network
370                .number(chain, "importanceActivityPercentage")?,
371            max_difficulty_blocks: network.number(chain, "maxDifficultyBlocks")?,
372            default_dynamic_fee_multiplier: network
373                .number(chain, "defaultDynamicFeeMultiplier")?
374                .try_into()
375                .map_err(|_| {
376                    ConfigError("defaultDynamicFeeMultiplier が大きすぎます".to_owned())
377                })?,
378            total_chain_importance: network.number(chain, "totalChainImportance")?,
379            min_harvester_balance: network.number(chain, "minHarvesterBalance")?,
380            max_harvester_balance: network.number(chain, "maxHarvesterBalance")?,
381            harvest_beneficiary_percentage: network
382                .number(chain, "harvestBeneficiaryPercentage")?,
383            harvest_network_percentage: network.number(chain, "harvestNetworkPercentage")?,
384            harvest_network_fee_sink: sink(chain, "harvestNetworkFeeSinkAddress")?,
385            mosaic_rental_fee: network.number(mosaic, "mosaicRentalFee")?,
386            mosaic_rental_fee_sink: sink(mosaic, "mosaicRentalFeeSinkAddress")?,
387            root_namespace_rental_fee_per_block: network
388                .number(namespace, "rootNamespaceRentalFeePerBlock")?,
389            child_namespace_rental_fee: network.number(namespace, "childNamespaceRentalFee")?,
390            namespace_rental_fee_sink: sink(namespace, "namespaceRentalFeeSinkAddress")?,
391            namespace_grace_period: network.seconds(namespace, "namespaceGracePeriodDuration")?
392                / block_time,
393            inflation: schedule,
394            skip_secret_lock_uniqueness_checks: network
395                .numbers("fork_heights", "skipSecretLockUniquenessChecks")?,
396            skip_secret_lock_expirations: network
397                .numbers("fork_heights", "skipSecretLockExpirations")?,
398            force_secret_lock_expirations: network
399                .numbers("fork_heights", "forceSecretLockExpirations")?,
400            total_voting_balance_calculation_fix: network
401                .number("fork_heights", "totalVotingBalanceCalculationFix")?,
402            vrf_gamma_subgroup_check: network
403                .optional_number("fork_heights", "vrfGammaSubgroupCheck")?
404                .unwrap_or(u64::MAX),
405            nemesis_signer_public_key: network
406                .get("network", "nemesisSignerPublicKey")?
407                .parse()
408                .map_err(|_| ConfigError("nemesisSignerPublicKey が読めません".to_owned()))?,
409            // catapult の `ExtractSectionKeysAsTypedVector` と同じく、値が true のキーだけ
410            treasury_reissuance_transaction_signatures: network
411                .values
412                .iter()
413                .filter(|((section, _), value)| {
414                    section == "treasury_reissuance_transaction_signatures" && *value == "true"
415                })
416                .map(|((_, signature), _)| {
417                    signature.parse().map_err(|_| {
418                        ConfigError(format!("国庫の再発行の署名が読めません: {signature}"))
419                    })
420                })
421                .collect::<Result<Vec<Signature>, _>>()
422                .map(|mut signatures| {
423                    // ファイルの順に依らないように並べる
424                    signatures.sort_unstable_by_key(|signature| signature.0);
425                    signatures
426                })?,
427            treasury_reissuance_height: treasury,
428            max_block_future_time: network.milliseconds(chain, "maxBlockFutureTime")?,
429            max_transaction_lifetime: network.seconds(chain, "maxTransactionLifetime")? * 1000,
430            max_bonded_transaction_lifetime: network
431                .seconds(aggregate, "maxBondedTransactionLifetime")?
432                * 1000,
433            min_proof_size: network.number(lock_secret, "minProofSize")?,
434            max_proof_size: network.number(lock_secret, "maxProofSize")?,
435            max_mosaic_atomic_units: network.number(chain, "maxMosaicAtomicUnits")?,
436            max_namespace_depth: network
437                .number(namespace, "maxNamespaceDepth")?
438                .try_into()
439                .map_err(|_| ConfigError("maxNamespaceDepth が大きすぎます".to_owned()))?,
440            max_child_namespaces: network
441                .number(namespace, "maxChildNamespaces")?
442                .try_into()
443                .map_err(|_| ConfigError("maxChildNamespaces が大きすぎます".to_owned()))?,
444            max_namespace_duration: network.seconds(namespace, "maxNamespaceDuration")?
445                / block_time,
446            reserved_root_namespace_ids: network
447                .get(namespace, "reservedRootNamespaceNames")?
448                .split(',')
449                .map(str::trim)
450                .filter(|name| !name.is_empty())
451                .map(|name| NamespaceId::generate(None, name.as_bytes()).0)
452                .collect(),
453            max_mosaics_per_account: network.size(mosaic, "maxMosaicsPerAccount")?,
454            max_mosaic_duration: network.seconds(mosaic, "maxMosaicDuration")? / block_time,
455            max_mosaic_divisibility: network
456                .number(mosaic, "maxMosaicDivisibility")?
457                .try_into()
458                .map_err(|_| ConfigError("maxMosaicDivisibility が大きすぎます".to_owned()))?,
459            locked_funds_per_aggregate: network.number(
460                "plugin:catapult.plugins.lockhash",
461                "lockedFundsPerAggregate",
462            )?,
463            max_multisig_depth: network.size(multisig, "maxMultisigDepth")?,
464            max_cosignatories_per_account: network.size(multisig, "maxCosignatoriesPerAccount")?,
465            max_cosigned_accounts_per_account: network
466                .size(multisig, "maxCosignedAccountsPerAccount")?,
467            max_account_restriction_values: network.size(
468                "plugin:catapult.plugins.restrictionaccount",
469                "maxAccountRestrictionValues",
470            )?,
471            max_mosaic_restriction_values: network.size(
472                "plugin:catapult.plugins.restrictionmosaic",
473                "maxMosaicRestrictionValues",
474            )?,
475            finalization: FinalizationConfig {
476                voting_set_grouping: network.number(chain, "votingSetGrouping")?,
477                min_voter_balance: network.number(chain, "minVoterBalance")?,
478                size: finalization.number("finalization", "size")?,
479                threshold: finalization.number("finalization", "threshold")?,
480                max_hashes_per_point: finalization.number("finalization", "maxHashesPerPoint")?,
481                step_duration: finalization.milliseconds("finalization", "stepDuration")?,
482                prevote_blocks_multiple: finalization
483                    .number("finalization", "prevoteBlocksMultiple")?,
484                enable_revote_on_boot: match finalization.get("finalization", "enableRevoteOnBoot")
485                {
486                    // catapult の設定には必ずあるが、なければ catapult の既定と同じく false
487                    Err(_) | Ok("false") => false,
488                    Ok("true") => true,
489                    Ok(other) => {
490                        return Err(ConfigError(format!(
491                            "[finalization] enableRevoteOnBoot が true か false ではありません: {other}"
492                        )));
493                    }
494                },
495                treasury_reissuance_epoch: finalization
496                    .number("finalization", "treasuryReissuanceEpoch")?
497                    .try_into()
498                    .map_err(|_| {
499                        ConfigError("treasuryReissuanceEpoch が大きすぎます".to_owned())
500                    })?,
501                ineligible_voters: finalization
502                    .values
503                    .keys()
504                    .filter(|(section, _)| {
505                        section == "treasury_reissuance_epoch_ineligible_voter_addresses"
506                    })
507                    .map(|(_, address)| {
508                        address
509                            .parse::<Address>()
510                            .map(|address| address.0)
511                            .map_err(|_| {
512                                ConfigError(format!(
513                                    "投票者から外すアドレスが読めません: {address}"
514                                ))
515                            })
516                    })
517                    .collect::<Result<Vec<_>, _>>()
518                    .map(|mut addresses| {
519                        addresses.sort_unstable();
520                        addresses
521                    })?,
522            },
523        })
524    }
525
526    /// `height` のブロックのインフレ。catapult の `InflationCalculator::getSpotAmount`。
527    pub fn inflation_at(&self, height: u64) -> u64 {
528        self.inflation
529            .iter()
530            .take_while(|(start, _)| *start <= height)
531            .last()
532            .map_or(0, |(_, amount)| *amount)
533    }
534
535    /// `height` が入る importance の区切りの高さ。catapult の `ConvertToImportanceHeight`。
536    /// 再開するとき(`node::chain::load`)に読み直すかもしれない、実行した高さより前のブロックの数の見積もり。
537    /// トランザクションの期限(ボンデッドを含む)の2倍のブロック数に、importance ブロックまでの数を足す。
538    /// これより前のブロックは、刈り込んでも再開に困らない
539    pub fn blocks_for_restart(&self) -> u64 {
540        let lifetime = self
541            .max_transaction_lifetime
542            .max(self.max_bonded_transaction_lifetime);
543        2 * lifetime / (self.block_generation_target_time * 1000) + self.importance_grouping
544    }
545
546    pub fn importance_height(&self, height: u64) -> u64 {
547        let grouped =
548            (height.saturating_sub(1)) / self.importance_grouping * self.importance_grouping;
549        grouped.max(1)
550    }
551}
552
553/// 決め打ちの設定に書く、16進のバイト列
554fn bytes<const N: usize>(text: &str) -> [u8; N] {
555    assert_eq!(text.len(), 2 * N, "決め打ちの16進の長さ");
556    std::array::from_fn(|index| {
557        u8::from_str_radix(&text[2 * index..2 * index + 2], 16).expect("決め打ちの16進")
558    })
559}
560
561fn address(text: &str) -> Address {
562    Address(bytes(text))
563}
564
565/// [`network_parameters`] を、ノードの `resources` フォルダーの `config-network.properties` から読む
566pub fn load_network_parameters(resources: &Path) -> Result<NetworkParameters, ConfigError> {
567    network_parameters(&read(resources, NETWORK_FILE)?)
568}
569
570/// 決め打ちのパラメーターを持たないネットワーク(プライベートなネットワークなど)の [`NetworkParameters`] を、
571/// `config-network.properties` のテキストから読む。`[corrupt_aggregate_transaction_hashes]` の並びは、プロセスが
572/// 終わるまで持つ([`NetworkParameters`] が `'static` の参照で持つため)
573pub fn network_parameters(network: &str) -> Result<NetworkParameters, ConfigError> {
574    let network = Properties::parse(NETWORK_FILE, network);
575    let chain = "chain";
576    let aggregate = "plugin:catapult.plugins.aggregate";
577    let lock_hash = "plugin:catapult.plugins.lockhash";
578    let lock_secret = "plugin:catapult.plugins.locksecret";
579    let namespace = "plugin:catapult.plugins.namespace";
580    let seconds = |section: &str, key: &str| network.seconds(section, key).map(Duration::from_secs);
581    let size = |section: &str, key: &str| network.size(section, key);
582    let epochs = |key: &str| -> Result<u32, ConfigError> {
583        network
584            .number(chain, key)?
585            .try_into()
586            .map_err(|_| ConfigError(format!("[{chain}] {key} が大きすぎます")))
587    };
588    let identifier = match network.get("network", "identifier")? {
589        "mainnet" => NetworkIdentifier::MAINNET,
590        "testnet" => NetworkIdentifier::TESTNET,
591        other => NetworkIdentifier(
592            other
593                .parse()
594                .map_err(|_| ConfigError(format!("[network] identifier が読めません: {other}")))?,
595        ),
596    };
597    let generation_hash_seed: GenerationHashSeed = network
598        .get("network", "generationHashSeed")?
599        .parse()
600        .map_err(|_| ConfigError("[network] generationHashSeed が読めません".to_owned()))?;
601    let mut corrupt = Vec::new();
602    for ((section, aggregate_hash), transactions_hash) in &network.values {
603        if section != "corrupt_aggregate_transaction_hashes" {
604            continue;
605        }
606        let parse = |text: &str| {
607            text.parse::<Hash256>().map_err(|_| {
608                ConfigError(format!("壊れたアグリゲートのハッシュが読めません: {text}"))
609            })
610        };
611        corrupt.push((parse(aggregate_hash)?, parse(transactions_hash)?));
612    }
613    Ok(NetworkParameters {
614        identifier,
615        generation_hash_seed,
616        epoch_adjustment: seconds("network", "epochAdjustment")?,
617        currency_mosaic_id: network.number(chain, "currencyMosaicId")?,
618        block_generation_target_time: seconds(chain, "blockGenerationTargetTime")?,
619        block_time_smoothing_factor: network.number(chain, "blockTimeSmoothingFactor")?,
620        max_difficulty_blocks: size(chain, "maxDifficultyBlocks")?,
621        total_chain_importance: network.number(chain, "totalChainImportance")?,
622        importance_grouping: network.number(chain, "importanceGrouping")?,
623        max_transaction_lifetime: seconds(chain, "maxTransactionLifetime")?,
624        max_cosignatures_per_aggregate: size(aggregate, "maxCosignaturesPerAggregate")?,
625        max_transactions_per_aggregate: size(aggregate, "maxTransactionsPerAggregate")?,
626        max_message_size: size("plugin:catapult.plugins.transfer", "maxMessageSize")?,
627        max_hash_lock_duration: seconds(lock_hash, "maxHashLockDuration")?,
628        max_secret_lock_duration: seconds(lock_secret, "maxSecretLockDuration")?,
629        min_proof_size: size(lock_secret, "minProofSize")?,
630        max_proof_size: size(lock_secret, "maxProofSize")?,
631        max_metadata_value_size: size("plugin:catapult.plugins.metadata", "maxValueSize")?,
632        max_namespace_name_size: size(namespace, "maxNameSize")?,
633        min_namespace_duration: seconds(namespace, "minNamespaceDuration")?,
634        max_namespace_duration: seconds(namespace, "maxNamespaceDuration")?,
635        voting_set_grouping: network.number(chain, "votingSetGrouping")?,
636        min_voting_key_lifetime: epochs("minVotingKeyLifetime")?,
637        max_voting_key_lifetime: epochs("maxVotingKeyLifetime")?,
638        max_voting_keys_per_account: size(chain, "maxVotingKeysPerAccount")?,
639        fork_heights: ForkHeights {
640            strict_aggregate_transaction_hash: network
641                .number("fork_heights", "strictAggregateTransactionHash")?,
642            unique_aggregate_transaction_hash: network
643                .number("fork_heights", "uniqueAggregateTransactionHash")?,
644            // catapult 1.0.3.10 と 1.0.3.11 から。前の設定ファイルには無いので、無ければフォークしない
645            strict_vrf_public_key_check: network
646                .optional_number("fork_heights", "strictVrfPublicKeyCheck")?
647                .unwrap_or(u64::MAX),
648            vrf_gamma_subgroup_check: network
649                .optional_number("fork_heights", "vrfGammaSubgroupCheck")?
650                .unwrap_or(u64::MAX),
651        },
652        corrupt_aggregate_transaction_hashes: Vec::leak(corrupt),
653    })
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659
660    #[test]
661    fn reads_sections_numbers_and_lists() {
662        let properties = Properties::parse(
663            "test",
664            "# コメント\n[chain]\nmaxDifficultyBlocks = 60\ncurrencyMosaicId = 0x6BED'913F'A202'23F8\n\
665             [fork_heights]\nskipSecretLockExpirations =\nforceSecretLockExpirations = 1, 2\n",
666        );
667        assert_eq!(
668            properties.number("chain", "maxDifficultyBlocks").unwrap(),
669            60
670        );
671        assert_eq!(
672            properties.number("chain", "currencyMosaicId").unwrap(),
673            0x6BED_913F_A202_23F8
674        );
675        assert!(
676            properties
677                .numbers("fork_heights", "skipSecretLockExpirations")
678                .unwrap()
679                .is_empty()
680        );
681        assert_eq!(
682            properties
683                .numbers("fork_heights", "forceSecretLockExpirations")
684                .unwrap(),
685            [1, 2]
686        );
687        assert!(properties.number("chain", "missing").is_err());
688        assert_eq!(
689            properties
690                .optional_number("chain", "maxDifficultyBlocks")
691                .unwrap(),
692            Some(60)
693        );
694        assert_eq!(
695            properties.optional_number("chain", "missing").unwrap(),
696            None
697        );
698    }
699
700    #[test]
701    fn reads_durations_in_milliseconds_and_seconds() {
702        let properties = Properties {
703            values: [
704                ("300ms", "300ms"),
705                ("30s", "30s"),
706                ("2m", "2m"),
707                ("1d", "1d"),
708            ]
709            .into_iter()
710            .map(|(key, value)| (("chain".to_owned(), key.to_owned()), value.to_owned()))
711            .collect(),
712            name: "test".to_owned(),
713        };
714        assert_eq!(properties.milliseconds("chain", "300ms").unwrap(), 300);
715        assert_eq!(properties.seconds("chain", "300ms").unwrap(), 0);
716        assert_eq!(properties.milliseconds("chain", "30s").unwrap(), 30_000);
717        assert_eq!(properties.seconds("chain", "2m").unwrap(), 120);
718        assert_eq!(properties.seconds("chain", "1d").unwrap(), 86_400);
719    }
720}