1mod partial;
11pub use partial::{Wanted, is_partial_row};
12pub use validate::PartialCheck;
13pub mod persist;
14mod rules;
15pub mod source;
16mod statement;
17
18mod accounts;
19mod block;
20mod link;
21mod lock;
22mod metadata;
23mod mosaic;
24mod multisig;
25mod namespace;
26mod resolve;
27mod restriction;
28mod roots;
29mod transfer;
30mod validate;
31
32use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
33use std::fmt;
34
35use heika_block::scoring::{BlockStatistic, NEMESIS_CHAIN_SCORE, block_score};
36use heika_block::statement::{
37 BalanceChange, BalanceTransfer, BlockStatement, Mosaic as ReceiptMosaic, ReceiptBody,
38};
39use heika_block::{Block, BlockType};
40use heika_core::address::Address;
41use heika_core::hash::Hash256;
42use heika_core::key::PublicKey;
43use heika_core::network::NetworkIdentifier;
44use heika_core::patricia::{SubCache, TreeNode, address_key, hash_key, id_key, state_hash};
45use heika_core::vrf::GenerationHash;
46use heika_transaction::{
47 Aggregate, AliasAction, Body, EmbeddedTransaction, LinkAction, MetadataKey, MetadataType,
48 MosaicFlags, MosaicId, MosaicSupplyChangeAction, NamespaceId, NamespaceRegistrationType,
49 Transaction, UnresolvedAddress, secret_lock_key,
50};
51use rayon::prelude::*;
52use sha3::{Digest, Sha3_256};
53
54use crate::account::{AccountState, AccountType, Bucket, Snapshot, VotingKey};
55use crate::config::ChainConfig;
56use crate::table::Table;
57use crate::tree::PatriciaTree;
58use crate::tree::StateTree;
59use statement::StatementBuilder;
60
61#[derive(Clone, PartialEq, Eq, Debug)]
63pub enum ExecError {
64 Unsupported(String),
66 Invalid(String),
68 Source(String),
70}
71
72impl fmt::Display for ExecError {
73 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74 match self {
75 Self::Unsupported(what) => write!(f, "扱いません: {what}"),
76 Self::Invalid(what) => write!(f, "規則に合いません: {what}"),
77 Self::Source(what) => write!(f, "状態を読めません: {what}"),
78 }
79 }
80}
81
82impl std::error::Error for ExecError {}
83
84fn invalid(what: impl Into<String>) -> ExecError {
85 ExecError::Invalid(what.into())
86}
87
88#[derive(Clone, Copy, PartialEq, Eq, Debug)]
90enum Alias {
91 None,
92 Mosaic(u64),
93 Address([u8; 24]),
94}
95
96impl Alias {
97 fn encode(&self, out: &mut Vec<u8>) {
98 match self {
99 Self::None => out.push(0),
100 Self::Mosaic(id) => {
101 out.push(1);
102 out.extend_from_slice(&id.to_le_bytes());
103 }
104 Self::Address(address) => {
105 out.push(2);
106 out.extend_from_slice(address);
107 }
108 }
109 }
110}
111
112#[derive(Clone, Debug)]
114struct RootNamespace {
115 owner: [u8; 24],
116 start: u64,
117 end: u64,
119 alias: Alias,
120 children: BTreeMap<Vec<u64>, Alias>,
122}
123
124#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
126enum Artifact {
127 Namespace(u64),
128 Mosaic(u64),
129}
130
131#[derive(Clone, Debug)]
133struct MosaicEntry {
134 supply: u64,
135 start_height: u64,
136 owner: [u8; 24],
137 revision: u32,
138 flags: u8,
139 divisibility: u8,
140 duration: u64,
141}
142
143impl MosaicEntry {
144 fn is_active(&self, height: u64) -> bool {
146 self.duration == 0
147 || (self.start_height <= height && height < self.start_height + self.duration)
148 }
149}
150
151#[derive(Clone, Debug, Default)]
153struct MultisigEntry {
154 min_approval: u32,
155 min_removal: u32,
156 cosignatories: BTreeSet<[u8; 24]>,
157 multisigs: BTreeSet<[u8; 24]>,
158}
159
160#[derive(Clone, Copy, PartialEq, Eq, Debug)]
162enum MultisigOperation {
163 Normal,
164 Removal,
165 Both,
166}
167
168const MAX_MULTISIG_WALK: usize = 8;
170
171const MOSAIC_FLAGS_ALL: u8 = 0x0F;
173
174#[derive(Clone, Debug)]
176struct AccountRestriction {
177 descriptor: u16,
179 values: BTreeSet<Vec<u8>>,
180}
181
182const RESTRICTION_BLOCK: u16 = 0x8000;
184
185fn new_account_restrictions() -> BTreeMap<u16, AccountRestriction> {
187 [0x0001, 0x0002, 0x4001, 0x4004]
188 .into_iter()
189 .map(|flags| {
190 (
191 flags,
192 AccountRestriction {
193 descriptor: flags | RESTRICTION_BLOCK,
194 values: BTreeSet::new(),
195 },
196 )
197 })
198 .collect()
199}
200
201#[derive(Clone, Copy, PartialEq, Eq, Debug)]
203enum LockStatus {
204 Unused = 0,
205 Used = 1,
206}
207
208#[derive(Clone, Debug)]
210struct HashLockInfo {
211 owner: [u8; 24],
212 mosaic_id: u64,
213 amount: u64,
214 end_height: u64,
215 status: LockStatus,
216}
217
218#[derive(Clone, Debug)]
220struct SecretLockInfo {
221 owner: [u8; 24],
222 mosaic_id: u64,
223 amount: u64,
224 end_height: u64,
225 status: LockStatus,
226 hash_algorithm: u8,
227 secret: [u8; 32],
228 recipient: [u8; 24],
229}
230
231#[derive(Clone, Debug, PartialEq)]
233enum MosaicRestrictionEntry {
234 Address {
236 mosaic_id: u64,
237 address: [u8; 24],
238 values: BTreeMap<u64, u64>,
239 },
240 Global {
242 mosaic_id: u64,
243 rules: BTreeMap<u64, (u64, u64, u8)>,
244 },
245}
246
247impl MosaicRestrictionEntry {
248 fn encode(&self) -> Vec<u8> {
250 let mut out = Vec::new();
251 match self {
252 Self::Address {
253 mosaic_id,
254 address,
255 values,
256 } => {
257 out.push(0);
258 out.extend_from_slice(&mosaic_id.to_le_bytes());
259 out.extend_from_slice(address);
260 out.push(values.len() as u8);
261 for (key, value) in values {
262 out.extend_from_slice(&key.to_le_bytes());
263 out.extend_from_slice(&value.to_le_bytes());
264 }
265 }
266 Self::Global { mosaic_id, rules } => {
267 out.push(1);
268 out.extend_from_slice(&mosaic_id.to_le_bytes());
269 out.push(rules.len() as u8);
270 for (key, (reference, value, restriction_type)) in rules {
271 out.extend_from_slice(&key.to_le_bytes());
272 out.extend_from_slice(&reference.to_le_bytes());
273 out.extend_from_slice(&value.to_le_bytes());
274 out.push(*restriction_type);
275 }
276 }
277 }
278 out
279 }
280
281 fn is_empty(&self) -> bool {
282 match self {
283 Self::Address { values, .. } => values.is_empty(),
284 Self::Global { rules, .. } => rules.is_empty(),
285 }
286 }
287}
288
289fn mosaic_restriction_key(mosaic_id: u64, address: &[u8; 24]) -> [u8; 32] {
291 let mut hasher = Sha3_256::new();
292 hasher.update(mosaic_id.to_le_bytes());
293 hasher.update(address);
294 hasher.finalize().into()
295}
296
297const MOSAIC_RESTRICTION_REMOVAL: u64 = u64::MAX;
299
300pub struct Executor {
302 config: ChainConfig,
303 network: NetworkIdentifier,
304 height: u64,
306 accounts: Table<[u8; 24], AccountState>,
307 touched: BTreeSet<[u8; 24]>,
309 dirty_accounts: BTreeSet<[u8; 24]>,
311 trees: [StateTree; 9],
313 unsaved_accounts: BTreeSet<[u8; 24]>,
315 dirty_rows: BTreeSet<Vec<u8>>,
317 unsaved_rows: BTreeSet<Vec<u8>>,
319 expiries: BTreeMap<u64, Vec<Vec<u8>>>,
321 artifact_expiries: BTreeMap<u64, BTreeSet<Artifact>>,
323 high_value: BTreeSet<[u8; 24]>,
324 removed: BTreeSet<[u8; 24]>,
326 last_importance_height: u64,
327 namespaces: BTreeMap<u64, RootNamespace>,
328 namespace_paths: HashMap<u64, Vec<u64>>,
330 mosaics: BTreeMap<u64, MosaicEntry>,
331 multisigs: Table<[u8; 24], MultisigEntry>,
332 account_restrictions: BTreeMap<[u8; 24], BTreeMap<u16, AccountRestriction>>,
333 hash_locks: Table<[u8; 32], Vec<HashLockInfo>>,
334 secret_locks: BTreeMap<[u8; 32], Vec<SecretLockInfo>>,
335 metadata: Table<[u8; 32], (MetadataKey, Vec<u8>)>,
337 mosaic_restrictions: BTreeMap<[u8; 32], MosaicRestrictionEntry>,
338 generation_hash_seed: heika_core::network::GenerationHashSeed,
339 fee_multipliers: VecDeque<u32>,
341 dynamic_fee_multiplier: u32,
343 nemesis: [u8; 24],
344 implicit_funding: Option<bool>,
346 stale_secret_locks: BTreeSet<[u8; 32]>,
349 score: Option<(u128, BlockStatistic)>,
352 recent_hashes: HashSet<[u8; 32]>,
355 hash_deadlines: BTreeMap<u64, Vec<[u8; 32]>>,
357 attempt_hashes: Vec<(u64, [u8; 32])>,
360 statement: StatementBuilder,
362 last_statement: BlockStatement,
364 producing: bool,
366 produced_footer: Option<(u32, u64, u64)>,
368 current_transaction: Option<usize>,
370}
371
372pub struct Produced {
374 pub state_hash: Hash256,
375 pub receipts_hash: Hash256,
376 pub footer: Option<(u32, u64, u64)>,
378 pub statement: BlockStatement,
379}
380
381impl Executor {
382 pub fn new(
383 config: ChainConfig,
384 network: NetworkIdentifier,
385 generation_hash_seed: heika_core::network::GenerationHashSeed,
386 ) -> Self {
387 Self {
388 config,
389 network,
390 height: 0,
391 accounts: Table::complete(),
392 touched: BTreeSet::new(),
393 dirty_accounts: BTreeSet::new(),
394 trees: Default::default(),
395 unsaved_accounts: BTreeSet::new(),
396 dirty_rows: BTreeSet::new(),
397 unsaved_rows: BTreeSet::new(),
398 expiries: BTreeMap::new(),
399 artifact_expiries: BTreeMap::new(),
400 high_value: BTreeSet::new(),
401 removed: BTreeSet::new(),
402 last_importance_height: 0,
403 namespaces: BTreeMap::new(),
404 namespace_paths: HashMap::new(),
405 mosaics: BTreeMap::new(),
406 multisigs: Table::complete(),
407 account_restrictions: BTreeMap::new(),
408 hash_locks: Table::complete(),
409 secret_locks: BTreeMap::new(),
410 metadata: Table::complete(),
411 mosaic_restrictions: BTreeMap::new(),
412 generation_hash_seed,
413 fee_multipliers: VecDeque::new(),
414 dynamic_fee_multiplier: 0,
415 nemesis: [0; 24],
416 implicit_funding: None,
417 stale_secret_locks: BTreeSet::new(),
418 score: Some((
419 0,
420 BlockStatistic {
421 timestamp: 0,
422 difficulty: 0,
423 },
424 )),
425 recent_hashes: HashSet::new(),
426 hash_deadlines: BTreeMap::new(),
427 attempt_hashes: Vec::new(),
428 statement: StatementBuilder::default(),
429 last_statement: BlockStatement::default(),
430 producing: false,
431 current_transaction: None,
432 produced_footer: None,
433 }
434 }
435
436 pub fn height(&self) -> u64 {
438 self.height
439 }
440
441 pub fn score(&self) -> Option<u128> {
443 self.score.map(|(total, _)| total)
444 }
445
446 pub fn set_score(&mut self, total: u128, last: BlockStatistic) {
448 self.score = Some((total, last));
449 }
450
451 pub fn apply(&mut self, block: &Block) -> Result<(), ExecError> {
453 self.current_transaction = None;
455 self.attempt_hashes.clear();
456 let height = self.height + 1;
457 if block.height != height {
458 return Err(invalid(format!("高さ {height} のはずが {}", block.height)));
459 }
460 let nemesis = block.block_type == BlockType::Nemesis;
461 if nemesis {
462 self.nemesis = self.address_of(&block.signer_public_key);
463 }
464 let harvest_sink = self.config.harvest_network_fee_sink.at(height).0;
465 self.forget_expired_hashes(block.timestamp);
466 let mut total_fee = 0u64;
467 for (index, bytes) in block.transactions().enumerate() {
468 let primary = index as u32 + 1;
470 self.current_transaction = Some(index);
471 self.statement.set_source(primary, 0);
472 if nemesis {
473 self.add_address(harvest_sink, height);
475 }
476 let transaction = Transaction::from_bytes(bytes)
477 .map_err(|error| invalid(format!("トランザクションが読めません: {error}")))?;
478 if !nemesis {
479 self.check_nemesis_sink(
480 height,
481 &transaction.signer_public_key,
482 &transaction.signature,
483 )?;
484 if let Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) =
485 &transaction.body
486 {
487 for cosignature in aggregate.cosignatures() {
488 self.check_nemesis_sink(
489 height,
490 &cosignature.signer_public_key,
491 &cosignature.signature,
492 )?;
493 }
494 }
495 }
496 let size = bytes.len() as u64;
497 let fee = u64::from(block.fee_multiplier) * size;
498 total_fee += fee;
499 self.apply_transaction(height, block.timestamp, primary, &transaction, size, fee)?;
500 }
501 self.current_transaction = None;
502 if nemesis {
503 self.add_address(harvest_sink, height);
504 }
505 self.statement.set_source(0, 0);
506 if !nemesis {
507 self.check_nemesis_sink(height, &block.signer_public_key, &block.signature)?;
508 self.check_harvester_balance(&block.signer_public_key)?;
509 }
510 self.apply_block_notifications(height, block, total_fee)?;
511 self.update_high_value();
512 let importance_height = self.config.importance_height(height + 1);
513 if importance_height != self.last_importance_height {
514 self.recalculate_importances(importance_height);
515 self.last_importance_height = importance_height;
516 }
517 if nemesis && self.producing {
518 self.produced_footer = Some(self.voting_footer(None));
520 }
521 if block.block_type == BlockType::Importance {
522 if self.producing {
523 self.produced_footer = Some(self.importance_footer(height));
524 } else if let Some(footer) = &block.importance_footer {
525 self.check_importance_footer(height, footer)?;
526 }
527 }
528 self.update_dynamic_fee_multiplier(block.fee_multiplier);
529 if let Some((total, last)) = &mut self.score {
530 let current = BlockStatistic::from(block);
531 *total = if nemesis {
532 NEMESIS_CHAIN_SCORE
533 } else {
534 *total + u128::from(block_score(last, ¤t))
535 };
536 *last = current;
537 }
538 self.unsaved_accounts.extend(self.touched.iter().copied());
539 self.dirty_accounts.append(&mut self.touched);
540 self.height = height;
541 self.last_statement = self.statement.take();
542 Ok(())
543 }
544
545 pub fn failed_transaction(&self) -> Option<usize> {
550 self.current_transaction
551 }
552
553 pub fn apply_produced(&mut self, block: &Block) -> Result<Produced, ExecError> {
554 self.producing = true;
555 let applied = self.apply(block);
556 self.producing = false;
557 applied?;
558 let statement = self.take_statement();
559 Ok(Produced {
560 state_hash: self.state_hash(),
561 receipts_hash: statement.merkle_hash(),
562 footer: self.produced_footer.take(),
563 statement,
564 })
565 }
566
567 pub fn take_statement(&mut self) -> BlockStatement {
569 std::mem::take(&mut self.last_statement)
570 }
571
572 pub fn roots(&mut self) -> [Hash256; 9] {
574 let mut roots = [crate::tree::EMPTY_ROOT; 9];
575 roots[SubCache::AccountState.index()] = self.account_root();
576 let due = self.expiries.split_off(&(self.height + 1));
577 for (_, rows) in std::mem::replace(&mut self.expiries, due) {
578 self.dirty_rows.extend(rows);
579 }
580 for row in std::mem::take(&mut self.dirty_rows) {
581 let cache = SubCache::ALL[usize::from(row[0])];
582 let key = tree_key(cache, &row[1..]);
583 match self.leaf(cache, &row[1..]) {
584 Some(value) => self.trees[cache.index()].set(key, value),
585 None => self.trees[cache.index()].remove(&key),
586 }
587 }
588 for cache in SubCache::ALL {
589 if cache != SubCache::AccountState {
590 roots[cache.index()] = self.trees[cache.index()].root();
591 }
592 }
593 roots
594 }
595
596 pub fn restore_trees(
599 &mut self,
600 nodes: impl IntoIterator<Item = (Vec<u8>, Vec<u8>)>,
601 ) -> Result<(), ExecError> {
602 let mut grouped: [Vec<_>; 9] = Default::default();
603 for (key, bytes) in nodes {
604 let (cache, position) = crate::tree::parse_node_key(&key)
605 .filter(|(cache, _)| usize::from(*cache) < 9)
606 .ok_or_else(|| {
607 ExecError::Source("しまった木のノードのキーが読めません".to_owned())
608 })?;
609 let node = TreeNode::decode_all(&bytes)
610 .ok()
611 .and_then(|nodes| nodes.into_iter().next())
612 .ok_or_else(|| ExecError::Source("しまった木のノードが読めません".to_owned()))?;
613 grouped[usize::from(cache)].push((position, node));
614 }
615 for (tree, nodes) in self.trees.iter_mut().zip(grouped) {
616 if tree.as_lazy_mut().is_none() {
618 *tree = StateTree::Full(PatriciaTree::from_nodes(nodes));
619 }
620 }
621 self.dirty_accounts.clear();
622 self.dirty_rows.clear();
623 Ok(())
624 }
625
626 pub fn rebuild_trees(&mut self) {
628 self.trees = Default::default();
629 for tree in &mut self.trees {
631 tree.track_node_changes(false);
632 }
633 self.dirty_accounts = self.accounts.keys().copied().collect();
634 self.dirty_rows = self.rows_for_rebuild();
635 }
636
637 pub fn take_node_changes(&mut self) -> Vec<(Vec<u8>, Option<Vec<u8>>)> {
640 let mut changes = Vec::new();
641 for (index, tree) in self.trees.iter_mut().enumerate() {
642 for (position, node) in tree.take_node_changes() {
643 changes.push((
644 crate::tree::node_key(index as u8, &position),
645 node.as_ref().map(TreeNode::encode),
646 ));
647 }
648 }
649 changes
650 }
651
652 pub fn forget_node_changes(&mut self) {
654 for tree in &mut self.trees {
655 tree.forget_node_changes();
656 tree.track_node_changes(true);
657 }
658 }
659
660 pub fn all_nodes(&mut self) -> Option<Vec<(Vec<u8>, Vec<u8>)>> {
662 let mut nodes = Vec::new();
663 self.forget_node_changes();
664 for (index, tree) in self.trees.iter_mut().enumerate() {
665 for (position, node) in tree.as_full_mut()?.nodes() {
666 nodes.push((crate::tree::node_key(index as u8, &position), node.encode()));
667 }
668 }
669 Some(nodes)
670 }
671
672 pub fn leaf_of_row(&self, row: &[u8]) -> (SubCache, Hash256, Option<Hash256>) {
674 let (cache, key) = tree_key_of_row(row);
675 let value = self.trees[cache.index()]
676 .as_full()
677 .and_then(|tree| tree.get(&key));
678 (cache, key, value)
679 }
680
681 pub fn state_bytes_of_row(&self, row: &[u8]) -> Option<Vec<u8>> {
684 let cache = SubCache::ALL[usize::from(row[0])];
685 if cache == SubCache::AccountState {
686 let account = self.accounts.get(&<[u8; 24]>::try_from(&row[1..]).ok()?)?;
687 Some(account.to_state_bytes(self.config.currency_mosaic_id))
688 } else {
689 self.state_bytes(cache, &row[1..])
690 }
691 }
692
693 pub fn path_of_row(&mut self, row: &[u8]) -> Option<Vec<TreeNode>> {
695 let (cache, key, _) = self.leaf_of_row(row);
696 Some(self.trees[cache.index()].as_full_mut()?.path(&key))
697 }
698
699 pub fn check_harvester(
709 &self,
710 parent: &Block,
711 parent_generation_hash: &GenerationHash,
712 block: &Block,
713 parameters: &heika_core::network::NetworkParameters,
714 ) -> Result<GenerationHash, ExecError> {
715 let vrf_key = self.check_hit(parent, block, parameters)?;
716 let proof_hash = heika_core::vrf::verify_with(
717 &vrf_key,
718 &parent_generation_hash.0,
719 &block.generation_hash_proof,
720 parameters.vrf_checks(block.height),
721 )
722 .ok_or_else(|| harvester_error("VRF の証明が通りません"))?;
723 Ok(proof_hash.generation_hash())
724 }
725
726 pub fn check_hit(
732 &self,
733 parent: &Block,
734 block: &Block,
735 parameters: &heika_core::network::NetworkParameters,
736 ) -> Result<PublicKey, ExecError> {
737 let forwarded = self.harvester(&block.signer_public_key)?;
738 let importance = self.importance_of(forwarded, block.height);
739 if !heika_block::scoring::is_hit(parent, block, importance, parameters) {
740 return Err(harvester_error("当たりではありません"));
741 }
742 Ok(PublicKey(forwarded.vrf.unwrap_or([0; 32])))
744 }
745
746 pub fn harvester_importance(&self, block: &Block) -> Result<u64, ExecError> {
748 self.signer_importance(&block.signer_public_key, block.height)
749 }
750
751 pub fn signer_importance(&self, signer: &PublicKey, height: u64) -> Result<u64, ExecError> {
753 Ok(self.importance_of(self.harvester(signer)?, height))
754 }
755
756 pub fn harvester_address(&self, signer: &PublicKey) -> Result<[u8; 24], ExecError> {
758 Ok(self.harvester(signer)?.address)
759 }
760
761 fn harvester(&self, signer: &PublicKey) -> Result<&AccountState, ExecError> {
763 let account = self
764 .accounts
765 .get(&self.address_of(signer))
766 .filter(|account| account.public_key_height != 0 && account.public_key == signer.0)
767 .ok_or_else(|| harvester_error("署名者のアカウントがありません"))?;
768 Ok(match account.account_type {
769 AccountType::Remote => {
770 let main = account
771 .linked
772 .ok_or_else(|| harvester_error("リモートなのにメインアカウントがありません"))?;
773 self.accounts
774 .get(&self.address_of(&PublicKey(main)))
775 .ok_or_else(|| harvester_error("メインアカウントがありません"))?
776 }
777 _ => account,
778 })
779 }
780
781 fn importance_of(&self, account: &AccountState, height: u64) -> u64 {
783 let snapshot = account.snapshots[0];
784 if snapshot.height == self.config.importance_height(height) {
785 snapshot.importance
786 } else {
787 0
788 }
789 }
790
791 pub fn harvesting_stake(&self) -> u128 {
794 let mosaic = self.config.harvesting_mosaic_id;
795 self.high_value
796 .iter()
797 .filter_map(|address| self.accounts.get(address))
798 .map(|account| u128::from(account.balance(mosaic)))
799 .sum()
800 }
801
802 pub fn voting_set(&self, epoch: u32) -> heika_block::finalization::proof::VotingSet {
806 let config = &self.config.finalization;
807 let mosaic = self.config.harvesting_mosaic_id;
808 let mut set = heika_block::finalization::proof::VotingSet::default();
809 let candidates: Box<dyn Iterator<Item = &[u8; 24]>> =
811 if config.min_voter_balance >= self.config.min_harvester_balance {
812 Box::new(self.high_value.iter())
813 } else {
814 Box::new(self.accounts.keys())
815 };
816 for address in candidates {
817 let Some(account) = self.accounts.get(address) else {
818 continue;
819 };
820 let balance = account.balance(mosaic);
821 if account.voting.is_empty() || balance < config.min_voter_balance {
822 continue;
823 }
824 let Some(key) = account
825 .voting
826 .iter()
827 .find(|key| key.start_epoch <= epoch && epoch <= key.end_epoch)
828 else {
829 continue;
830 };
831 if key.key == [0; 32] {
833 continue;
834 }
835 if config.treasury_reissuance_epoch <= epoch
836 && config.ineligible_voters.contains(address)
837 {
838 continue;
839 }
840 set.voters.insert(key.key, balance);
841 }
842 set
843 }
844
845 pub fn state_hash(&mut self) -> Hash256 {
847 state_hash(&self.roots())
848 }
849
850 fn touch(&mut self, cache: SubCache, key: &[u8]) {
852 let row = persist::row_key(cache, key);
853 self.dirty_rows.insert(row.clone());
854 self.unsaved_rows.insert(row);
855 }
856
857 fn locks_due(&self, height: u64, cache: SubCache) -> BTreeSet<[u8; 32]> {
859 let index = cache.index() as u8;
860 self.expiries
861 .get(&height)
862 .map_or_else(BTreeSet::new, |rows| {
863 rows.iter()
864 .filter(|row| row.first() == Some(&index))
865 .filter_map(|row| row[1..].try_into().ok())
866 .collect()
867 })
868 }
869
870 fn expire_at(&mut self, height: u64, cache: SubCache, key: &[u8]) {
872 if height != u64::MAX {
873 self.expiries
874 .entry(height)
875 .or_default()
876 .push(persist::row_key(cache, key));
877 }
878 }
879
880 fn apply_transaction(
883 &mut self,
884 height: u64,
885 timestamp: u64,
886 primary: u32,
887 transaction: &Transaction,
888 size: u64,
889 fee: u64,
890 ) -> Result<(), ExecError> {
891 let hash = transaction.hash(&self.generation_hash_seed);
892 self.check_transaction(height, timestamp, transaction, &hash, size, fee)?;
893 if self.remember_hash(transaction.deadline, hash.0) {
894 self.attempt_hashes.push((transaction.deadline, hash.0));
895 }
896 let signer = self.add_public_key(&transaction.signer_public_key, height);
897 self.check_transaction_rules(signer, transaction.body.transaction_type())?;
898 if fee > 0 {
900 let importance_height = self.config.importance_height(height);
901 self.account_mut(&signer)?
902 .try_update_bucket(importance_height, |bucket| bucket.total_fees_paid += fee);
903 }
904 let currency = self.config.currency_mosaic_id;
907 let fee_first = height < self.config.total_voting_balance_calculation_fix;
908 if fee_first {
909 self.debit(&signer, currency, fee)?;
910 }
911 match &transaction.body {
912 Body::AggregateComplete(aggregate) | Body::AggregateBonded(aggregate) => {
913 let cosigners = self.cosigners(transaction, aggregate);
914 self.check_eligible_cosigners(&cosigners, aggregate)?;
915 if matches!(transaction.body, Body::AggregateBonded(_)) {
916 self.touch(SubCache::HashLockInfo, &hash.0);
918 let lock = self
919 .hash_locks
920 .get_mut(&hash.0)
921 .and_then(|history| history.last_mut())
922 .ok_or_else(|| {
923 invalid(format!("アグリゲート {hash} のロックがありません"))
924 })?;
925 lock.status = LockStatus::Used;
926 let (owner, mosaic_id, amount) = (lock.owner, lock.mosaic_id, lock.amount);
927 self.credit(&owner, mosaic_id, amount)?;
928 self.statement
929 .add_receipt(ReceiptBody::LockHashCompleted(change(
930 owner, mosaic_id, amount,
931 )));
932 }
933 for (index, inner) in aggregate.transactions().iter().enumerate() {
935 self.statement.set_source(primary, index as u32 + 1);
937 self.check_sufficient_cosigners(&cosigners, inner)?;
939 let inner_signer = self.add_public_key(&inner.signer_public_key, height);
940 self.apply_body(height, inner_signer, &inner.signer_public_key, &inner.body)?;
941 }
942 }
943 body => self.apply_body(height, signer, &transaction.signer_public_key, body)?,
944 }
945 if !fee_first {
946 self.debit(&signer, currency, fee)?;
947 }
948 Ok(())
949 }
950
951 fn apply_body(
953 &mut self,
954 height: u64,
955 signer: [u8; 24],
956 signer_key: &PublicKey,
957 body: &Body,
958 ) -> Result<(), ExecError> {
959 self.check_body_rules(height, signer, body)?;
960 self.apply_checked_body(height, signer, signer_key, body)
961 }
962
963 fn apply_checked_body(
965 &mut self,
966 height: u64,
967 signer: [u8; 24],
968 signer_key: &PublicKey,
969 body: &Body,
970 ) -> Result<(), ExecError> {
971 let is_nemesis_signer = height == 1 && signer == self.nemesis;
972 match body {
973 Body::Transfer(transfer) => {
974 self.apply_transfer(height, signer, is_nemesis_signer, transfer)?;
975 }
976 Body::MosaicDefinition(definition) => {
977 self.apply_mosaic_definition(height, signer, is_nemesis_signer, definition)?;
978 }
979 Body::MosaicSupplyChange(change) => {
980 self.apply_mosaic_supply_change(height, signer, change)?;
981 }
982 Body::MosaicSupplyRevocation(revocation) => {
983 self.apply_mosaic_supply_revocation(height, signer, revocation)?;
984 }
985 Body::NamespaceRegistration(registration) => {
986 self.apply_namespace_registration(height, signer, is_nemesis_signer, registration)?;
987 }
988 Body::MosaicAlias(alias) => {
989 self.apply_mosaic_alias(height, signer, alias)?;
990 }
991 Body::AddressAlias(alias) => {
992 self.apply_address_alias(height, signer, alias)?;
993 }
994 Body::MultisigAccountModification(modification) => {
995 self.apply_multisig(height, signer, modification)?;
996 }
997 Body::AccountKeyLink(link) => {
998 self.apply_account_key_link(height, signer, signer_key, link)?;
999 }
1000 Body::VrfKeyLink(link) | Body::NodeKeyLink(link) => {
1001 self.apply_vrf_or_node_key_link(signer, body, link)?;
1002 }
1003 Body::VotingKeyLink(link) => {
1004 self.apply_voting_key_link(signer, link)?;
1005 }
1006 Body::AccountMetadata(metadata) => {
1007 self.apply_metadata(signer, metadata, 0, MetadataType::Account)?;
1008 }
1009 Body::MosaicMetadata(metadata) => {
1010 let id = self.resolve_mosaic(metadata.target_mosaic_id.0)?;
1011 self.apply_metadata(signer, &metadata.metadata, id, MetadataType::Mosaic)?;
1012 }
1013 Body::NamespaceMetadata(metadata) => {
1014 let id = metadata.target_namespace_id.0;
1015 self.apply_metadata(signer, &metadata.metadata, id, MetadataType::Namespace)?;
1016 }
1017 Body::HashLock(lock) => {
1018 self.apply_hash_lock(height, signer, lock)?;
1019 }
1020 Body::SecretLock(lock) => {
1021 self.apply_secret_lock(height, signer, lock)?;
1022 }
1023 Body::SecretProof(proof) => {
1024 self.apply_secret_proof(height, proof)?;
1025 }
1026 Body::AccountAddressRestriction(restriction) => {
1027 self.apply_account_address_restriction(signer, restriction)?;
1028 }
1029 Body::AccountMosaicRestriction(restriction) => {
1030 self.apply_account_mosaic_restriction(signer, restriction)?;
1031 }
1032 Body::AccountOperationRestriction(restriction) => {
1033 self.apply_account_operation_restriction(signer, restriction)?;
1034 }
1035 Body::MosaicGlobalRestriction(restriction) => {
1036 self.apply_mosaic_global_restriction(restriction)?;
1037 }
1038 Body::MosaicAddressRestriction(restriction) => {
1039 self.apply_mosaic_address_restriction(restriction)?;
1040 }
1041 other => {
1042 let name = format!("{other:?}");
1043 let name = name.split(['(', ' ', '{']).next().unwrap_or("?");
1044 return Err(ExecError::Unsupported(name.to_owned()));
1045 }
1046 }
1047 Ok(())
1048 }
1049
1050 }
1052
1053const PARALLEL_LEAVES: usize = 512;
1055
1056pub fn tree_key_of_row(row: &[u8]) -> (SubCache, Hash256) {
1058 let cache = SubCache::ALL[usize::from(row[0])];
1059 let key = if cache == SubCache::AccountState {
1060 address_key(&Address(row[1..].try_into().expect("address")))
1061 } else {
1062 tree_key(cache, &row[1..])
1063 };
1064 (cache, key)
1065}
1066
1067fn change(address: [u8; 24], mosaic_id: u64, amount: u64) -> BalanceChange {
1069 BalanceChange {
1070 mosaic: ReceiptMosaic {
1071 mosaic_id: MosaicId(mosaic_id),
1072 amount,
1073 },
1074 target_address: Address(address),
1075 }
1076}
1077
1078fn transfer_receipt(from: [u8; 24], to: [u8; 24], mosaic_id: u64, amount: u64) -> BalanceTransfer {
1080 BalanceTransfer {
1081 mosaic: ReceiptMosaic {
1082 mosaic_id: MosaicId(mosaic_id),
1083 amount,
1084 },
1085 sender_address: Address(from),
1086 recipient_address: Address(to),
1087 }
1088}
1089
1090fn tree_key(cache: SubCache, key: &[u8]) -> Hash256 {
1092 match key.len() {
1093 8 => id_key(u64::from_le_bytes(key.try_into().expect("8 bytes"))),
1094 24 => address_key(&Address(key.try_into().expect("24 bytes"))),
1095 _ => {
1096 debug_assert!(!matches!(cache, SubCache::Namespace | SubCache::Mosaic));
1097 hash_key(&Hash256(key.try_into().expect("32 bytes")))
1098 }
1099 }
1100}
1101
1102fn mosaic_restriction_type(restriction_type: heika_transaction::MosaicRestrictionType) -> u8 {
1104 use heika_transaction::MosaicRestrictionType as Type;
1105 match restriction_type {
1106 Type::None => 0,
1107 Type::Eq => 1,
1108 Type::Ne => 2,
1109 Type::Lt => 3,
1110 Type::Le => 4,
1111 Type::Gt => 5,
1112 Type::Ge => 6,
1113 }
1114}
1115
1116fn hash_algorithm_byte(algorithm: heika_transaction::LockHashAlgorithm) -> u8 {
1118 match algorithm {
1119 heika_transaction::LockHashAlgorithm::Sha3_256 => 0,
1120 heika_transaction::LockHashAlgorithm::Hash160 => 1,
1121 heika_transaction::LockHashAlgorithm::Hash256 => 2,
1122 }
1123}
1124
1125fn sha3(bytes: &[u8]) -> Hash256 {
1126 Hash256(Sha3_256::digest(bytes).into())
1127}
1128
1129fn harvester_error(what: &str) -> ExecError {
1130 ExecError::Invalid(format!("ブロックを出した人: {what}"))
1131}