forest-filecoin 0.36.1

Rust Filecoin implementation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
// Copyright 2019-2026 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use super::circulating_supply::GenesisInfo;
use super::*;
use crate::interpreter::{BlockMessages, ExecutionContext, VM, VMTrace};
use crate::prelude::*;
use crate::shim::message::Message;
use crate::state_migration::run_state_migrations;
use anyhow::{bail, ensure};
use fil_actors_shared::fvm_ipld_amt::{Amt, Amtv0};
use tracing::{error, info, instrument, warn};

enum StateRecomputePolicy {
    Allowed,
    Disallowed,
}

impl StateManager {
    /// Load the state of a tipset, including state root, message receipts
    pub async fn load_tipset_state(&self, ts: &Tipset) -> anyhow::Result<TipsetState> {
        if let Some(state) = self.cache.get_map(ts.key(), |et| et.into()) {
            Ok(state)
        } else {
            match self.chain_store().load_child_tipset(ts).await? {
                Some(receipt_ts) => Ok(TipsetState {
                    state_root: *receipt_ts.parent_state(),
                    receipt_root: *receipt_ts.parent_message_receipts(),
                }),
                None => Ok(self.load_executed_tipset(ts).await?.into()),
            }
        }
    }

    /// Clears all cached state outputs and traces. Used after repairing corrupted
    /// computation inputs (e.g. a stale tipset lookup entry): any cached result may have
    /// been derived from the poisoned data, and the tainted ones cannot be told apart.
    pub fn clear_tipset_state_caches(&self) {
        self.cache.clear();
        self.trace_cache.clear();
    }

    /// Verifies and repairs the tipset lookup table (see `ChainStore::repair_tipset_lookup`)
    /// and clears the state caches when anything was repaired: results computed while the
    /// entries were wrong may be tainted.
    pub fn repair_tipset_lookup(&self) -> anyhow::Result<usize> {
        let n_repaired = self.cs.repair_tipset_lookup()?;
        if n_repaired > 0 {
            self.clear_tipset_state_caches();
        }
        Ok(n_repaired)
    }

    /// State recomputation policy for RPC methods: recomputation is disabled unless explicitly
    /// enabled via the environment.
    fn rpc_state_recompute_policy() -> StateRecomputePolicy {
        crate::def_is_env_truthy!(
            enable_state_computation,
            "FOREST_ETH_RPC_COMPUTE_STATE_ON_INDEX_MISS"
        );

        if enable_state_computation() {
            StateRecomputePolicy::Allowed
        } else {
            StateRecomputePolicy::Disallowed
        }
    }

    /// Load an executed tipset for RPC methods, with state computation unless explicitly enabled.
    pub async fn load_executed_tipset_for_rpc(
        &self,
        ts: &Tipset,
    ) -> anyhow::Result<ExecutedTipset> {
        self.load_executed_tipset_with_cache(ts, Self::rpc_state_recompute_policy())
            .await
    }

    /// Returns `ts`'s messages paired with their execution receipts, without loading events.
    /// `receipt_ts` is `ts`'s child (whose `parent_message_receipts` is `ts`'s receipt root) when the
    /// caller already knows it, avoiding a `load_child_tipset` lookup; `None` resolves it.
    pub async fn tipset_message_receipts(
        &self,
        ts: &Tipset,
        receipt_ts: Option<&Tipset>,
    ) -> anyhow::Result<TipsetMessageReceipts> {
        if let Some(cached) = self.cache.get(ts.key()) {
            return Ok(TipsetMessageReceipts::Executed(cached.executed_messages));
        }

        let receipt_ts = match receipt_ts {
            Some(child) => Some(child.shallow_clone()),
            None => self.chain_store().load_child_tipset(ts).await?,
        };
        if let Some(child) = &receipt_ts {
            anyhow::ensure!(
                ts.key() == child.parents(),
                "message tipset should be the parent of message receipt tipset"
            );
            if let Ok(receipts) =
                Receipt::get_receipts(self.cs.db(), *child.parent_message_receipts())
            {
                let messages = self.chain_store().messages_for_tipset(ts)?;
                anyhow::ensure!(
                    messages.len() == receipts.len(),
                    "mismatching message and receipt counts ({} messages, {} receipts)",
                    messages.len(),
                    receipts.len()
                );
                return Ok(TipsetMessageReceipts::Stored(messages, receipts));
            }
        }
        Ok(TipsetMessageReceipts::Executed(
            self.load_executed_tipset_for_rpc(ts)
                .await?
                .executed_messages,
        ))
    }

