Skip to main content

heika_state_transition/executor/
mod.rs

1//! ブロックを実行して、状態を進める。catapult の observer を、状態の木に効くところだけ移したもの。
2//!
3//! 今はメモリの中だけで持ち、根は求めるたびに葉から組み直す。まだ移していないトランザクションの種類や
4//! 状態が出てきたら、黙って進めずに [`ExecError::Unsupported`] で止める。
5//!
6//! 1つのブロックの中の順番は catapult の `NotificationPublisher` と `CoreSystem` の observer に合わせる。
7//! トランザクションを順に、最後にブロックそのもの。ブロックのあとに、大口のアカウントの更新、importance の計算し直し、
8//! 手数料の倍率の更新。
9
10mod 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/// 実行できなかったわけ。
62#[derive(Clone, PartialEq, Eq, Debug)]
63pub enum ExecError {
64    /// この実装が扱わないもの(知らない種類のトランザクション、扱わない設定)
65    Unsupported(String),
66    /// ブロックが規則に合わない(残高が足りない、知らない ID、validator が弾いたなど)
67    Invalid(String),
68    /// 状態の読み口([`source::StateSource`])から読めなかった。ブロックのせいではない
69    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/// ネームスペースの別名
89#[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/// ルートのネームスペースの、今の持ち主のもの。catapult の `RootNamespace`。
113#[derive(Clone, Debug)]
114struct RootNamespace {
115    owner: [u8; 24],
116    start: u64,
117    /// 猶予を含めた終わり。期限がなければ u64::MAX
118    end: u64,
119    alias: Alias,
120    /// ルートを除いた経路 → 別名
121    children: BTreeMap<Vec<u64>, Alias>,
122}
123
124/// 期限切れのレシートを出すもの。並びはレシートを出す順(ID の順)
125#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
126enum Artifact {
127    Namespace(u64),
128    Mosaic(u64),
129}
130
131/// catapult の `MosaicEntry`。
132#[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    /// catapult の `MosaicDefinition::isActive`。期間 0 は期限なし
145    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/// catapult の `MultisigEntry`。
152#[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/// 連署の数を数えるときの、トランザクションの種類。連署者を外すだけなら min removal、足しもするなら大きいほう
161#[derive(Clone, Copy, PartialEq, Eq, Debug)]
162enum MultisigOperation {
163    Normal,
164    Removal,
165    Both,
166}
167
168/// マルチシグを連署者へたどる深さの上限。正しいチェーンでは `maxMultisigDepth`(3)までしかない
169const MAX_MULTISIG_WALK: usize = 8;
170
171/// モザイクのフラグの全部(catapult の `MosaicFlags::All`)
172const MOSAIC_FLAGS_ALL: u8 = 0x0F;
173
174/// アカウントの制限の1種類。catapult の `AccountRestriction`。
175#[derive(Clone, Debug)]
176struct AccountRestriction {
177    /// 向き(Outgoing)と種類に、Block の印を合わせたもの
178    descriptor: u16,
179    values: BTreeSet<Vec<u8>>,
180}
181
182/// Block の印
183const RESTRICTION_BLOCK: u16 = 0x8000;
184
185/// catapult の `AccountRestrictions`。向きと種類の4つ(ブロックの印を除いたフラグ)ごとに持つ
186fn 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/// ロックの状態。catapult の `LockInfo` の `Status`
202#[derive(Clone, Copy, PartialEq, Eq, Debug)]
203enum LockStatus {
204    Unused = 0,
205    Used = 1,
206}
207
208/// catapult の `HashLockInfo`。同じハッシュのものは履歴として並び、葉にするのは最後のもの
209#[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/// catapult の `SecretLockInfo`。キーはシークレットと受取人から求めたハッシュ
219#[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/// catapult の `MosaicRestrictionEntry`。キーはモザイクとアドレスから求めたハッシュ(全体の制限ではアドレスが0)
232#[derive(Clone, Debug, PartialEq)]
233enum MosaicRestrictionEntry {
234    /// アドレスごとの値。キー → 値
235    Address {
236        mosaic_id: u64,
237        address: [u8; 24],
238        values: BTreeMap<u64, u64>,
239    },
240    /// モザイク全体の決まり。キー → (条件を借りるモザイク、値、比べ方)
241    Global {
242        mosaic_id: u64,
243        rules: BTreeMap<u64, (u64, u64, u8)>,
244    },
245}
246
247impl MosaicRestrictionEntry {
248    /// catapult の `MosaicRestrictionEntrySerializer` の形。版の番号は付けない
249    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
289/// catapult の `CreateMosaicRestrictionEntryKey`
290fn 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
297/// アドレスの制限で、値を消すことを表す値(catapult の `Sentinel_Removal_Value`)
298const MOSAIC_RESTRICTION_REMOVAL: u64 = u64::MAX;
299
300/// 実行している状態。
301pub struct Executor {
302    config: ChainConfig,
303    network: NetworkIdentifier,
304    /// 実行した最後の高さ
305    height: u64,
306    accounts: Table<[u8; 24], AccountState>,
307    /// このブロックで触ったアカウント。大口かどうかを見直す
308    touched: BTreeSet<[u8; 24]>,
309    /// 前に根を求めてから変わったかもしれないアカウント
310    dirty_accounts: BTreeSet<[u8; 24]>,
311    /// 9本の木。SubCache の順
312    trees: [StateTree; 9],
313    /// 前に DB に書いてから変わったかもしれないアカウント
314    unsaved_accounts: BTreeSet<[u8; 24]>,
315    /// アカウント以外で、前に根を求めてから変わったかもしれない行([`persist::row_key`])
316    dirty_rows: BTreeSet<Vec<u8>>,
317    /// アカウント以外で、前に DB に書いてから変わったかもしれない行
318    unsaved_rows: BTreeSet<Vec<u8>>,
319    /// 期限が来て木から外れる高さ → 行。書き換えなしで木が変わるので、その高さで根を求め直す
320    expiries: BTreeMap<u64, Vec<Vec<u8>>>,
321    /// 期限切れのレシートが出るかもしれない高さ → ネームスペースとモザイク。その高さで今の期限と照らす
322    artifact_expiries: BTreeMap<u64, BTreeSet<Artifact>>,
323    high_value: BTreeSet<[u8; 24]>,
324    /// 大口から外れたが、履歴が残っているもの
325    removed: BTreeSet<[u8; 24]>,
326    last_importance_height: u64,
327    namespaces: BTreeMap<u64, RootNamespace>,
328    /// ネームスペースの ID → ルートからの経路
329    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    /// 1件を指すハッシュ → (キー、値)
336    metadata: Table<[u8; 32], (MetadataKey, Vec<u8>)>,
337    mosaic_restrictions: BTreeMap<[u8; 32], MosaicRestrictionEntry>,
338    generation_hash_seed: heika_core::network::GenerationHashSeed,
339    /// 最近のブロックの手数料の倍率。新しいものが後ろ
340    fee_multipliers: VecDeque<u32>,
341    /// レンタル料に掛ける倍率。1つ前のブロックのあとで求めたもの
342    dynamic_fee_multiplier: u32,
343    nemesis: [u8; 24],
344    /// Nemesis の最初の送金のときに、送り手に残高がなかったか(catapult の `NemesisFundingObserver`)
345    implicit_funding: Option<bool>,
346    /// 期限切れの処理を飛ばした高さ(`skipSecretLockExpirations`)で切れたシークレットロック。
347    /// catapult の木は書き換えたものだけを見直すので、次にそのキーに触れるまで、切れたまま木に残る
348    stale_secret_locks: BTreeSet<[u8; 32]>,
349    /// ジェネシスからのチェーンのスコア(catapult の `ChainScore`)と、最後のブロック。ピアと比べてどの枝を取るかを決める。
350    /// 前の DB の実行の状態にはないので、そのときは `None` で、[`Executor::set_score`] で入れる
351    score: Option<(u128, BlockStatistic)>,
352    /// 期限が過ぎていないトランザクションのハッシュ(catapult の `HashCache`)。同じトランザクションの二度入れを弾く。
353    /// 状態の木に入らないので、しまわない。途中から実行するときは [`Executor::remember_transactions`] で作り直す
354    recent_hashes: HashSet<[u8; 32]>,
355    /// 期限 → その期限のハッシュ。ブロックの時刻より前の期限のものは、もう入りえないので捨てる
356    hash_deadlines: BTreeMap<u64, Vec<[u8; 32]>>,
357    /// 最後の [`Executor::apply`] で新しく覚えたハッシュと、その期限。当てた実行を [`Executor::undo_attempt`] で
358    /// 戻すときは、これだけを忘れる。前から覚えていたもの(二度入れで弾いたトランザクションのものなど)は忘れない
359    attempt_hashes: Vec<(u64, [u8; 32])>,
360    /// 実行しているブロックのステートメント
361    statement: StatementBuilder,
362    /// 最後に実行したブロックのステートメント
363    last_statement: BlockStatement,
364    /// ブロックを作っているところ([`Executor::apply_produced`])。importance ブロックの足を比べずに求める
365    producing: bool,
366    /// 作っているブロックの importance ブロックの足(投票できる数、ハーベストできる数、投票の残高の合計)
367    produced_footer: Option<(u32, u64, u64)>,
368    /// 当てている(弾いたなら、弾いた)トランザクションが、ブロックの何件目か(0から)。作るときに外すものを決める
369    current_transaction: Option<usize>,
370}
371
372/// 作るブロックを当てて求めた、ヘッダーに書くもの
373pub struct Produced {
374    pub state_hash: Hash256,
375    pub receipts_hash: Hash256,
376    /// importance ブロックと Nemesis の足(投票できる数、ハーベストできる数、投票の残高の合計)。ほかのブロックは `None`
377    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    /// 実行した最後の高さ。
437    pub fn height(&self) -> u64 {
438        self.height
439    }
440
441    /// ジェネシスからのチェーンのスコア。前の DB から戻してまだ入れていなければ `None`
442    pub fn score(&self) -> Option<u128> {
443        self.score.map(|(total, _)| total)
444    }
445
446    /// 前の DB から戻したときに、しまったブロックから求めたスコアと、最後のブロックを入れる
447    pub fn set_score(&mut self, total: u128, last: BlockStatistic) {
448        self.score = Some((total, last));
449    }
450
451    /// 次の高さのブロックを実行する。ブロックそのものは確かめてあること。
452    pub fn apply(&mut self, block: &Block) -> Result<(), ExecError> {
453        // 前に弾いたときの何件目かを、トランザクションを当てる前に弾いたときに残さない
454        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            // ステートメントの元は、トランザクションの何件目か(1から)
469            let primary = index as u32 + 1;
470            self.current_transaction = Some(index);
471            self.statement.set_source(primary, 0);
472            if nemesis {
473                // Nemesis では、どのエンティティの前にも手数料の受け取り先のアカウントを作る
474                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            // catapult の nemgen は、Nemesis の足をエポック 0 で、つまりエポックで絞らずに数える
519            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, &current))
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    /// 作るブロックを当てて、ヘッダーに書く StateHash、ReceiptsHash、importance ブロックの足を求める。
546    /// ブロックのそれらは見ない(0 のままでよい)。どれも状態を変えないので、当てたあとの状態は、求めたものを書いた
547    /// ブロックを実行したあとのものと同じ。通らなければ状態は途中のままなので、捨てて戻し直すこと
548    /// 最後の [`Executor::apply`] がトランザクションを当てているところで弾いたなら、それがブロックの何件目か(0から)
549    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    /// 最後に実行したブロックのステートメント。この Merkle の根が、ブロックの ReceiptsHash になる
568    pub fn take_statement(&mut self) -> BlockStatement {
569        std::mem::take(&mut self.last_statement)
570    }
571
572    /// 9本の木の根。アカウントは変わったものだけ、ほかは葉を並べ直して、変わった道だけを計算し直す。
573    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    /// しまった木のノードから9本の木を戻す。行から組み直すと全部の葉とノードのハッシュを求め直すが、
597    /// こちらはハッシュをほとんど求めない。戻したあとで、根がブロックの StateHash と合うかを確かめること
598    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            // 必要なノードだけを持つ木は、全部を組み直さない
617            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    /// 木を捨てて、行から組み直すことにする。[`Executor::restore_trees`] の根が合わなかったとき
627    pub fn rebuild_trees(&mut self) {
628        self.trees = Default::default();
629        // 全部のノードが変わったことになるので、覚えない。組んだら DB に合わせて [`Executor::forget_node_changes`] する
630        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    /// 前に呼んでから変わった、9本の木のノード。キー([`crate::tree::node_key`])と、
638    /// 今のノードのバイト列か、なくなったら `None`。[`Executor::roots`] のあとで呼ぶ
639    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    /// 木の組み直しなどで溜まったノードの変化を捨てて、これからの変化を覚える。DB にあるものと同じ木のとき
653    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    /// 9本の木のノードを全部。[`Executor::roots`] のあとで呼ぶ。必要なノードだけを持つ木があれば `None`
661    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    /// 行([`persist::row_key`])の、木の番号と木のキーと、木にある葉の値。[`Executor::roots`] のあとで呼ぶ
673    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    /// 行の、木の葉の値のもとになる catapult の形のバイト列。この SHA3-256 が葉の値になる。
682    /// 木の中を見ないので、行だけから戻した状態でも使える。木に入らなければ `None`
683    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    /// 行の葉への経路。[`Executor::roots`] のあとで呼ぶ。必要なノードだけを持つ木なら `None`
694    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    /// `block` を出したアカウントに、その資格があるか。1つ前のブロック `parent` のあとの状態で、実行する前に呼ぶ。
700    /// catapult の `BlockchainProcessor` の `CheckGenerationHash` と `BlockHitPredicate`:
701    ///
702    /// 1. 署名者のアカウントが、公開鍵で見つかる
703    /// 2. 署名者がリモートならメインアカウントの、VRF の鍵で、`parent_generation_hash` の証明が通る
704    /// 3. 証明から出た generation hash で当たりになる。importance は、リモートならメインアカウントの、
705    ///    その高さの importance の高さのもの。違う高さのものしかなければ 0
706    ///
707    /// 通れば、このブロックの generation hash を返す。
708    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    /// [`Executor::check_harvester`] のうち、状態を見るところ(1 と 3)。VRF の証明はまだ確かめずに、証明の gamma から
727    /// 出る generation hash で当たりかを見る。通れば、証明を確かめるのに使う VRF の鍵を返す。
728    ///
729    /// 証明は状態に依らないので、呼んだ側が別に(別のスレッドなどで)[`heika_core::vrf::verify`] で確かめる。
730    /// 確かめ終えるまで、このブロックは確かめたことにならない
731    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        // VRF の鍵がなければ、catapult は0の鍵で確かめるので通らない
743        Ok(PublicKey(forwarded.vrf.unwrap_or([0; 32])))
744    }
745
746    /// `block` を出したアカウント(リモートならメインアカウント)の、そのブロックの高さで使う Importance
747    pub fn harvester_importance(&self, block: &Block) -> Result<u64, ExecError> {
748        self.signer_importance(&block.signer_public_key, block.height)
749    }
750
751    /// `signer` が高さ `height` のブロックを出すときに使う Importance(リモートならメインアカウントのもの)
752    pub fn signer_importance(&self, signer: &PublicKey, height: u64) -> Result<u64, ExecError> {
753        Ok(self.importance_of(self.harvester(signer)?, height))
754    }
755
756    /// `signer` の鍵でブロックを出したときに、報酬を受け取るアカウントのアドレス(リモートならメインアカウント)
757    pub fn harvester_address(&self, signer: &PublicKey) -> Result<[u8; 24], ExecError> {
758        Ok(self.harvester(signer)?.address)
759    }
760
761    /// `signer` の鍵でブロックを出すアカウント。リモートなら、リンクしたメインアカウント
762    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    /// `account` の、高さ `height` のブロックで使う Importance。最後のスナップショットがその高さのものでなければ 0
782    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    /// 大口のアカウント(収穫モザイクの残高が minHarvesterBalance 以上)の残高の合計。catapult が Importance を
792    /// 求めるときの `ActiveHarvestingMosaics`(ハーベストしているかに依らない)
793    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    /// 今の状態で決まる、エポック `epoch` の投票者。catapult の `FinalizationContext` の作り方と同じで、
803    /// 投票の鍵を持ち、収穫モザイクの残高が minVoterBalance 以上のアカウントの、そのエポックの鍵と残高。
804    /// 今の高さが `epoch` の1つ前のエポックの最後の高さのときに呼ぶ
805    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        // 投票者は大口のアカウントに入っている。大口の閾値のほうが低いので
810        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            // catapult と同じく、すべて 0 の鍵は投票しないものとする。リンクするときには弾かれない
832            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    /// 根から求めた StateHash。
846    pub fn state_hash(&mut self) -> Hash256 {
847        state_hash(&self.roots())
848    }
849
850    /// アカウント以外の行が変わったかもしれないことを覚える
851    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    /// `height` で期限が来ると覚えた、木 `cache` のロックのキー。ロックを作るたびに、その終わりの高さで覚えている
858    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    /// `height` で期限が来て、木から外れることを覚える
871    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    // region: トランザクション
881
882    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        // TransactionFeeActivity
899        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        // 手数料は、totalVotingBalanceCalculationFix より前は中身の前に、そこからは中身のあとに引く(catapult の
905        // `BasicNotificationPublisher`)。どちらも残高が足りなければ弾くので、順番で通るかどうかが変わる
906        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                    // CompletedAggregate: 預けてあったものを持ち主に返す
917                    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                // 連署者の公開鍵は、アカウントの状態には入らない
934                for (index, inner) in aggregate.transactions().iter().enumerate() {
935                    // 中のトランザクションは、元の2つ目の番号を1から振る
936                    self.statement.set_source(primary, index as u32 + 1);
937                    // 中のトランザクションごとに、その前までを当てた状態で、要る署名者が連署しているか
938                    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    /// 中身を確かめて当てる
952    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    /// 確かめた中身を当てる
964    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    // endregion
1051}
1052
1053/// アカウントの葉の値を並列に求める、変わったアカウントの数の下限。普通のブロックでは数十なので、並列にしない
1054const PARALLEL_LEAVES: usize = 512;
1055
1056/// 行([`persist::row_key`])の、木の番号と木のキー
1057pub 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
1067/// アカウントのモザイクが増えたか減ったレシートの本体
1068fn 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
1078/// モザイクが動いたレシートの本体
1079fn 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
1090/// 行のキーから、木のキー
1091fn 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
1102/// catapult の `MosaicRestrictionType` の値
1103fn 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
1116/// catapult の `LockHashAlgorithm` の値
1117fn 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}