1use std::collections::{BTreeMap, HashSet};
20use std::fmt;
21
22use heika_block::Block;
23use heika_block::statement::BlockStatement;
24use heika_core::address::Address;
25use heika_core::hash::Hash256;
26use heika_core::key::{PrivateKey, PublicKey};
27use heika_core::network::{GenerationHashSeed, NetworkIdentifier, NetworkParameters};
28use heika_core::vrf::{self, GenerationHash};
29use heika_state_transition::config::ChainConfig;
30use heika_state_transition::executor::Executor;
31use heika_transaction::{
32 AliasAction, Body, MosaicAlias, MosaicDefinition, MosaicFlags, MosaicId, MosaicSupplyChange,
33 MosaicSupplyChangeAction, NamespaceId, NamespaceRegistration, NamespaceRegistrationType,
34 Transaction, Transfer, UnresolvedAddress, UnresolvedMosaicId, is_valid_namespace_name,
35};
36
37const HEADER_SIZE: usize = 424;
39const SIGNED_FROM: usize = 108;
41const NEMESIS_DIFFICULTY: u64 = 100_000_000_000_000;
43const NEMESIS_DEADLINE: u64 = 1;
45
46#[derive(Debug, PartialEq, Eq)]
48pub struct NemesisError(pub String);
49
50impl fmt::Display for NemesisError {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 write!(f, "Nemesis: {}", self.0)
53 }
54}
55
56impl std::error::Error for NemesisError {}
57
58fn error<T>(message: impl Into<String>) -> Result<T, NemesisError> {
59 Err(NemesisError(message.into()))
60}
61
62#[derive(Clone, Debug)]
64pub struct NemesisProperties {
65 pub network: NetworkIdentifier,
66 pub generation_hash_seed: GenerationHashSeed,
67 roots: Vec<RootSeed>,
69 mosaics: Vec<MosaicSeed>,
71 distribution: Vec<(Address, Vec<(usize, u64)>)>,
73 pub transactions_directory: Option<String>,
75}
76
77#[derive(Clone, Debug)]
78struct RootSeed {
79 name: String,
80 duration: u64,
82 children: Vec<String>,
84}
85
86#[derive(Clone, Debug)]
87struct MosaicSeed {
88 name: String,
90 divisibility: u8,
91 duration: u64,
92 supply: u64,
93 flags: MosaicFlags,
94}
95
96struct Entries {
98 items: Vec<(String, String, String)>,
99 used: HashSet<usize>,
100}
101
102impl Entries {
103 fn parse(text: &str) -> Result<Self, NemesisError> {
104 let mut items: Vec<(String, String, String)> = Vec::new();
105 let mut section = String::new();
106 for (number, line) in text.lines().enumerate() {
107 let line = line.trim();
108 if line.is_empty() || line.starts_with('#') {
109 continue;
110 }
111 if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
112 section = name.to_owned();
113 continue;
114 }
115 let Some((key, value)) = line.split_once('=') else {
116 return error(format!(
117 "{} 行目が `キー = 値` の形ではありません",
118 number + 1
119 ));
120 };
121 let key = key.trim().to_owned();
122 if items.iter().any(|(s, k, _)| *s == section && *k == key) {
123 return error(format!("[{section}] {key} が2つあります"));
124 }
125 items.push((section.clone(), key, value.trim().to_owned()));
126 }
127 Ok(Self {
128 items,
129 used: HashSet::new(),
130 })
131 }
132
133 fn find(&mut self, section: &str, key: &str) -> Option<String> {
135 let index = self
136 .items
137 .iter()
138 .position(|(s, k, _)| s == section && k == key)?;
139 self.used.insert(index);
140 Some(self.items[index].2.clone())
141 }
142
143 fn get(&mut self, section: &str, key: &str) -> Result<String, NemesisError> {
144 match self.find(section, key) {
145 Some(value) => Ok(value),
146 None => error(format!("[{section}] {key} がありません")),
147 }
148 }
149
150 fn section(&mut self, section: &str) -> Vec<(String, String)> {
152 let mut out = Vec::new();
153 for (index, (s, key, value)) in self.items.iter().enumerate() {
154 if s == section {
155 self.used.insert(index);
156 out.push((key.clone(), value.clone()));
157 }
158 }
159 out
160 }
161
162 fn number(&mut self, section: &str, key: &str) -> Result<u64, NemesisError> {
163 let value = self.get(section, key)?;
164 parse_number(&value)
165 .ok_or_else(|| NemesisError(format!("[{section}] {key} が数ではありません: {value}")))
166 }
167
168 fn boolean(&mut self, section: &str, key: &str) -> Result<bool, NemesisError> {
169 let value = self.get(section, key)?;
170 parse_bool(&value).ok_or_else(|| {
171 NemesisError(format!(
172 "[{section}] {key} が true か false ではありません: {value}"
173 ))
174 })
175 }
176
177 fn unused(&self) -> Option<(&str, &str)> {
179 (0..self.items.len())
180 .find(|index| !self.used.contains(index))
181 .map(|index| (self.items[index].0.as_str(), self.items[index].1.as_str()))
182 }
183}
184
185fn parse_number(value: &str) -> Option<u64> {
187 value.replace('\'', "").parse().ok()
188}
189
190fn parse_bool(value: &str) -> Option<bool> {
191 match value {
192 "true" => Some(true),
193 "false" => Some(false),
194 _ => None,
195 }
196}
197
198impl NemesisProperties {
199 pub fn parse(text: &str) -> Result<Self, NemesisError> {
201 let mut entries = Entries::parse(text)?;
202 if entries.find("nemesis", "nemesisSignerPrivateKey").is_some() {
203 return error(
204 "[nemesis] nemesisSignerPrivateKey は書かないでください。秘密鍵は標準入力で渡します",
205 );
206 }
207 let network = entries.get("nemesis", "networkIdentifier")?;
208 let network = match network.as_str() {
209 "mainnet" => NetworkIdentifier::MAINNET,
210 "testnet" => NetworkIdentifier::TESTNET,
211 other => NetworkIdentifier(other.parse().map_err(|_| {
212 NemesisError(format!("[nemesis] networkIdentifier が読めません: {other}"))
213 })?),
214 };
215 let generation_hash_seed = entries
216 .get("nemesis", "nemesisGenerationHashSeed")?
217 .parse()
218 .map_err(|_| {
219 NemesisError("[nemesis] nemesisGenerationHashSeed が読めません".to_owned())
220 })?;
221 entries.section("cpp");
223 entries.section("output");
224
225 let roots = parse_namespaces(&mut entries)?;
226 let names: HashSet<String> = roots
227 .iter()
228 .flat_map(|root| std::iter::once(root.name.clone()).chain(root.children.clone()))
229 .collect();
230 let (mosaics, distribution) = parse_mosaics(&mut entries, &names, network)?;
231
232 let transactions_directory = entries.get("transactions", "transactionsDirectory")?;
233 if let Some((section, key)) = entries.unused() {
234 return error(format!("知らない設定です: [{section}] {key}"));
235 }
236 Ok(Self {
237 network,
238 generation_hash_seed,
239 roots,
240 mosaics,
241 distribution,
242 transactions_directory: (!transactions_directory.is_empty())
243 .then_some(transactions_directory),
244 })
245 }
246}
247
248fn parse_namespaces(entries: &mut Entries) -> Result<Vec<RootSeed>, NemesisError> {
249 let mut roots: Vec<RootSeed> = Vec::new();
250 for (name, enabled) in entries.section("namespaces") {
251 let enabled = parse_bool(&enabled).ok_or_else(|| {
252 NemesisError(format!(
253 "[namespaces] {name} が true か false ではありません"
254 ))
255 })?;
256 if !name
257 .split('.')
258 .all(|part| is_valid_namespace_name(part.as_bytes()))
259 {
260 return error(format!("ネームスペースの名前が正しくありません: {name}"));
261 }
262 match name.rsplit_once('.') {
263 None => {
264 let duration = entries.number(&format!("namespace>{name}"), "duration")?;
266 if !enabled {
267 continue;
268 }
269 if roots.iter().any(|root| root.name == name) {
270 return error(format!("ルートのネームスペース {name} が2つあります"));
271 }
272 roots.push(RootSeed {
273 name,
274 duration,
275 children: Vec::new(),
276 });
277 }
278 Some((parent, _)) => {
279 if !enabled {
280 continue;
281 }
282 let root_name = name.split('.').next().expect("split has a first part");
283 let Some(root) = roots.iter_mut().find(|root| root.name == root_name) else {
284 return error(format!("{name} のルートのネームスペースがありません"));
285 };
286 if parent != root.name && !root.children.iter().any(|child| child == parent) {
287 return error(format!("{name} の親のネームスペースがありません"));
288 }
289 if root.children.contains(&name) {
290 return error(format!("ネームスペース {name} が2つあります"));
291 }
292 root.children.push(name);
293 }
294 }
295 }
296 for root in &mut roots {
298 root.children.sort_by_key(|name| name.matches('.').count());
299 }
300 Ok(roots)
301}
302
303type Distribution = Vec<(Address, Vec<(usize, u64)>)>;
304
305fn parse_mosaics(
306 entries: &mut Entries,
307 namespaces: &HashSet<String>,
308 network: NetworkIdentifier,
309) -> Result<(Vec<MosaicSeed>, Distribution), NemesisError> {
310 let mut mosaics: Vec<MosaicSeed> = Vec::new();
311 let mut distribution: Distribution = Vec::new();
312 for (name, enabled) in entries.section("mosaics") {
313 let enabled = parse_bool(&enabled).ok_or_else(|| {
314 NemesisError(format!("[mosaics] {name} が true か false ではありません"))
315 })?;
316 let section = format!("mosaic>{name}");
318 let divisibility = entries.number(§ion, "divisibility")?;
319 let duration = entries.number(§ion, "duration")?;
320 let supply = entries.number(§ion, "supply")?;
321 let mut flags = MosaicFlags::default();
322 for (key, flag) in [
323 ("isTransferable", MosaicFlags::TRANSFERABLE),
324 ("isSupplyMutable", MosaicFlags::SUPPLY_MUTABLE),
325 ("isRestrictable", MosaicFlags::RESTRICTABLE),
326 ] {
327 if entries.boolean(§ion, key)? {
328 flags = flags | flag;
329 }
330 }
331 let seeds = entries.section(&format!("distribution>{name}"));
332 if !enabled {
333 continue;
334 }
335 let divisibility = u8::try_from(divisibility)
336 .map_err(|_| NemesisError(format!("[{section}] divisibility が大きすぎます")))?;
337 if mosaics.iter().any(|mosaic| mosaic.name == name) {
338 return error(format!("モザイク {name} が2つあります"));
339 }
340 if !namespaces.contains(&name.replace(':', ".")) {
341 return error(format!(
342 "モザイク {name} のエイリアスにするネームスペースがありません"
343 ));
344 }
345 let index = mosaics.len();
346 mosaics.push(MosaicSeed {
347 name: name.clone(),
348 divisibility,
349 duration,
350 supply,
351 flags,
352 });
353 for (address, amount) in seeds {
354 let parsed: Address = address
355 .parse()
356 .ok()
357 .filter(|parsed: &Address| parsed.network() == network)
358 .ok_or_else(|| {
359 NemesisError(format!(
360 "[distribution>{name}] にこのネットワークのアドレスでないものがあります"
361 ))
362 })?;
363 let amount = parse_number(&amount).ok_or_else(|| {
364 NemesisError(format!("[distribution>{name}] に数でない量があります"))
365 })?;
366 match distribution.iter_mut().find(|(seen, _)| *seen == parsed) {
367 Some((_, seeds)) => seeds.push((index, amount)),
368 None => distribution.push((parsed, vec![(index, amount)])),
369 }
370 }
371 }
372 Ok((mosaics, distribution))
373}
374
375#[derive(Debug)]
377pub struct Nemesis {
378 pub block: Block,
379 pub generation_hash: GenerationHash,
380 pub statement: BlockStatement,
382 pub sub_cache_roots: [Hash256; 9],
384}
385
386pub fn generate(
390 properties: &NemesisProperties,
391 config: ChainConfig,
392 parameters: &NetworkParameters,
393 signer: &PrivateKey,
394 additional: &[Vec<u8>],
395) -> Result<Nemesis, NemesisError> {
396 let seed = &properties.generation_hash_seed;
397 let network = properties.network;
398 let signer_public_key = PublicKey::from_private_key(signer);
399 if network != parameters.identifier {
400 return error("networkIdentifier が config-network の identifier と違います");
401 }
402 if *seed != parameters.generation_hash_seed {
403 return error(
404 "nemesisGenerationHashSeed が config-network の generationHashSeed と違います",
405 );
406 }
407 if signer_public_key != config.nemesis_signer_public_key {
408 return error("秘密鍵が config-network の nemesisSignerPublicKey と合いません");
409 }
410 let owner = Address::from_public_key(&signer_public_key, network);
411 let mosaic_ids: Vec<MosaicId> = (0..properties.mosaics.len())
412 .map(|nonce| MosaicId::generate(&owner, nonce as u32))
413 .collect();
414 check_funding(properties, &config, &mosaic_ids)?;
415
416 let mut transactions = Vec::new();
417 let mut add = |body: Body| -> Result<(), NemesisError> {
418 let mut transaction =
419 Transaction::new(signer_public_key, network, 0, NEMESIS_DEADLINE, body);
420 transaction
421 .sign(signer, seed)
422 .map_err(|error| NemesisError(error.to_string()))?;
423 transactions.push(transaction.to_bytes());
424 Ok(())
425 };
426 for root in &properties.roots {
427 add(registration(
428 &root.name,
429 NamespaceRegistrationType::Root {
431 duration: root.duration,
432 },
433 )?)?;
434 for child in &root.children {
435 let (parent, name) = child.rsplit_once('.').expect("child has a parent");
436 let parent_id = namespace_id(parent)?;
437 add(registration(
438 name,
439 NamespaceRegistrationType::Child { parent_id },
440 )?)?;
441 }
442 }
443 let mut aliases = Vec::new();
444 for (nonce, mosaic) in properties.mosaics.iter().enumerate() {
445 add(Body::MosaicDefinition(MosaicDefinition {
446 id: mosaic_ids[nonce],
447 duration: mosaic.duration,
448 nonce: nonce as u32,
449 flags: mosaic.flags,
450 divisibility: mosaic.divisibility,
451 }))?;
452 let alias = namespace_id(&mosaic.name.replace(':', "."))?;
453 add(Body::MosaicAlias(MosaicAlias {
454 namespace_id: alias,
455 mosaic_id: mosaic_ids[nonce],
456 alias_action: AliasAction::Link,
457 }))?;
458 let unresolved = UnresolvedMosaicId(alias.0);
460 add(Body::MosaicSupplyChange(MosaicSupplyChange {
461 mosaic_id: unresolved,
462 delta: mosaic.supply,
463 action: MosaicSupplyChangeAction::Increase,
464 }))?;
465 aliases.push(unresolved);
466 }
467 for (address, seeds) in &properties.distribution {
468 let mosaics: BTreeMap<UnresolvedMosaicId, u64> = seeds
469 .iter()
470 .map(|&(index, amount)| (aliases[index], amount))
471 .collect();
472 if mosaics.len() != seeds.len() {
473 return error(format!("{address} に同じモザイクを2回配っています"));
474 }
475 let transfer = Transfer::new(UnresolvedAddress(address.0), mosaics, Vec::new())
476 .map_err(|error| NemesisError(error.to_string()))?;
477 add(Body::Transfer(transfer))?;
478 }
479 for (index, bytes) in additional.iter().enumerate() {
480 check_additional(bytes, &signer_public_key, seed).map_err(|NemesisError(why)| {
481 NemesisError(format!("追加の {} 件目: {why}", index + 1))
482 })?;
483 transactions.push(bytes.clone());
484 }
485
486 let proof = vrf::prove(signer, &seed.0)
487 .ok_or_else(|| NemesisError("VRF の証明が作れません".to_owned()))?;
488 let mut bytes = assemble(network, &signer_public_key, &owner, &proof, &transactions)?;
489 let unsigned = decode(&bytes)?;
490 let transactions_hash = unsigned
491 .calculate_transactions_hash(seed)
492 .map_err(|error| NemesisError(error.to_string()))?;
493 bytes[248..280].copy_from_slice(&transactions_hash.0);
494
495 let mut executor = Executor::new(config, network, *seed);
496 let produced = executor
497 .apply_produced(&decode(&bytes)?)
498 .map_err(|error| NemesisError(format!("実行できません: {error}")))?;
499 bytes[280..312].copy_from_slice(&produced.receipts_hash.0);
500 bytes[312..344].copy_from_slice(&produced.state_hash.0);
501 let (voting, harvesting, balance) = produced
502 .footer
503 .ok_or_else(|| NemesisError("足が求まりません".to_owned()))?;
504 bytes[372..376].copy_from_slice(&voting.to_le_bytes());
505 bytes[376..384].copy_from_slice(&harvesting.to_le_bytes());
506 bytes[384..392].copy_from_slice(&balance.to_le_bytes());
507 let signature = signer.sign(&[&bytes[SIGNED_FROM..HEADER_SIZE]]);
508 bytes[8..72].copy_from_slice(&signature.0);
509 let block = decode(&bytes)?;
510 if !block.verify_signature() {
511 return error("作ったブロックの署名が確かめられません");
512 }
513 Ok(Nemesis {
514 generation_hash: vrf::proof_hash(&proof.gamma).generation_hash(),
515 block,
516 statement: produced.statement,
517 sub_cache_roots: executor.roots(),
518 })
519}
520
521fn namespace_id(full_name: &str) -> Result<NamespaceId, NemesisError> {
522 NamespaceId::from_full_name(full_name).map_err(|error| NemesisError(error.to_string()))
523}
524
525fn registration(
526 name: &str,
527 registration_type: NamespaceRegistrationType,
528) -> Result<Body, NemesisError> {
529 let parent = match registration_type {
530 NamespaceRegistrationType::Root { .. } => None,
531 NamespaceRegistrationType::Child { parent_id } => Some(parent_id),
532 };
533 Ok(Body::NamespaceRegistration(NamespaceRegistration {
534 registration_type,
535 id: NamespaceId::generate(parent, name.as_bytes()),
536 name: name
537 .as_bytes()
538 .to_vec()
539 .try_into()
540 .map_err(|_| NemesisError(format!("ネームスペースの名前が長すぎます: {name}")))?,
541 }))
542}
543
544fn check_funding(
547 properties: &NemesisProperties,
548 config: &ChainConfig,
549 mosaic_ids: &[MosaicId],
550) -> Result<(), NemesisError> {
551 let mut funded = vec![0u64; mosaic_ids.len()];
552 for (_, seeds) in &properties.distribution {
553 for &(index, amount) in seeds {
554 funded[index] = funded[index]
555 .checked_add(amount)
556 .ok_or_else(|| NemesisError("配る量の合計が大きすぎます".to_owned()))?;
557 }
558 }
559 let total_of = |id: u64, what: &str| -> Result<u64, NemesisError> {
560 mosaic_ids
561 .iter()
562 .position(|mosaic| mosaic.0 == id)
563 .map(|index| funded[index])
564 .ok_or_else(|| {
565 NemesisError(format!(
566 "config-network の {what}({id:016X})を、Nemesis で作っていません"
567 ))
568 })
569 };
570 total_of(config.currency_mosaic_id, "currencyMosaicId")?;
571 let harvesting = total_of(config.harvesting_mosaic_id, "harvestingMosaicId")?;
572 if harvesting != config.total_chain_importance {
573 return error(format!(
574 "ハーベストのモザイクを配った合計 {harvesting} が、totalChainImportance {} と違います",
575 config.total_chain_importance
576 ));
577 }
578 for (mosaic, total) in properties.mosaics.iter().zip(&funded) {
579 if *total > config.max_mosaic_atomic_units {
580 return error(format!(
581 "{} を配った合計が maxMosaicAtomicUnits を超えます",
582 mosaic.name
583 ));
584 }
585 }
586 Ok(())
587}
588
589fn check_additional(
592 bytes: &[u8],
593 nemesis: &PublicKey,
594 seed: &GenerationHashSeed,
595) -> Result<(), NemesisError> {
596 let transaction = Transaction::from_bytes(bytes)
597 .map_err(|error| NemesisError(format!("読めません: {error}")))?;
598 if transaction.deadline != NEMESIS_DEADLINE {
599 return error("期限が 1 ではありません");
600 }
601 if transaction.fee != 0 {
602 return error("手数料が 0 ではありません");
603 }
604 let mut signers = vec![transaction.signer_public_key];
605 match &transaction.body {
606 Body::Transfer(_) => return error("送金は入れられません"),
607 Body::AggregateBonded(_) => return error("ボンデッドのアグリゲートは入れられません"),
608 Body::AggregateComplete(aggregate) => {
609 for embedded in aggregate.transactions() {
610 if matches!(embedded.body, Body::Transfer(_)) {
611 return error("アグリゲートの中の送金は入れられません");
612 }
613 signers.push(embedded.signer_public_key);
614 }
615 if !transaction.verify_cosignatures(seed) {
616 return error("連署が確かめられません");
617 }
618 }
619 _ => {}
620 }
621 if signers.contains(nemesis) {
622 return error("Nemesis の鍵で署名したものは入れられません");
623 }
624 if !transaction.verify(seed) {
625 return error("署名が確かめられません(generation hash seed が違うかもしれません)");
626 }
627 Ok(())
628}
629
630fn assemble(
632 network: NetworkIdentifier,
633 signer: &PublicKey,
634 owner: &Address,
635 proof: &vrf::VrfProof,
636 transactions: &[Vec<u8>],
637) -> Result<Vec<u8>, NemesisError> {
638 let mut bytes = vec![0u8; HEADER_SIZE];
639 bytes[72..104].copy_from_slice(&signer.0);
640 bytes[108] = 1;
641 bytes[109] = network.0;
642 bytes[110..112].copy_from_slice(&0x8043u16.to_le_bytes());
643 bytes[112..120].copy_from_slice(&1u64.to_le_bytes());
644 bytes[128..136].copy_from_slice(&NEMESIS_DIFFICULTY.to_le_bytes());
645 bytes[136..168].copy_from_slice(&proof.gamma);
646 bytes[168..184].copy_from_slice(&proof.verification_hash);
647 bytes[184..216].copy_from_slice(&proof.scalar);
648 bytes[344..368].copy_from_slice(&owner.0);
650 for (index, transaction) in transactions.iter().enumerate() {
652 bytes.extend_from_slice(transaction);
653 if index + 1 < transactions.len() {
654 bytes.resize(bytes.len().next_multiple_of(8), 0);
655 }
656 }
657 let size = u32::try_from(bytes.len()).map_err(|_| NemesisError("大きすぎます".into()))?;
658 bytes[0..4].copy_from_slice(&size.to_le_bytes());
659 Ok(bytes)
660}
661
662fn decode(bytes: &[u8]) -> Result<Block, NemesisError> {
663 Block::from_bytes(bytes)
664 .map_err(|error| NemesisError(format!("組んだブロックが読めません: {error}")))
665}
666
667pub const SEED_BLOCK_FILE: &str = "00000/00001.dat";
669
670pub fn read_seed_block(element: &[u8]) -> Result<Block, NemesisError> {
672 let size = element
673 .get(..4)
674 .map(|size| u32::from_le_bytes(size.try_into().expect("4 bytes")) as usize)
675 .filter(|&size| size <= element.len())
676 .ok_or_else(|| NemesisError(format!("{SEED_BLOCK_FILE} が短すぎます")))?;
677 let block = Block::from_bytes(&element[..size]).map_err(|error| {
678 NemesisError(format!("{SEED_BLOCK_FILE} のブロックが読めません: {error}"))
679 })?;
680 if block.height != 1 || block.block_type != heika_block::BlockType::Nemesis {
681 return error(format!(
682 "{SEED_BLOCK_FILE} のブロックが Nemesis ではありません"
683 ));
684 }
685 Ok(block)
686}
687
688pub fn nemesis_proof(hash: &Hash256) -> Vec<u8> {
691 let mut proof = Vec::with_capacity(56);
692 proof.extend_from_slice(&56u32.to_le_bytes());
693 proof.extend_from_slice(&1u32.to_le_bytes());
694 proof.extend_from_slice(&1u32.to_le_bytes());
695 proof.extend_from_slice(&1u32.to_le_bytes());
696 proof.extend_from_slice(&1u64.to_le_bytes());
697 proof.extend_from_slice(&hash.0);
698 proof
699}
700
701impl Nemesis {
702 pub fn seed_files(&self, seed: &GenerationHashSeed) -> Vec<(&'static str, Vec<u8>)> {
705 let hash = self.block.hash();
706 let mut element = self.block.as_bytes().to_vec();
707 element.extend_from_slice(&hash.0);
708 element.extend_from_slice(&self.generation_hash.0);
709 let transactions: Vec<Transaction> = self
710 .block
711 .transactions()
712 .map(|bytes| Transaction::from_bytes(bytes).expect("built from these bytes"))
713 .collect();
714 element.extend_from_slice(&(transactions.len() as u32).to_le_bytes());
715 for transaction in &transactions {
716 element.extend_from_slice(&transaction.hash(seed).0);
717 element.extend_from_slice(&transaction.merkle_component_hash(seed).0);
718 }
719 element.extend_from_slice(&(self.sub_cache_roots.len() as u32).to_le_bytes());
720 for root in &self.sub_cache_roots {
721 element.extend_from_slice(&root.0);
722 }
723
724 let mut hashes = vec![0u8; 32];
726 hashes.extend_from_slice(&hash.0);
727
728 let proof = nemesis_proof(&hash);
730 let round = proof[8..].to_vec();
731
732 vec![
733 ("index.dat", 1u64.to_le_bytes().to_vec()),
734 ("00000/hashes.dat", hashes),
735 (SEED_BLOCK_FILE, element),
736 ("00000/00001.stmt", self.statement.to_bytes()),
737 ("proof.index.dat", round),
738 ("00000/proof.heights.dat", vec![0; 16]),
739 ("00000/00001.proof", proof),
740 ]
741 }
742}
743
744#[cfg(test)]
745mod tests {
746 use super::*;
747 use heika_block::BlockType;
748 use heika_transaction::{KeyLink, LinkAction};
749
750 const SEED: GenerationHashSeed = GenerationHashSeed([7; 32]);
751 const STAKE: u64 = 20_000_000_000;
753
754 fn key(byte: u8) -> PrivateKey {
755 PrivateKey::from_bytes(&[byte; 32])
756 }
757
758 fn address(byte: u8) -> Address {
759 Address::from_public_key(
760 &PublicKey::from_private_key(&key(byte)),
761 NetworkIdentifier::TESTNET,
762 )
763 }
764
765 fn properties_text(extra: &str) -> String {
766 format!(
767 "[nemesis]\n\nnetworkIdentifier = testnet\nnemesisGenerationHashSeed = {}\n\n\
768 [cpp]\n\ncppFileHeader =\n\n[output]\n\ncppFile =\nbinDirectory = seed\n\n\
769 [namespaces]\n\nsymbol = true\nsymbol.xym = true\n\n[namespace>symbol]\n\nduration = 0\n\n\
770 [mosaics]\n\nsymbol:xym = true\n\n[mosaic>symbol:xym]\n\ndivisibility = 6\nduration = 0\n\
771 supply = 40'000'000'000\nisTransferable = true\nisSupplyMutable = false\nisRestrictable = false\n\n\
772 [distribution>symbol:xym]\n\n{} = 20'000'000'000\n{} = 20'000'000'000\n{extra}\n\
773 [transactions]\n\ntransactionsDirectory =\n",
774 hex(&SEED.0),
775 address(2),
776 address(3),
777 )
778 }
779
780 fn hex(bytes: &[u8]) -> String {
781 bytes.iter().map(|byte| format!("{byte:02X}")).collect()
782 }
783
784 fn network() -> (ChainConfig, NetworkParameters) {
786 let signer = PublicKey::from_private_key(&key(1));
787 let currency = MosaicId::generate(
788 &Address::from_public_key(&signer, NetworkIdentifier::TESTNET),
789 0,
790 );
791 let mut config = ChainConfig::testnet();
792 config.nemesis_signer_public_key = signer;
793 config.currency_mosaic_id = currency.0;
794 config.harvesting_mosaic_id = currency.0;
795 config.total_chain_importance = 2 * STAKE;
796 let mut parameters = NetworkParameters::TESTNET;
797 parameters.generation_hash_seed = SEED;
798 (config, parameters)
799 }
800
801 fn build(text: &str, additional: &[Vec<u8>]) -> Result<Nemesis, NemesisError> {
802 let properties = NemesisProperties::parse(text)?;
803 let (config, parameters) = network();
804 generate(&properties, config, ¶meters, &key(1), additional)
805 }
806
807 fn vrf_link(signer: u8, fee: u64) -> Vec<u8> {
809 let mut transaction = Transaction::new(
810 PublicKey::from_private_key(&key(signer)),
811 NetworkIdentifier::TESTNET,
812 fee,
813 NEMESIS_DEADLINE,
814 Body::VrfKeyLink(KeyLink {
815 linked_public_key: PublicKey::from_private_key(&key(9)),
816 link_action: LinkAction::Link,
817 }),
818 );
819 transaction.sign(&key(signer), &SEED).unwrap();
820 transaction.to_bytes()
821 }
822
823 #[test]
824 fn builds_a_nemesis_that_replays_to_the_same_hashes() {
825 let link = vrf_link(2, 0);
826 let nemesis = build(&properties_text(""), std::slice::from_ref(&link)).unwrap();
827 let block = &nemesis.block;
828 assert_eq!(block.block_type, BlockType::Nemesis);
829 assert!(block.verify_signature());
830 assert_eq!(block.verify_transactions_hash(&SEED), Ok(true));
831 assert_eq!(
832 block.verify_generation_hash_proof(&block.signer_public_key, &SEED.0),
833 Some(nemesis.generation_hash)
834 );
835 assert_eq!(block.beneficiary_address, address(1));
836 assert_eq!(block.difficulty, NEMESIS_DIFFICULTY);
837 let footer = block.importance_footer.as_ref().unwrap();
838 assert_eq!(footer.harvesting_eligible_accounts_count, 2);
839 assert_eq!(footer.voting_eligible_accounts_count, 0);
840 assert!(block.verify_receipts_hash(&nemesis.statement));
841
842 let (config, _) = network();
844 let mut executor = Executor::new(config, NetworkIdentifier::TESTNET, SEED);
845 executor.apply(block).unwrap();
846 assert_eq!(executor.state_hash(), block.state_hash);
847 assert_eq!(executor.roots(), nemesis.sub_cache_roots);
848
849 let again = build(&properties_text(""), &[link]).unwrap();
851 assert_eq!(again.block.as_bytes(), block.as_bytes());
852 }
853
854 #[test]
855 fn orders_transactions_like_nemgen() {
856 let nemesis = build(&properties_text(""), &[vrf_link(3, 0)]).unwrap();
857 let types: Vec<u16> = nemesis
858 .block
859 .transactions()
860 .map(|bytes| {
861 Transaction::from_bytes(bytes)
862 .unwrap()
863 .body
864 .transaction_type()
865 })
866 .collect();
867 assert_eq!(
869 types,
870 [
871 0x414E, 0x414E, 0x414D, 0x434E, 0x424D, 0x4154, 0x4154, 0x4243
872 ]
873 );
874 }
875
876 #[test]
877 fn writes_the_seed_layout() {
878 let nemesis = build(&properties_text(""), &[]).unwrap();
879 let files = nemesis.seed_files(&SEED);
880 let file = |name: &str| &files.iter().find(|(path, _)| *path == name).unwrap().1;
881 let hash = nemesis.block.hash();
882 assert_eq!(file("index.dat"), &1u64.to_le_bytes());
883 assert_eq!(&file("00000/hashes.dat")[32..], &hash.0);
884 let element = file(SEED_BLOCK_FILE);
885 let size = nemesis.block.as_bytes().len();
886 assert_eq!(&element[..size], nemesis.block.as_bytes());
887 assert_eq!(&element[size..size + 32], &hash.0);
888 assert_eq!(element.len(), size + 64 + 4 + 7 * 64 + 4 + 9 * 32);
890 assert_eq!(
891 BlockStatement::from_bytes(file("00000/00001.stmt")).unwrap(),
892 nemesis.statement
893 );
894 assert_eq!(&file("00000/00001.proof")[24..], &hash.0);
895 assert_eq!(file("proof.index.dat"), &file("00000/00001.proof")[8..]);
896 assert_eq!(file("00000/00001.proof"), &nemesis_proof(&hash));
898 let header = heika_block::finalization::proof::proof_header(&nemesis_proof(&hash)).unwrap();
899 assert_eq!(
900 (header.round.epoch, header.height, header.hash),
901 (1, 1, hash)
902 );
903 assert!(heika_block::finalization::proof::closes_epoch(&header, 60));
904 assert_eq!(read_seed_block(element).unwrap(), nemesis.block);
906 assert!(read_seed_block(&element[..100]).is_err());
907 }
908
909 #[test]
910 fn rejects_what_nemgen_or_the_node_would() {
911 let fails = |text: &str, additional: &[Vec<u8>]| build(text, additional).unwrap_err().0;
912 let text = properties_text("");
913 let with_key = text.replace(
915 "[cpp]",
916 &format!(
917 "nemesisSignerPrivateKey = {}\n\n[cpp]",
918 hex(key(1).as_bytes())
919 ),
920 );
921 assert!(fails(&with_key, &[]).contains("nemesisSignerPrivateKey"));
922 assert!(fails(&format!("{text}typo = 1\n"), &[]).contains("知らない設定"));
924 let more = properties_text(&format!("{} = 1\n", address(4)));
926 assert!(fails(&more, &[]).contains("totalChainImportance"));
927 let orphan = text.replace("symbol.xym = true", "symbol.xym = true\nother.child = true");
929 assert!(fails(&orphan, &[]).contains("ルート"));
930 assert!(fails(&text, &[vrf_link(2, 1)]).contains("手数料"));
932 assert!(fails(&text, &[vrf_link(1, 0)]).contains("Nemesis の鍵"));
933 }
934
935 #[test]
936 fn skips_disabled_entries_but_keeps_reading_them() {
937 let text = properties_text("").replace(
939 "[mosaics]\n\nsymbol:xym = true\n",
940 "[mosaics]\n\nsymbol:old = false\nsymbol:xym = true\n\n[mosaic>symbol:old]\n\n\
941 divisibility = 0\nduration = 0\nsupply = 1\nisTransferable = true\n\
942 isSupplyMutable = false\nisRestrictable = false\n",
943 );
944 let nemesis = build(&text, &[]).unwrap();
945 assert_eq!(nemesis.block.transactions().count(), 7);
946 let missing = properties_text("").replace(
948 "[mosaics]\n\nsymbol:xym = true\n",
949 "[mosaics]\n\nsymbol:old = false\nsymbol:xym = true\n",
950 );
951 assert!(
952 build(&missing, &[])
953 .unwrap_err()
954 .0
955 .contains("mosaic>symbol:old")
956 );
957 }
958}