    /// Load an executed tipset using an explicitly provided receipt (child) tipset instead of
    /// resolving the child on the current heaviest chain. This is required when serving events
    /// for tipsets that are no longer canonical.
    pub async fn load_executed_tipset_with_receipt(
        &self,
        msg_ts: &Tipset,
        receipt_ts: &Tipset,
    ) -> anyhow::Result<ExecutedTipset> {
        self.cache
            .get_or_insert_async(msg_ts.key(), async move {
                self.load_executed_tipset_inner(
                    msg_ts,
                    Some(receipt_ts),
                    Self::rpc_state_recompute_policy(),
                )
                .await
            })
            .await
    }

    /// Load an executed tipset, including state root, message receipts and events with caching.
    pub async fn load_executed_tipset(&self, ts: &Tipset) -> anyhow::Result<ExecutedTipset> {
        self.load_executed_tipset_with_cache(ts, StateRecomputePolicy::Allowed)
            .await
    }

    /// Load an executed tipset without reading from or populating the cache. Errors on a missing
    /// state output unless `allow_state_compute` is true.
    pub async fn load_executed_tipset_uncached(
        &self,
        ts: &Tipset,
        allow_state_compute: bool,
    ) -> anyhow::Result<ExecutedTipset> {
        let policy = if allow_state_compute {
            StateRecomputePolicy::Allowed
        } else {
            StateRecomputePolicy::Disallowed
        };
        let receipt_ts = self.chain_store().load_child_tipset(ts).await?;
        self.load_executed_tipset_inner(ts, receipt_ts.as_ref(), policy)
            .await
    }

    async fn load_executed_tipset_with_cache(
        &self,
        ts: &Tipset,
        policy: StateRecomputePolicy,
    ) -> anyhow::Result<ExecutedTipset> {
        // validate the existence of state trees for post-chain-head-epoch tipsets in case chain head is reset(e.g. manually or via GC).
        if ts.epoch() >= self.heaviest_tipset().epoch()
            && let Some(cached) = self.cache.get(ts.key())
        {
            if StateTree::new_from_root(self.db(), &cached.state_root).is_ok() {
                return Ok(cached);
            } else {
                self.cache.remove(ts.key());
            }
        }
        self.cache
            .get_or_insert_async(ts.key(), async move {
                let receipt_ts = self.chain_store().load_child_tipset(ts).await?;
                self.load_executed_tipset_inner(ts, receipt_ts.as_ref(), policy)
                    .await
            })
            .await
    }

