Skip to main content

forest/interpreter/
vm.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use crate::blocks::Tipset;
5use crate::chain::block_messages;
6use crate::chain::index::ChainIndex;
7use crate::chain::store::Error;
8use crate::db::DbImpl;
9use crate::interpreter::{fvm2::ForestExternsV2, fvm3::ForestExternsV3, fvm4::ForestExternsV4};
10use crate::message::ChainMessage;
11use crate::message::MessageRead as _;
12use crate::networks::{ChainConfig, Height, NetworkChain};
13use crate::prelude::*;
14use crate::shim::actors::{AwardBlockRewardParams, cron, reward};
15use crate::shim::clock::ChainEpoch;
16use crate::shim::{
17    address::{Address, Protocol},
18    econ::TokenAmount,
19    executor::{ApplyRet, Receipt, StampedEvent},
20    externs::Rand,
21    machine::MultiEngine,
22    message::{Message, Message_v3},
23    state_tree::{ActorState, StateTree},
24    version::NetworkVersion,
25};
26use ahash::{HashMap, HashSet};
27use anyhow::bail;
28use fvm_ipld_encoding::RawBytes;
29use fvm2::{
30    executor::{DefaultExecutor as DefaultExecutor_v2, Executor as Executor_v2},
31    machine::{
32        DefaultMachine as DefaultMachine_v2, Machine as Machine_v2,
33        NetworkConfig as NetworkConfig_v2,
34    },
35};
36use fvm3::{
37    executor::{DefaultExecutor as DefaultExecutor_v3, Executor as Executor_v3},
38    machine::{
39        DefaultMachine as DefaultMachine_v3, Machine as Machine_v3,
40        NetworkConfig as NetworkConfig_v3,
41    },
42};
43use fvm4::{
44    executor::{DefaultExecutor as DefaultExecutor_v4, Executor as Executor_v4},
45    machine::{
46        DefaultMachine as DefaultMachine_v4, Machine as Machine_v4,
47        NetworkConfig as NetworkConfig_v4,
48    },
49};
50use num::Zero;
51use spire_enum::prelude::delegated_enum;
52use std::time::{Duration, Instant};
53
54pub(in crate::interpreter) type ForestMachineV2 = DefaultMachine_v2<DbImpl, ForestExternsV2>;
55pub(in crate::interpreter) type ForestMachineV3 = DefaultMachine_v3<DbImpl, ForestExternsV3>;
56pub(in crate::interpreter) type ForestMachineV4 = DefaultMachine_v4<DbImpl, ForestExternsV4>;
57
58type ForestKernelV2 = fvm2::DefaultKernel<fvm2::call_manager::DefaultCallManager<ForestMachineV2>>;
59type ForestKernelV3 = fvm3::DefaultKernel<fvm3::call_manager::DefaultCallManager<ForestMachineV3>>;
60type ForestKernelV4 = fvm4::kernel::filecoin::DefaultFilecoinKernel<
61    fvm4::call_manager::DefaultCallManager<ForestMachineV4>,
62>;
63
64type ForestExecutorV2 = DefaultExecutor_v2<ForestKernelV2>;
65type ForestExecutorV3 = DefaultExecutor_v3<ForestKernelV3>;
66type ForestExecutorV4 = DefaultExecutor_v4<ForestKernelV4>;
67
68pub type ApplyResult = anyhow::Result<(ApplyRet, Duration)>;
69
70pub type ApplyBlockResult = anyhow::Result<(
71    Vec<Receipt>,
72    Vec<Option<Vec<StampedEvent>>>,
73    Vec<Option<Cid>>,
74)>;
75
76/// Comes from <https://github.com/filecoin-project/lotus/blob/v1.23.2/chain/vm/fvm.go#L473>
77pub const IMPLICIT_MESSAGE_GAS_LIMIT: i64 = i64::MAX / 2;
78
79/// Contains all messages to process through the VM as well as miner information
80/// for block rewards.
81#[derive(Debug)]
82pub struct BlockMessages {
83    pub miner: Address,
84    pub messages: Vec<ChainMessage>,
85    pub win_count: i64,
86}
87
88/// How tipset message senders are keyed for dedup, mirroring Lotus's lazy ID resolution.
89enum Keying<'a, DB> {
90    /// Pre-Hyperdrive: key by the raw sender address, never resolving.
91    Raw,
92    /// Hyperdrive era with no ID-form sender yet: key by the raw address, but resolve every sender
93    /// to its ID address as soon as one appears.
94    Lazy { db: &'a DB, parent_state: &'a Cid },
95    /// An ID-form sender has appeared: key by the resolved ID address.
96    Resolved(Box<StateTree<DB>>),
97}
98
99impl<DB: Blockstore + ShallowClone> Keying<'_, DB> {
100    /// The dedup key for `from`. On the first ID-form sender, loads the parent state, re-keys the
101    /// `applied` entries so far to their ID addresses, and switches to [`Keying::Resolved`].
102    fn sender_key(
103        &mut self,
104        from: Address,
105        applied: &mut HashMap<Address, u64>,
106    ) -> Result<Address, Error> {
107        match self {
108            Keying::Raw => Ok(from),
109            Keying::Resolved(state) => Ok(state.lookup_required_id_address(&from)?),
110            Keying::Lazy { db, parent_state } if from.protocol() == Protocol::ID => {
111                let (db, parent_state) = (*db, *parent_state);
112                let state = StateTree::new_from_root(db, parent_state)?;
113                for (robust, nonce) in std::mem::take(applied) {
114                    applied.insert(state.lookup_required_id_address(&robust)?, nonce);
115                }
116                let id = state.lookup_required_id_address(&from)?;
117                *self = Keying::Resolved(Box::new(state));
118                Ok(id)
119            }
120            Keying::Lazy { .. } => Ok(from),
121        }
122    }
123}
124
125impl BlockMessages {
126    /// Retrieves block messages to be passed through the VM and removes duplicate messages which appear in multiple blocks.
127    pub fn for_tipset<DB: Blockstore + ShallowClone>(
128        db: &DB,
129        ts: &Tipset,
130        chain_config: &ChainConfig,
131    ) -> Result<Vec<BlockMessages>, Error> {
132        // From Hyperdrive, dedup keys on the sender's resolved ID, lazily as in Lotus `BlockMsgsForTipset`.
133        // https://github.com/filecoin-project/lotus/blob/0065aa70bb20bf87801b6e96ecb7e7fe707566bd/chain/store/messages.go#L126-L182
134        let mut applied: HashMap<Address, u64> = HashMap::new();
135        let mut keying = if ts.epoch() >= chain_config.epoch(Height::Hyperdrive) {
136            Keying::Lazy {
137                db,
138                parent_state: ts.parent_state(),
139            }
140        } else {
141            Keying::Raw
142        };
143        let mut select_msg = |m: ChainMessage| -> Result<Option<ChainMessage>, Error> {
144            let sender = keying.sender_key(m.from(), &mut applied)?;
145            // The first match for a sender is guaranteed to have correct nonce
146            // the block isn't valid otherwise.
147            let entry = applied.entry(sender).or_insert_with(|| m.sequence());
148
149            if *entry != m.sequence() {
150                return Ok(None);
151            }
152
153            *entry += 1;
154            Ok(Some(m))
155        };
156
157        ts.block_headers()
158            .iter()
159            .map(|b| {
160                let (usm, sm) = block_messages(db, b)?;
161
162                let mut messages = Vec::with_capacity(usm.len() + sm.len());
163                for m in usm {
164                    messages.extend(select_msg(m.into())?);
165                }
166                for m in sm {
167                    messages.extend(select_msg(m.into())?);
168                }
169
170                Ok(BlockMessages {
171                    miner: b.miner_address,
172                    messages,
173                    win_count: b
174                        .election_proof
175                        .as_ref()
176                        .map(|e| e.win_count)
177                        .unwrap_or_default(),
178                })
179            })
180            .collect()
181    }
182}
183
184/// Interpreter which handles execution of state transitioning messages and
185/// returns receipts from the VM execution.
186#[delegated_enum(impl_conversions)]
187pub enum VM {
188    VM2(ForestExecutorV2),
189    VM3(ForestExecutorV3),
190    VM4(ForestExecutorV4),
191}
192
193pub struct ExecutionContext {
194    // This tipset identifies of the blockchain. It functions as a starting
195    // point when searching for ancestors. It may be any tipset as long as its
196    // epoch is at or higher than the epoch in `epoch`.
197    pub heaviest_tipset: Tipset,
198    // State-tree generated by the parent tipset.
199    pub state_tree_root: Cid,
200    // Epoch of the messages to be executed.
201    pub epoch: ChainEpoch,
202    // Source of deterministic randomness
203    pub rand: Box<dyn Rand>,
204    // https://spec.filecoin.io/systems/filecoin_vm/gas_fee/
205    pub base_fee: TokenAmount,
206    // https://filecoin.io/blog/filecoin-circulating-supply/
207    pub circ_supply: TokenAmount,
208    // The chain config is used to determine which consensus rules to use.
209    pub chain_config: Arc<ChainConfig>,
210    // Caching interface to the DB
211    pub chain_index: ChainIndex,
212    // UNIX timestamp for epoch
213    pub timestamp: u64,
214}
215
216impl VM {
217    pub fn new(
218        ExecutionContext {
219            heaviest_tipset,
220            state_tree_root,
221            epoch,
222            rand,
223            base_fee,
224            circ_supply,
225            chain_config,
226            chain_index,
227            timestamp,
228        }: ExecutionContext,
229        multi_engine: &MultiEngine,
230        enable_tracing: VMTrace,
231    ) -> anyhow::Result<Self> {
232        let network_version = chain_config.network_version(epoch);
233        if network_version >= NetworkVersion::V21 {
234            let mut config = NetworkConfig_v4::new(network_version.into());
235            // ChainId defines the chain ID used in the Ethereum JSON-RPC endpoint.
236            config.chain_id((chain_config.eth_chain_id).into());
237            if let NetworkChain::Devnet(_) = chain_config.network {
238                config.enable_actor_debugging();
239            }
240
241            let engine = multi_engine.v4.get(&config)?;
242            let mut context = config.for_epoch(epoch, timestamp, state_tree_root);
243            context.set_base_fee(base_fee.into());
244            context.set_circulating_supply(circ_supply.into());
245            context.tracing = enable_tracing.is_traced();
246
247            let fvm = ForestMachineV4::new(
248                &context,
249                chain_index.db().shallow_clone(),
250                ForestExternsV4::new(
251                    rand,
252                    heaviest_tipset,
253                    epoch,
254                    state_tree_root,
255                    chain_index,
256                    chain_config,
257                ),
258            )?;
259            let exec = DefaultExecutor_v4::new(engine, fvm)?;
260            Ok(VM::VM4(exec))
261        } else if network_version >= NetworkVersion::V18 {
262            let mut config = NetworkConfig_v3::new(network_version.into());
263            // ChainId defines the chain ID used in the Ethereum JSON-RPC endpoint.
264            config.chain_id((chain_config.eth_chain_id).into());
265            if let NetworkChain::Devnet(_) = chain_config.network {
266                config.enable_actor_debugging();
267            }
268
269            let engine = multi_engine.v3.get(&config)?;
270            let mut context = config.for_epoch(epoch, timestamp, state_tree_root);
271            context.set_base_fee(base_fee.into());
272            context.set_circulating_supply(circ_supply.into());
273            context.tracing = enable_tracing.is_traced();
274
275            let fvm = ForestMachineV3::new(
276                &context,
277                chain_index.db().shallow_clone(),
278                ForestExternsV3::new(
279                    rand,
280                    heaviest_tipset,
281                    epoch,
282                    state_tree_root,
283                    chain_index,
284                    chain_config,
285                ),
286            )?;
287            let exec = DefaultExecutor_v3::new(engine, fvm)?;
288            Ok(VM::VM3(exec))
289        } else {
290            let config = NetworkConfig_v2::new(network_version.into());
291            let engine = multi_engine.v2.get(&config)?;
292            let mut context = config.for_epoch(epoch, state_tree_root);
293            context.set_base_fee(base_fee.into());
294            context.set_circulating_supply(circ_supply.into());
295            context.tracing = enable_tracing.is_traced();
296
297            let fvm = ForestMachineV2::new(
298                &engine,
299                &context,
300                chain_index.db().shallow_clone(),
301                ForestExternsV2::new(
302                    rand,
303                    heaviest_tipset,
304                    epoch,
305                    state_tree_root,
306                    chain_index,
307                    chain_config,
308                ),
309            )?;
310            let exec = DefaultExecutor_v2::new(fvm);
311            Ok(VM::VM2(exec))
312        }
313    }
314
315    /// Flush stores in VM and return state root.
316    pub fn flush(&mut self) -> anyhow::Result<Cid> {
317        Ok(delegate_vm!(self.flush()?))
318    }
319
320    /// Get actor state from an address. Will be resolved to ID address.
321    pub fn get_actor(&self, addr: &Address) -> anyhow::Result<Option<ActorState>> {
322        match self {
323            VM::VM2(fvm_executor) => Ok(fvm_executor
324                .state_tree()
325                .get_actor(&addr.try_to_v2()?)?
326                .map(ActorState::from)),
327            VM::VM3(fvm_executor) => {
328                if let Some(id) = fvm_executor.state_tree().lookup_id(&addr.into())? {
329                    Ok(fvm_executor
330                        .state_tree()
331                        .get_actor(id)?
332                        .map(ActorState::from))
333                } else {
334                    Ok(None)
335                }
336            }
337            VM::VM4(fvm_executor) => {
338                if let Some(id) = fvm_executor.state_tree().lookup_id(&addr.into())? {
339                    Ok(fvm_executor
340                        .state_tree()
341                        .get_actor(id)?
342                        .map(ActorState::from))
343                } else {
344                    Ok(None)
345                }
346            }
347        }
348    }
349
350    pub fn run_cron(
351        &mut self,
352        epoch: ChainEpoch,
353        callback: Option<impl FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()>>,
354    ) -> anyhow::Result<()> {
355        let cron_msg: Message = Message_v3 {
356            from: Address::SYSTEM_ACTOR.into(),
357            to: Address::CRON_ACTOR.into(),
358            // Epoch as sequence is intentional
359            sequence: epoch as u64,
360            // Arbitrarily large gas limit for cron (matching Lotus value)
361            gas_limit: IMPLICIT_MESSAGE_GAS_LIMIT as u64,
362            method_num: cron::Method::EpochTick as u64,
363            params: Default::default(),
364            value: Default::default(),
365            version: Default::default(),
366            gas_fee_cap: Default::default(),
367            gas_premium: Default::default(),
368        }
369        .into();
370
371        let (ret, duration) = self.apply_implicit_message(&cron_msg)?;
372        if let Some(err) = ret.failure_info() {
373            anyhow::bail!("failed to apply block cron message: {err}");
374        }
375
376        if let Some(mut callback) = callback {
377            callback(MessageCallbackCtx {
378                cid: cron_msg.cid(),
379                message: &cron_msg.into(),
380                apply_ret: &ret,
381                at: CalledAt::Cron,
382                duration,
383                state: VMStateView(self),
384            })?;
385        }
386        Ok(())
387    }
388
389    /// Apply block messages from a Tipset.
390    /// Returns the receipts from the transactions.
391    pub fn apply_block_messages(
392        &mut self,
393        messages: &[BlockMessages],
394        epoch: ChainEpoch,
395        mut callback: Option<impl FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()>>,
396    ) -> ApplyBlockResult {
397        let mut receipts = Vec::new();
398        let mut events = Vec::new();
399        let mut events_roots: Vec<Option<Cid>> = Vec::new();
400        let mut processed = HashSet::default();
401
402        for block in messages.iter() {
403            let mut penalty = TokenAmount::zero();
404            let mut gas_reward = TokenAmount::zero();
405
406            let mut process_msg = |message: &ChainMessage| -> anyhow::Result<()> {
407                let cid = message.cid();
408                // Ensure no duplicate processing of a message
409                if processed.contains(&cid) {
410                    return Ok(());
411                }
412                let (ret, duration) = self.apply_message(message)?;
413
414                if let Some(cb) = &mut callback {
415                    cb(MessageCallbackCtx {
416                        cid,
417                        message,
418                        apply_ret: &ret,
419                        at: CalledAt::Applied,
420                        duration,
421                        state: VMStateView(self),
422                    })?;
423                }
424
425                // Update totals
426                gas_reward += ret.miner_tip();
427                penalty += ret.penalty();
428                let (receipt, msg_events) = ret.into_receipt_and_events();
429                events_roots.push(receipt.events_root());
430                receipts.push(receipt);
431                events.push(msg_events);
432
433                // Add processed Cid to set of processed messages
434                processed.insert(cid);
435                Ok(())
436            };
437
438            for msg in block.messages.iter() {
439                process_msg(msg)?;
440            }
441
442            // Generate reward transaction for the miner of the block
443            if let Some(rew_msg) =
444                self.reward_message(epoch, block.miner, block.win_count, penalty, gas_reward)?
445            {
446                let (ret, duration) = self.apply_implicit_message(&rew_msg)?;
447                if let Some(err) = ret.failure_info() {
448                    anyhow::bail!(
449                        "failed to apply reward message for miner {}: {}",
450                        block.miner,
451                        err
452                    );
453                }
454                // This is more of a sanity check, this should not be able to be hit.
455                if !ret.exit_code().is_success() {
456                    anyhow::bail!(
457                        "reward application message failed (exit: {:?})",
458                        ret.exit_code()
459                    );
460                }
461
462                if let Some(callback) = &mut callback {
463                    callback(MessageCallbackCtx {
464                        cid: rew_msg.cid(),
465                        message: &rew_msg.into(),
466                        apply_ret: &ret,
467                        at: CalledAt::Reward,
468                        duration,
469                        state: VMStateView(self),
470                    })?
471                }
472            }
473        }
474
475        if let Err(e) = self.run_cron(epoch, callback.as_mut()) {
476            tracing::error!("End of epoch cron failed to run: {e:#}");
477        }
478
479        Ok((receipts, events, events_roots))
480    }
481
482    /// Applies single message through VM and returns result from execution.
483    pub fn apply_implicit_message(&mut self, msg: &Message) -> ApplyResult {
484        let start = Instant::now();
485
486        // Every FVM version charges a zero `GasCharge` for `ApplyKind::Implicit` and never reads
487        // `raw_length`, so don't pay to serialize the message just to measure it.
488        let raw_length = 0;
489
490        let ret = match self {
491            VM::VM2(fvm_executor) => fvm_executor
492                .execute_message(
493                    msg.try_into()?,
494                    fvm2::executor::ApplyKind::Implicit,
495                    raw_length,
496                )?
497                .into(),
498            VM::VM3(fvm_executor) => fvm_executor
499                .execute_message(msg.into(), fvm3::executor::ApplyKind::Implicit, raw_length)?
500                .into(),
501            VM::VM4(fvm_executor) => fvm_executor
502                .execute_message(msg.into(), fvm4::executor::ApplyKind::Implicit, raw_length)?
503                .into(),
504        };
505        Ok((ret, start.elapsed()))
506    }
507
508    /// Applies the state transition for a single message.
509    /// Returns `ApplyRet` structure which contains the message receipt and some
510    /// meta data.
511    pub fn apply_message(&mut self, msg: &ChainMessage) -> ApplyResult {
512        let start = Instant::now();
513
514        // Basic validity check
515        msg.message().check()?;
516
517        let unsigned = msg.message().clone();
518        let raw_length = msg.encoded_len();
519        let ret: ApplyRet = match self {
520            VM::VM2(fvm_executor) => {
521                let ret = fvm_executor.execute_message(
522                    unsigned.try_into()?,
523                    fvm2::executor::ApplyKind::Explicit,
524                    raw_length,
525                )?;
526
527                if fvm_executor.externs().bail() {
528                    bail!("encountered a database lookup error");
529                }
530
531                ret.into()
532            }
533            VM::VM3(fvm_executor) => {
534                let ret = fvm_executor.execute_message(
535                    unsigned.into(),
536                    fvm3::executor::ApplyKind::Explicit,
537                    raw_length,
538                )?;
539
540                if fvm_executor.externs().bail() {
541                    bail!("encountered a database lookup error");
542                }
543
544                ret.into()
545            }
546            VM::VM4(fvm_executor) => {
547                let ret = fvm_executor.execute_message(
548                    unsigned.into(),
549                    fvm4::executor::ApplyKind::Explicit,
550                    raw_length,
551                )?;
552
553                if fvm_executor.externs().bail() {
554                    bail!("encountered a database lookup error");
555                }
556
557                ret.into()
558            }
559        };
560        let duration = start.elapsed();
561
562        let exit_code = ret.exit_code();
563
564        if !exit_code.is_success() {
565            tracing::debug!(?exit_code, "VM message execution failure.")
566        }
567
568        Ok((ret, duration))
569    }
570
571    pub(crate) fn reward_message(
572        &self,
573        epoch: ChainEpoch,
574        miner: Address,
575        win_count: i64,
576        penalty: TokenAmount,
577        gas_reward: TokenAmount,
578    ) -> anyhow::Result<Option<Message>> {
579        let params = RawBytes::serialize(AwardBlockRewardParams {
580            miner: miner.into(),
581            penalty: penalty.into(),
582            gas_reward: gas_reward.into(),
583            win_count,
584        })?;
585        let rew_msg = Message_v3 {
586            from: Address::SYSTEM_ACTOR.into(),
587            to: Address::REWARD_ACTOR.into(),
588            method_num: reward::Method::AwardBlockReward as u64,
589            params,
590            // Epoch as sequence is intentional
591            sequence: epoch as u64,
592            gas_limit: IMPLICIT_MESSAGE_GAS_LIMIT as u64,
593            value: Default::default(),
594            version: Default::default(),
595            gas_fee_cap: Default::default(),
596            gas_premium: Default::default(),
597        };
598        Ok(Some(rew_msg.into()))
599    }
600}
601
602#[derive(Debug, Clone)]
603pub struct MessageCallbackCtx<'a> {
604    pub cid: Cid,
605    pub message: &'a ChainMessage,
606    pub apply_ret: &'a ApplyRet,
607    pub at: CalledAt,
608    pub duration: Duration,
609    /// State of the VM after `message` was applied.
610    pub state: VMStateView<'a>,
611}
612
613/// Read-only view of a [`VM`]'s state, including the changes it has not flushed.
614#[derive(Clone, Copy, derive_more::Debug)]
615pub struct VMStateView<'a>(#[debug(skip)] &'a VM);
616
617impl VMStateView<'_> {
618    /// Returns the state of the actor at `addr`, or `None` when there is no such actor.
619    pub fn get_actor(&self, addr: &Address) -> anyhow::Result<Option<ActorState>> {
620        self.0.get_actor(addr)
621    }
622}
623
624impl Blockstore for VMStateView<'_> {
625    fn get(&self, k: &Cid) -> anyhow::Result<Option<Vec<u8>>> {
626        delegate_vm!(self.0 => |executor| executor.state_tree().store().get(k))
627    }
628
629    /// Not supported, the view is read-only.
630    fn put_keyed(&self, _: &Cid, _: &[u8]) -> anyhow::Result<()> {
631        bail!("VMStateView is read-only");
632    }
633}
634
635#[derive(Debug, Clone, Copy)]
636pub enum CalledAt {
637    Applied,
638    Reward,
639    Cron,
640}
641
642/// Tracing a Filecoin VM has a performance penalty.
643/// This controls whether a VM should be traced or not when it is created.
644#[derive(Default, Clone, Copy)]
645pub enum VMTrace {
646    /// Collect trace for the given operation
647    Traced,
648    /// Do not collect trace
649    #[default]
650    NotTraced,
651}
652
653impl VMTrace {
654    /// Should tracing be collected?
655    pub fn is_traced(&self) -> bool {
656        matches!(self, VMTrace::Traced)
657    }
658}
659
660#[cfg(test)]
661mod for_tipset_tests {
662    use super::*;
663    use crate::blocks::{Block, CachingBlockHeader, FullTipset, RawBlockHeader, Tipset};
664    use crate::chain_sync::TipsetValidator;
665    use crate::db::{DbImpl, MemoryDB};
666    use crate::message::SignedMessage;
667    use crate::shim::crypto::Signature;
668    use crate::shim::message::Message_v3;
669    use crate::test_utils::{dummy_ticket, resolving_state_tree};
670    use rstest::rstest;
671
672    fn secp(from: Address, nonce: u64) -> SignedMessage {
673        let m: Message = Message_v3 {
674            to: Address::new_id(99).into(),
675            from: from.into(),
676            sequence: nonce,
677            ..Default::default()
678        }
679        .into();
680        SignedMessage::new_unchecked(m, Signature::new_secp256k1(vec![0]))
681    }
682
683    fn selected_message_count(
684        db: &DbImpl,
685        secp_messages: Vec<SignedMessage>,
686        state_root: Cid,
687        epoch: ChainEpoch,
688    ) -> usize {
689        let config = ChainConfig::default();
690        let secp_cids = secp_messages.iter().map(SignedMessage::signed_cid);
691        let msg_root =
692            TipsetValidator::compute_msg_root(&db, std::iter::empty(), secp_cids).unwrap();
693        let header = CachingBlockHeader::new(RawBlockHeader {
694            miner_address: Address::new_id(1000),
695            ticket: dummy_ticket(0),
696            epoch,
697            state_root,
698            messages: msg_root,
699            ..Default::default()
700        });
701        let block = Block {
702            header,
703            bls_messages: vec![],
704            secp_messages: secp_messages.into_iter().map(Arc::new).collect(),
705        };
706        let fts = FullTipset::new([block]).unwrap();
707        fts.persist(&db).unwrap();
708        let tipset = Tipset::from(fts);
709
710        BlockMessages::for_tipset(db, &tipset, &config)
711            .unwrap()
712            .iter()
713            .map(|bm| bm.messages.len())
714            .sum()
715    }
716
717    #[rstest]
718    #[case::from_hyperdrive_dedups(0, 1)]
719    #[case::before_hyperdrive_keeps_both(-1, 2)]
720    fn one_account_under_two_address_forms(
721        #[case] epoch_offset: ChainEpoch,
722        #[case] expected: usize,
723    ) {
724        let db: DbImpl = Arc::new(MemoryDB::default()).into();
725        let f1 = Address::new_secp256k1(&[0x04; 65]).unwrap();
726        let (mut tree, f0) = resolving_state_tree(&db, f1);
727        let state_root = tree.flush().unwrap();
728
729        let count = selected_message_count(
730            &db,
731            vec![secp(f1, 7), secp(f0, 7)],
732            state_root,
733            ChainConfig::default().epoch(Height::Hyperdrive) + epoch_offset,
734        );
735        assert_eq!(count, expected);
736    }
737
738    #[test]
739    fn re_key_preserves_nonces() {
740        let db: DbImpl = Arc::new(MemoryDB::default()).into();
741        let f1 = Address::new_secp256k1(&[0x04; 65]).unwrap();
742        let (mut tree, f0) = resolving_state_tree(&db, f1);
743        let state_root = tree.flush().unwrap();
744
745        // Re-keying to the ID must carry the nonce advanced under `f1`, leaving only `f0` as the
746        // duplicate.
747        let count = selected_message_count(
748            &db,
749            vec![secp(f1, 7), secp(f1, 8), secp(f0, 8)],
750            state_root,
751            ChainConfig::default().epoch(Height::Hyperdrive),
752        );
753        assert_eq!(count, 2);
754    }
755
756    #[test]
757    fn robust_only_senders_need_no_state() {
758        let db: DbImpl = Arc::new(MemoryDB::default()).into();
759        let f1 = Address::new_secp256k1(&[0x04; 65]).unwrap();
760
761        // The state root is absent from the store; lazy keying must not load it while every sender
762        // is in robust form, as happens for a pruned tipset.
763        let count = selected_message_count(
764            &db,
765            vec![secp(f1, 7), secp(f1, 8)],
766            Cid::default(),
767            ChainConfig::default().epoch(Height::Hyperdrive),
768        );
769        assert_eq!(count, 2);
770    }
771}