    async fn load_executed_tipset_inner(
        &self,
        msg_ts: &Tipset,
        // when `msg_ts` is the current head, `receipt_ts` is `None`
        receipt_ts: Option<&Tipset>,
        policy: StateRecomputePolicy,
    ) -> anyhow::Result<ExecutedTipset> {
        let state_compute_disallow_error = || {
            format!(
                "failed to load tipset state output and recomputation is disallowed, epoch={}, key={}",
                msg_ts.epoch(),
                msg_ts.key()
            )
        };

        if let Some(receipt_ts) = receipt_ts {
            anyhow::ensure!(
                msg_ts.key() == receipt_ts.parents(),
                "message tipset should be the parent of message receipt tipset"
            );
        }
        let allow_state_compute = matches!(policy, StateRecomputePolicy::Allowed);
        let mut recomputed = false;
        let (state_root, receipt_root, receipts) = match receipt_ts.and_then(|ts| {
            let receipt_root = *ts.parent_message_receipts();
            Receipt::get_receipts(self.cs.db(), receipt_root)
                .ok()
                .map(|r| (*ts.parent_state(), receipt_root, r))
        }) {
            Some((state_root, receipt_root, receipts)) => (state_root, receipt_root, receipts),
            None => {
                if !allow_state_compute {
                    anyhow::bail!(state_compute_disallow_error());
                }
                let state_output = self
                    .compute_tipset_state(msg_ts.shallow_clone(), NO_CALLBACK, VMTrace::NotTraced)
                    .await?;
                recomputed = true;
                (
                    state_output.state_root,
                    state_output.receipt_root,
                    Receipt::get_receipts(self.cs.db(), state_output.receipt_root)?,
                )
            }
        };

        let messages = self.chain_store().messages_for_tipset(msg_ts)?;
        anyhow::ensure!(
            messages.len() == receipts.len(),
            "mismatching message and receipt counts ({} messages, {} receipts)",
            messages.len(),
            receipts.len()
        );
        let mut executed_messages = Vec::with_capacity(messages.len());
        for (message, receipt) in messages.iter().cloned().zip(receipts) {
            let events = if let Some(events_root) = receipt.events_root() {
                Some(match StampedEvent::get_events(self.cs.db(), &events_root) {
                    Ok(events) => events,
                    Err(e) if recomputed => return Err(e),
                    Err(_) => {
                        if !allow_state_compute {
                            anyhow::bail!(state_compute_disallow_error());
                        }
                        self.compute_tipset_state(
                            msg_ts.shallow_clone(),
                            NO_CALLBACK,
                            VMTrace::NotTraced,
                        )
                        .await?;
                        recomputed = true;
                        StampedEvent::get_events(self.cs.db(), &events_root)?
                    }
                })
            } else {
                None
            };
            executed_messages.push(ExecutedMessage {
                message,
                receipt,
                events,
            });
        }

        // Store the block logs bloom whenever this tipset was executed here.
        if recomputed
            && let Err(e) = crate::rpc::eth::store_block_logs_bloom(
                self,
                msg_ts,
                &state_root,
                &executed_messages,
            )
        {
            warn!(
                "failed to store block logs bloom for tipset {}: {e:#}",
                msg_ts.key()
            );
        }

        Ok(ExecutedTipset {
            state_root,
            receipt_root,
            executed_messages: Arc::new(executed_messages),
        })
    }

    /// Conceptually, a [`Tipset`] consists of _blocks_ which share an _epoch_.
    /// Each _block_ contains _messages_, which are executed by the _Filecoin Virtual Machine_.
    ///
    /// VM message execution essentially looks like this:
    /// ```text
    /// state[N-900..N] * message = state[N+1]
    /// ```
    ///
    /// The `state`s above are stored in the `IPLD Blockstore`, and can be referred to by
    /// a [`Cid`] - the _state root_.
    /// The previous 900 states (configurable, see
    /// <https://docs.filecoin.io/reference/general/glossary/#finality>) can be
    /// queried when executing a message, so a store needs at least that many.
    /// (a snapshot typically contains 2000, for example).
    ///
    /// Each message costs FIL to execute - this is _gas_.
    /// After execution, the message has a _receipt_, showing how much gas was spent.
    /// This is similarly a [`Cid`] into the block store.
    ///
    /// For details, see the documentation for [`apply_block_messages`].
    ///
    pub async fn compute_tipset_state(
        &self,
        tipset: Tipset,
        callback: Option<impl FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()> + Send + 'static>,
        enable_tracing: VMTrace,
    ) -> Result<ExecutedTipset, Error> {
        let this = self.shallow_clone();
        tokio::task::spawn_blocking(move || {
            this.compute_tipset_state_blocking(tipset, callback, enable_tracing)
        })
        .await?
    }

    /// Blocking version of `compute_tipset_state`
    pub fn compute_tipset_state_blocking(
        &self,
        tipset: Tipset,
        callback: Option<impl FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()>>,
        enable_tracing: VMTrace,
    ) -> Result<ExecutedTipset, Error> {
        let epoch = tipset.epoch();
        let has_callback = callback.is_some();
        info!(
            "Evaluating tipset: EPOCH={epoch}, blocks={}, tsk={}",
            tipset.len(),
            tipset.key(),
        );
        Ok(apply_block_messages_blocking(
            self.chain_index().shallow_clone(),
            self.chain_config().shallow_clone(),
            self.beacon_schedule().shallow_clone(),
            &self.engine,
            tipset,
            callback,
            enable_tracing,
        )
        .map_err(|e| {
            if has_callback {
                e
            } else {
                e.context(format!("Failed to compute tipset state@{epoch}"))
            }
        })?)
    }

    #[instrument(skip_all)]
    pub async fn compute_state(
        &self,
        height: ChainEpoch,
        messages: Vec<Message>,
        tipset: Tipset,
        callback: Option<impl FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()> + Send + 'static>,
        enable_tracing: VMTrace,
    ) -> Result<ExecutedTipset, Error> {
        let this = self.shallow_clone();
        tokio::task::spawn_blocking(move || {
            this.compute_state_blocking(height, messages, tipset, callback, enable_tracing)
        })
        .await?
    }

    /// Blocking version of `compute_state`
    #[tracing::instrument(skip_all)]
    pub fn compute_state_blocking(
        &self,
        height: ChainEpoch,
        messages: Vec<Message>,
        tipset: Tipset,
        callback: Option<impl FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()>>,
        enable_tracing: VMTrace,
    ) -> Result<ExecutedTipset, Error> {
        Ok(compute_state_blocking(
            height,
            messages,
            tipset,
            self.chain_index().shallow_clone(),
            self.chain_config().shallow_clone(),
            self.beacon_schedule().shallow_clone(),
            &self.engine,
            callback,
            enable_tracing,
        )?)
    }
}

pub fn validate_tipsets_blocking<T>(
    chain_index: &ChainIndex,
    chain_config: &Arc<ChainConfig>,
    beacon: &Arc<BeaconSchedule>,
    engine: &MultiEngine,
    tipsets: T,
) -> anyhow::Result<()>
where
    T: Iterator<Item = Tipset> + Send,
{
    // Validate one tipset at a time. Parallelizing the outer loop across tipsets
    // might wedge the global rayon pool.
    // Sequential outer iteration leaves the entire rayon pool free for that
    // already-rich inner parallelism.
    for (child, parent) in tipsets.tuple_windows() {
        info!(height = parent.epoch(), "compute parent state");
        let ExecutedTipset {
            state_root: actual_state,
            receipt_root: actual_receipt,
            ..
        } = apply_block_messages_blocking(
            chain_index.shallow_clone(),
            chain_config.shallow_clone(),
            beacon.shallow_clone(),
            engine,
            parent,
            NO_CALLBACK,
            VMTrace::NotTraced,
        )
        .context("couldn't compute tipset state")?;
        let expected_receipt = child.min_ticket_block().message_receipts;
        let expected_state = child.parent_state();
        if (expected_state, expected_receipt) != (&actual_state, actual_receipt) {
            error!(
                height = child.epoch(),
                ?expected_state,
                ?expected_receipt,
                ?actual_state,
                ?actual_receipt,
                "state mismatch"
            );
            bail!("state mismatch");
        }
    }
    Ok(())
}

/// Shared context for creating VMs and preparing tipset state.
///
/// Encapsulates randomness source, genesis info, VM construction,
/// null-epoch cron handling, and state migrations.
pub(in crate::state_manager) struct TipsetExecutor<'a> {
    tipset: Tipset,
    rand: ChainRand,
    chain_config: Arc<ChainConfig>,
    chain_index: ChainIndex,
    genesis_info: GenesisInfo,
    engine: &'a MultiEngine,
}

impl<'a> TipsetExecutor<'a> {
    pub(in crate::state_manager) fn new(
        chain_index: ChainIndex,
        chain_config: Arc<ChainConfig>,
        beacon: Arc<BeaconSchedule>,
        engine: &'a MultiEngine,
        tipset: Tipset,
    ) -> Self {
        let rand = ChainRand::new(
            chain_config.shallow_clone(),
            tipset.shallow_clone(),
            chain_index.shallow_clone(),
            beacon,
        );
        let genesis_info = GenesisInfo::from_chain_config(chain_config.shallow_clone());
        Self {
            tipset,
            rand,
            chain_config,
            chain_index,
            genesis_info,
            engine,
        }
    }

    pub(in crate::state_manager) fn create_vm(
        &self,
        state_root: Cid,
        epoch: ChainEpoch,
        timestamp: u64,
        trace: VMTrace,
    ) -> anyhow::Result<VM> {
        let circ_supply = self.genesis_info.get_vm_circulating_supply(
            epoch,
            self.chain_index.db(),
            &state_root,
        )?;
        VM::new(
            ExecutionContext {
                heaviest_tipset: self.tipset.shallow_clone(),
                state_tree_root: state_root,
                epoch,
                rand: Box::new(self.rand.shallow_clone()),
                base_fee: self.tipset.min_ticket_block().parent_base_fee.clone(),
                circ_supply,
                chain_config: self.chain_config.shallow_clone(),
                chain_index: self.chain_index.shallow_clone(),
                timestamp,
            },
            self.engine,
            trace,
        )
    }

    /// Produces the state root ready for message execution by running
    /// null-epoch `crons` and any pending state migrations.
    pub(in crate::state_manager) fn prepare_parent_state_blocking<F>(
        &self,
        genesis_timestamp: u64,
        null_epoch_trace: VMTrace,
        cron_callback: &mut Option<F>,
    ) -> anyhow::Result<(Cid, ChainEpoch, Vec<BlockMessages>)>
    where
        F: FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()>,
    {
        use crate::shim::clock::EPOCH_DURATION_SECONDS;

        let mut parent_state = *self.tipset.parent_state();
        let parent_epoch = self
            .chain_index
            .load_required_tipset(self.tipset.parents())?
            .epoch();
        let epoch = self.tipset.epoch();

        for epoch_i in parent_epoch..epoch {
            if epoch_i > parent_epoch {
                let timestamp = genesis_timestamp + ((EPOCH_DURATION_SECONDS * epoch_i) as u64);
                parent_state = stacker::grow(64 << 20, || -> anyhow::Result<Cid> {
                    let mut vm =
                        self.create_vm(parent_state, epoch_i, timestamp, null_epoch_trace)?;
                    if let Err(e) = vm.run_cron(epoch_i, cron_callback.as_mut()) {
                        error!("Beginning of epoch cron failed to run: {e:#}");
                        return Err(e);
                    }
                    vm.flush()
                })?;
            }
            if let Some(new_state) = run_state_migrations(
                epoch_i,
                &self.chain_config,
                self.chain_index.db(),
                &parent_state,
            )? {
                parent_state = new_state;
            }
        }

        let block_messages = BlockMessages::for_tipset(self.chain_index.db(), &self.tipset)?;
        Ok((parent_state, epoch, block_messages))
    }
}

/// Messages are transactions that produce new states. The state (usually
/// referred to as the 'state-tree') is a mapping from actor addresses to actor
/// states. Each block contains the hash of the state-tree that should be used
/// as the starting state when executing the block messages.
///
/// # Execution environment
///
/// Transaction execution has the following inputs:
/// - a current state-tree (stored as IPLD in a key-value database). This
///   reference is in [`Tipset::parent_state`].
/// - up to 900 past state-trees. See
///   <https://docs.filecoin.io/reference/general/glossary/#finality>.
/// - up to 900 past tipset IDs.
/// - a deterministic source of randomness.
/// - the circulating supply of FIL (see
///   <https://filecoin.io/blog/filecoin-circulating-supply/>). The circulating
///   supply is determined by the epoch and the states of a few key actors.
/// - the base fee (see <https://spec.filecoin.io/systems/filecoin_vm/gas_fee/>).
///   This value is defined by `tipset.parent_base_fee`.
/// - the genesis timestamp (UNIX epoch time when the first block was
///   mined/created).
/// - a chain configuration (maps epoch to network version, has chain specific
///   settings).
///
/// The result of running a set of block messages is an index to the final
/// state-tree and an index to an array of message receipts (listing gas used,
/// return codes, etc).
///
/// # Cron and null tipsets
///
/// Once per epoch, after all messages have run, a special 'cron' transaction
/// must be executed. The tasks of the 'cron' transaction include running batch
/// jobs and keeping the state up-to-date with the current epoch.
///
/// It can happen that no blocks are mined in an epoch. The tipset for such an
/// epoch is called a null tipset. A null tipset has no identity and cannot be
/// directly executed. This is a problem for 'cron' which must run for every
/// epoch, even if there are no messages. The fix is to run 'cron' if there are
/// any null tipsets between the current epoch and the parent epoch.
///
/// Imagine the blockchain looks like this with a null tipset at epoch 9:
///
/// ```text
/// ┌────────┐ ┌────┐ ┌───────┐  ┌───────┐
/// │Epoch 10│ │Null│ │Epoch 8├──►Epoch 7├─►
/// └───┬────┘ └────┘ └───▲───┘  └───────┘
///     └─────────────────┘
/// ```
///
/// The parent of tipset-epoch-10 is tipset-epoch-8. Before executing the
/// messages in epoch 10, we have to run cron for epoch 9. However, running
/// 'cron' requires the timestamp of the youngest block in the tipset (which
/// doesn't exist because there are no blocks in the tipset). Lotus dictates that
/// the timestamp of a null tipset is `30s * epoch` after the genesis timestamp.
/// So, in the above example, if the genesis block was mined at time `X`, the
/// null tipset for epoch 9 will have timestamp `X + 30 * 9`.
///
/// # Migrations
///
/// Migrations happen between network upgrades and modify the state tree. If a
/// migration is scheduled for epoch 10, it will be run _after_ the messages for
/// epoch 10. The tipset for epoch 11 will link the state-tree produced by the
/// migration.
///
/// Example timeline with a migration at epoch 10:
///   1. Tipset-epoch-10 executes, producing state-tree A.
///   2. Migration consumes state-tree A and produces state-tree B.
///   3. Tipset-epoch-11 executes, consuming state-tree B (rather than A).
///
/// Note: The migration actually happens when tipset-epoch-11 executes. This is
///       because tipset-epoch-10 may be null and therefore not executed at all.
///
/// # Caching
///
/// Scanning the blockchain to find past tipsets and state-trees may be slow.
/// The `ChainStore` caches recent tipsets to make these scans faster.
#[allow(clippy::too_many_arguments)]
pub fn apply_block_messages_blocking(
    chain_index: ChainIndex,
    chain_config: Arc<ChainConfig>,
    beacon: Arc<BeaconSchedule>,
    engine: &MultiEngine,
    tipset: Tipset,
    mut callback: Option<impl FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()>>,
    enable_tracing: VMTrace,
) -> anyhow::Result<ExecutedTipset> {
    // This function will:
    // 1. handle the genesis block as a special case
    // 2. run 'cron' for any null-tipsets between the current tipset and our parent tipset
    // 3. run migrations
    // 4. execute block messages
    // 5. write the state-tree to the DB and return the CID

    // step 1: special case for genesis block
    let genesis_timestamp = chain_index.genesis().min_ticket_block().timestamp;
    if tipset.epoch() == 0 {
        // NB: This is here because the process that executes blocks requires that the
        // block miner reference a valid miner in the state tree. Unless we create some
        // magical genesis miner, this won't work properly, so we short circuit here
        // This avoids the question of 'who gets paid the genesis block reward'
        let message_receipts = tipset.min_ticket_block().message_receipts;
        return Ok(ExecutedTipset {
            state_root: *tipset.parent_state(),
            receipt_root: message_receipts,
            executed_messages: vec![].into(),
        });
    }

    let exec = TipsetExecutor::new(
        chain_index.shallow_clone(),
        chain_config,
        beacon,
        engine,
        tipset.shallow_clone(),
    );

    // step 2: running cron for any null-tipsets
    // step 3: run migrations
    let (parent_state, epoch, block_messages) =
        exec.prepare_parent_state_blocking(genesis_timestamp, enable_tracing, &mut callback)?;

    // FVM requires a stack size of 64MiB. The alternative is to use `ThreadedExecutor` from
    // FVM, but that introduces some constraints, and possible deadlocks.
    stacker::grow(64 << 20, || -> anyhow::Result<ExecutedTipset> {
        let mut vm = exec.create_vm(parent_state, epoch, tipset.min_timestamp(), enable_tracing)?;

        // step 4: apply tipset messages
        let (receipts, events, events_roots) =
            vm.apply_block_messages(&block_messages, epoch, callback)?;

        // step 5: construct receipt root from receipts
        let receipt_root = Amtv0::new_from_iter(chain_index.db(), receipts.iter())?;

        // step 6: store events AMTs in the blockstore
        for (events, events_root) in events.iter().zip(events_roots.iter()) {
            if let Some(events) = events {
                let event_root =
                    events_root.context("events root should be present when events present")?;
                // Store the events AMT - the root CID should match the one computed by FVM
                let derived_event_root = Amt::new_from_iter_with_bit_width(
                    chain_index.db(),
                    EVENTS_AMT_BITWIDTH,
                    events.iter(),
                )
                .map_err(|e| Error::Other(format!("failed to store events AMT: {e}")))?;

                // Verify the stored root matches the FVM-computed root
                ensure!(
                    derived_event_root == event_root,
                    "Events AMT root mismatch: derived={derived_event_root}, actual={event_root}."
                );
            }
        }

        let state_root = vm.flush()?;

        // Update executed tipset cache
        let messages: Vec<ChainMessage> = block_messages
            .into_iter()
            .flat_map(|bm| bm.messages)
            .collect_vec();
        anyhow::ensure!(
            messages.len() == receipts.len() && messages.len() == events.len(),
            "length of messages, receipts, and events should match",
        );
        Ok(ExecutedTipset {
            state_root,
            receipt_root,
            executed_messages: messages
                .into_iter()
                .zip(receipts)
                .zip(events)
                .map(|((message, receipt), events)| ExecutedMessage {
                    message,
                    receipt,
                    events,
                })
                .collect_vec()
                .into(),
        })
    })
}

#[allow(clippy::too_many_arguments)]
pub(in crate::state_manager) fn compute_state_blocking(
    _height: ChainEpoch,
    messages: Vec<Message>,
    tipset: Tipset,
    chain_index: ChainIndex,
    chain_config: Arc<ChainConfig>,
    beacon: Arc<BeaconSchedule>,
    engine: &MultiEngine,
    callback: Option<impl FnMut(MessageCallbackCtx<'_>) -> anyhow::Result<()>>,
    enable_tracing: VMTrace,
) -> anyhow::Result<ExecutedTipset> {
    if !messages.is_empty() {
        anyhow::bail!("Applying messages is not yet implemented.");
    }

    let output = apply_block_messages_blocking(
        chain_index,
        chain_config,
        beacon,
        engine,
        tipset,
        callback,
        enable_tracing,
    )?;

    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::blocks::{CachingBlockHeader, RawBlockHeader, TipsetKey, TxMeta};
    use crate::utils::db::CborStoreExt as _;

    #[test]
    fn tipset_message_receipts_iter_pairs_in_order() {
        let msg_count = 3u64;
        let messages = (0..msg_count)
            .map(|i| {
                ChainMessage::Unsigned(Arc::new(Message {
                    sequence: i,
                    ..Default::default()
                }))
            })
            .collect_vec();
        let receipts = (0..msg_count)
            .map(|i| Receipt::with_gas_used((i + 1) * 10))
            .collect_vec();
        let expected = (0..msg_count).map(|i| (i, (i + 1) * 10)).collect_vec();

        let executed = TipsetMessageReceipts::Executed(Arc::new(
            messages
                .iter()
                .zip(receipts.iter())
                .map(|(m, r)| ExecutedMessage {
                    message: m.clone(),
                    receipt: r.clone(),
                    events: None,
                })
                .collect(),
        ));
        let stored = TipsetMessageReceipts::Stored(Arc::new(messages), receipts);

        for variant in [&executed, &stored] {
            let got = variant
                .iter()
                .map(|(m, r)| (m.message().sequence, r.gas_used()))
                .collect_vec();
            assert_eq!(got, expected);
        }
    }

    /// A `TxMeta` with empty message roots, so `messages_for_tipset` yields zero messages.
    fn empty_message_meta(db: &impl Blockstore) -> Cid {
        let empty = Amtv0::<Cid, _>::new(db).flush().unwrap();
        db.put_cbor_default(&TxMeta {
            bls_message_root: empty,
            secp_message_root: empty,
        })
        .unwrap()
    }

    /// A single block with the given epoch, parents, message meta and receipt root. The nonzero
    /// timestamp lets an epoch-0 block serve as a genesis (which must not be at time 0).
    fn block(
        epoch: ChainEpoch,
        parents: TipsetKey,
        messages: Cid,
        receipts: Cid,
    ) -> CachingBlockHeader {
        CachingBlockHeader::new(RawBlockHeader {
            parents,
            epoch,
            messages,
            message_receipts: receipts,
            timestamp: 1,
            ..Default::default()
        })
    }

    #[tokio::test]
    async fn tipset_message_receipts_covers_all_paths() {
        use crate::chain::ChainStore;
        use crate::db::MemoryDB;
        use crate::networks::ChainConfig;

        let db = Arc::new(MemoryDB::default());
        let genesis = block(0, TipsetKey::default(), Cid::default(), Cid::default());
        db.put_cbor_default(&genesis).unwrap();
        let cs = ChainStore::new(db.clone(), Arc::new(ChainConfig::default()), genesis).unwrap();
        let genesis_key = cs.genesis_tipset().key().clone();

        // `ts` (epoch 1, no messages) and `head` (epoch 2), its child and the chain head, so
        // `load_child_tipset(ts)` resolves `head`.
        let ts = Tipset::from(block(
            1,
            genesis_key.clone(),
            empty_message_meta(&db),
            Cid::default(),
        ));
        let head = Tipset::from(block(
            2,
            ts.key().clone(),
            Cid::default(),
            Receipt::store_receipts(&db, 0).unwrap(),
        ));
        for b in ts.block_headers().iter().chain(head.block_headers().iter()) {
            db.put_cbor_default(b).unwrap();
        }
        cs.set_heaviest_tipset(head.clone()).unwrap();
        let sm = StateManager::new(cs).unwrap();

        // Cache hit -> Executed.
        sm.cache.insert(
            ts.key().clone(),
            ExecutedTipset {
                state_root: Cid::default(),
                receipt_root: Cid::default(),
                executed_messages: Arc::new(vec![]),
            },
        );
        assert!(matches!(
            sm.tipset_message_receipts(&ts, None).await.unwrap(),
            TipsetMessageReceipts::Executed(_)
        ));
        sm.cache.remove(ts.key());

        // Caller-supplied child -> Stored (assertion holds, receipts read, counts match).
        assert!(matches!(
            sm.tipset_message_receipts(&ts, Some(&head)).await.unwrap(),
            TipsetMessageReceipts::Stored(m, r) if m.is_empty() && r.is_empty()
        ));

        // `None` resolves the child via `load_child_tipset` -> Stored.
        assert!(matches!(
            sm.tipset_message_receipts(&ts, None).await.unwrap(),
            TipsetMessageReceipts::Stored(..)
        ));

        // `head` has no child, so `None` resolves to nothing and the loader fallback errors.
        assert!(sm.tipset_message_receipts(&head, None).await.is_err());

        // Receipt tipset that is not `ts`'s child -> parent-mismatch error.
        let wrong = Tipset::from(block(
            2,
            genesis_key,
            Cid::default(),
            Receipt::store_receipts(&db, 0).unwrap(),
        ));
        assert!(
            sm.tipset_message_receipts(&ts, Some(&wrong))
                .await
                .err()
                .expect("expected error")
                .to_string()
                .contains("should be the parent")
        );

        // Receipt count != message count -> error.
        let extra = Tipset::from(block(
            2,
            ts.key().clone(),
            Cid::default(),
            Receipt::store_receipts(&db, 1).unwrap(),
        ));
        assert!(
            sm.tipset_message_receipts(&ts, Some(&extra))
                .await
                .err()
                .expect("expected error")
                .to_string()
                .contains("mismatching message and receipt counts")
        );

        // Unreadable receipt root -> falls back to the full loader (re-resolves the on-chain child).
        // Keep last: this populates `ts`'s cache, which would mask the `Stored` cases above.
        let unreadable = Tipset::from(block(2, ts.key().clone(), Cid::default(), Cid::default()));
        assert!(matches!(
            sm.tipset_message_receipts(&ts, Some(&unreadable))
                .await
                .unwrap(),
            TipsetMessageReceipts::Executed(_)
        ));
    }
}