Skip to main content

forest/chain_sync/
tipset_syncer.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use crate::chain_sync::BadBlockCache;
5use crate::db::DbImpl;
6use crate::networks::Height;
7use crate::prelude::*;
8use crate::shim::clock::ALLOWABLE_CLOCK_DRIFT;
9use crate::shim::crypto::SignatureType;
10use crate::shim::version::NetworkVersion;
11use crate::shim::{
12    address::Address,
13    crypto::verify_bls_aggregate,
14    econ::BLOCK_GAS_LIMIT,
15    gas::{PriceList, price_list_by_network_version},
16    state_tree::StateTree,
17};
18use crate::state_manager::ExecutedTipset;
19use crate::state_manager::{Error as StateManagerError, StateManager, utils::is_valid_for_sending};
20use crate::{
21    blocks::{Block, CachingBlockHeader, Error as ForestBlockError, FullTipset, Tipset},
22    fil_cns::{self, FilecoinConsensus, FilecoinConsensusError},
23};
24use crate::{
25    chain::{ChainStore, Error as ChainStoreError},
26    metrics::HistogramTimerExt,
27};
28use crate::{
29    eth::is_valid_eth_tx_for_sending,
30    message::{MessageRead, valid_for_block_inclusion},
31};
32use ahash::HashMap;
33use futures::TryFutureExt;
34use nunny::Vec as NonEmpty;
35use thiserror::Error;
36use tokio::task::JoinSet;
37use tracing::{trace, warn};
38
39use crate::chain_sync::{consensus::collect_errs, metrics, validation::TipsetValidator};
40
41#[derive(Debug, Error)]
42pub enum TipsetSyncerError {
43    #[error("Block must have a signature")]
44    BlockWithoutSignature,
45    #[error("Block without BLS aggregate signature")]
46    BlockWithoutBlsAggregate,
47    #[error("Block received from the future: now = {0}, block = {1}")]
48    TimeTravellingBlock(u64, u64),
49    #[error("Validation error: {0}")]
50    Validation(String),
51    /// Locally computed parent state or receipt root does not match the block header.
52    /// Distinct from [`Self::Validation`] so the chain follower can repair locally
53    /// corrupted inputs (e.g. a stale tipset lookup entry) before treating the block as bad.
54    #[error("Parent chain state mismatch: {0}")]
55    ParentChainStateMismatch(String),
56    #[error("Processing error: {0}")]
57    Calculation(String),
58    #[error("Chain store error: {0}")]
59    ChainStore(#[from] ChainStoreError),
60    #[error("StateManager error: {0}")]
61    StateManager(#[from] StateManagerError),
62    #[error("Block error: {0}")]
63    BlockError(#[from] ForestBlockError),
64    #[error("Querying tipsets from the network failed: {0}")]
65    NetworkTipsetQueryFailed(String),
66    #[error("BLS aggregate signature {0} was invalid for msgs {1}")]
67    BlsAggregateSignatureInvalid(String, String),
68    #[error("Message signature invalid: {0}")]
69    MessageSignatureInvalid(String),
70    #[error("Block message root does not match: expected {0}, computed {1}")]
71    BlockMessageRootInvalid(String, String),
72    #[error("Computing message root failed: {0}")]
73    ComputingMessageRoot(String),
74    #[error("Resolving address from message failed: {0}")]
75    ResolvingAddressFromMessage(String),
76    #[error("Loading tipset parent from the store failed: {0}")]
77    TipsetParentNotFound(ChainStoreError),
78    #[error("Consensus error: {0}")]
79    ConsensusError(FilecoinConsensusError),
80    #[error(
81        "Block had a signed message at index {0} whose signature type {1} is not allowed in the SECP message list"
82    )]
83    SecpSignatureTypeInvalid(usize, SignatureType),
84}
85
86impl From<tokio::task::JoinError> for TipsetSyncerError {
87    fn from(err: tokio::task::JoinError) -> Self {
88        TipsetSyncerError::NetworkTipsetQueryFailed(format!("{err}"))
89    }
90}
91
92impl TipsetSyncerError {
93    /// Concatenate all validation error messages into one comma separated
94    /// version.
95    fn concat(errs: NonEmpty<TipsetSyncerError>) -> Self {
96        let msg = errs.iter().map(|e| e.to_string()).collect_vec().join(", ");
97
98        if errs
99            .iter()
100            .any(|e| matches!(e, TipsetSyncerError::ParentChainStateMismatch(_)))
101        {
102            TipsetSyncerError::ParentChainStateMismatch(msg)
103        } else {
104            TipsetSyncerError::Validation(msg)
105        }
106    }
107}
108
109/// Validates full blocks in the tipset in parallel (since the messages are not
110/// executed), adding the successful ones to the tipset tracker, and the failed
111/// ones to the bad block cache, depending on strategy. Any bad block fails
112/// validation.
113pub async fn validate_tipset(
114    state_manager: &StateManager,
115    full_tipset: FullTipset,
116    bad_block_cache: Option<BadBlockCache>,
117) -> Result<(), TipsetSyncerError> {
118    if full_tipset
119        .key()
120        .eq(state_manager.chain_store().genesis_tipset().key())
121    {
122        trace!("Skipping genesis tipset validation");
123        return Ok(());
124    }
125
126    let timer = metrics::TIPSET_PROCESSING_TIME.start_timer();
127
128    let epoch = full_tipset.epoch();
129    let parent_state = *full_tipset.parent_state();
130    let tipset_key = full_tipset.key();
131    trace!("Tipset keys: {tipset_key}");
132    let blocks = full_tipset.into_blocks();
133    let mut validations = JoinSet::new();
134    for b in blocks {
135        validations.spawn(validate_block(state_manager.shallow_clone(), Arc::new(b)));
136    }
137
138    while let Some(result) = validations.join_next().await {
139        match result? {
140            Ok(block) => {
141                state_manager
142                    .chain_store()
143                    .add_to_tipset_tracker(block.header());
144            }
145            Err(boxed) => {
146                let (cid, why) = *boxed;
147                warn!(
148                    "Validating block [CID = {cid}, PARENT_STATE = {parent_state}] in EPOCH = {epoch} failed: {why}",
149                );
150                match &why {
151                    TipsetSyncerError::TimeTravellingBlock(_, _) => {
152                        // Do not mark a block as bad for temporary errors.
153                        // See <https://github.com/filecoin-project/lotus/blob/v1.34.1/chain/sync.go#L602> in Lotus
154                    }
155                    _ => {
156                        // Do not mark block as bad if the parent state tree does not exist
157                        if StateTree::new_from_root(state_manager.db(), &parent_state).is_ok()
158                            && let Some(bad_block_cache) = bad_block_cache
159                        {
160                            bad_block_cache.push(cid);
161                        }
162                    }
163                };
164                return Err(why);
165            }
166        }
167    }
168    drop(timer);
169    Ok(())
170}
171
172/// Validate the block according to the rules specific to the consensus being
173/// used, and the common rules that pertain to the assumptions of the
174/// `ChainSync` protocol.
175///
176/// Returns the validated block if `Ok`.
177/// Returns the block CID (for marking bad) and `Error` if invalid (`Err`).
178///
179/// Common validation includes:
180/// * Sanity checks
181/// * Clock drifts
182/// * Signatures
183/// * Message inclusion (fees, sequences)
184/// * Parent related fields: base fee, weight, the state root
185/// * NB: This is where the messages in the *parent* tipset are executed.
186///
187/// Consensus specific validation should include:
188/// * Checking that the messages in the block correspond to the agreed upon
189///   total ordering
190/// * That the block is a deterministic derivative of the underlying consensus
191async fn validate_block(
192    state_manager: StateManager,
193    block: Arc<Block>,
194) -> Result<Arc<Block>, Box<(Cid, TipsetSyncerError)>> {
195    let consensus = FilecoinConsensus::new(state_manager.beacon_schedule().clone());
196    trace!(
197        "Validating block: epoch = {}, weight = {}, key = {}",
198        block.header().epoch,
199        block.header().weight,
200        block.header().cid(),
201    );
202    let chain_store = state_manager.chain_store().shallow_clone();
203    let block_cid = block.cid();
204
205    // Check block validation cache in store
206    let is_validated = chain_store.is_block_validated(block_cid);
207    if is_validated {
208        return Ok(block);
209    }
210
211    let _timer = metrics::BLOCK_VALIDATION_TIME.start_timer();
212
213    let header = block.header();
214
215    // Check to ensure all optional values exist
216    block_sanity_checks(header).map_err(|e| Box::new((*block_cid, e)))?;
217    block_timestamp_checks(header).map_err(|e| Box::new((*block_cid, e)))?;
218
219    let base_tipset = chain_store
220        .chain_index()
221        .load_required_tipset(&header.parents)
222        // The parent tipset will always be there when calling validate_block
223        // as part of the sync_tipset_range flow because all of the headers in the range
224        // have been committed to the store. When validate_block is called from sync_tipset
225        // this guarantee does not exist, so we create a specific error to inform the caller
226        // not to add this block to the bad blocks cache.
227        .map_err(|why| Box::new((*block_cid, TipsetSyncerError::TipsetParentNotFound(why))))?;
228
229    // Retrieve lookback tipset for validation
230    let lookback_state = ChainStore::get_lookback_tipset_for_round(
231        state_manager.chain_store().chain_index().shallow_clone(),
232        state_manager.chain_config().shallow_clone(),
233        base_tipset.shallow_clone(),
234        block.header().epoch,
235    )
236    .await
237    .map_err(|e| Box::new((*block_cid, e.into())))
238    .map(|(_, s)| Arc::new(s))?;
239
240    // Work address needed for async validations, so necessary
241    // to do sync to avoid duplication
242    let work_addr = state_manager
243        .get_miner_work_addr(*lookback_state, &header.miner_address)
244        .map_err(|e| Box::new((*block_cid, e.into())))?;
245
246    // Async validations
247    let mut validations = JoinSet::new();
248
249    // Check block messages
250    validations.spawn(check_block_messages(
251        state_manager.shallow_clone(),
252        block.shallow_clone(),
253        base_tipset.shallow_clone(),
254    ));
255
256    // Base fee check
257    validations.spawn_blocking({
258        let smoke_height = state_manager.chain_config().epoch(Height::Smoke);
259        let firehorse_height = state_manager.chain_config().epoch(Height::FireHorse);
260        let base_tipset = base_tipset.shallow_clone();
261        let block_store = state_manager.db_owned();
262        let block = block.shallow_clone();
263        move || {
264            let base_fee = crate::chain::compute_base_fee(
265                &block_store,
266                &base_tipset,
267                smoke_height,
268                firehorse_height,
269            )
270            .map_err(|e| {
271                TipsetSyncerError::Validation(format!("Could not compute base fee: {e}"))
272            })?;
273            let parent_base_fee = &block.header.parent_base_fee;
274            if &base_fee != parent_base_fee {
275                return Err(TipsetSyncerError::Validation(format!(
276                    "base fee doesn't match: {parent_base_fee} (header), {base_fee} (computed)"
277                )));
278            }
279            Ok(())
280        }
281    });
282
283    // Parent weight calculation check
284    validations.spawn_blocking({
285        let block_store = state_manager.db_owned();
286        let base_tipset = base_tipset.shallow_clone();
287        let weight = header.weight.clone();
288        move || {
289            let calc_weight = fil_cns::weight(&block_store, &base_tipset).map_err(|e| {
290                TipsetSyncerError::Calculation(format!("Error calculating weight: {e:#}"))
291            })?;
292            if weight != calc_weight {
293                return Err(TipsetSyncerError::Validation(format!(
294                    "Parent weight doesn't match: {weight} (header), {calc_weight} (computed)"
295                )));
296            }
297            Ok(())
298        }
299    });
300
301    // State root and receipt root validations
302    validations.spawn({
303        let state_manager = state_manager.shallow_clone();
304        let block = block.shallow_clone();
305        async move {
306            let header = block.header();
307            let ExecutedTipset {
308                state_root,
309                receipt_root,
310                ..
311            } = state_manager
312                .load_executed_tipset(&base_tipset)
313                .await
314                .map_err(|e| {
315                    TipsetSyncerError::Calculation(format!("Failed to calculate state: {e:#}"))
316                })?;
317
318            if state_root != header.state_root {
319                return Err(TipsetSyncerError::ParentChainStateMismatch(format!(
320                    "Parent state root did not match computed state: {} (header), {} (computed)",
321                    header.state_root, state_root,
322                )));
323            }
324
325            if receipt_root != header.message_receipts {
326                return Err(TipsetSyncerError::ParentChainStateMismatch(format!(
327                    "Parent receipt root did not match computed root: {} (header), {} (computed)",
328                    header.message_receipts, receipt_root
329                )));
330            }
331            Ok(())
332        }
333    });
334
335    // Block signature check
336    validations.spawn_blocking({
337        let block = block.shallow_clone();
338        move || {
339            block.header().verify_signature_against(&work_addr)?;
340            Ok(())
341        }
342    });
343
344    validations.spawn({
345        let block = block.shallow_clone();
346        async move {
347            consensus
348                .validate_block(state_manager, block)
349                .map_err(|errs| {
350                    // NOTE: Concatenating errors here means the wrapper type of error
351                    // never surfaces, yet we always pay the cost of the generic argument.
352                    // But there's no reason `validate_block` couldn't return a list of all
353                    // errors instead of a single one that has all the error messages,
354                    // removing the caller's ability to distinguish between them.
355
356                    TipsetSyncerError::concat(
357                        errs.into_iter_ne()
358                            .map(TipsetSyncerError::ConsensusError)
359                            .collect_vec(),
360                    )
361                })
362                .await
363        }
364    });
365
366    // Collect the errors from the async validations
367    if let Err(errs) = collect_errs(validations).await {
368        return Err(Box::new((*block_cid, TipsetSyncerError::concat(errs))));
369    }
370
371    chain_store.mark_block_as_validated(block_cid);
372
373    Ok(block)
374}
375
376/// Runs the per-message checks of [`check_block_messages`], carrying the state they accumulate
377/// across a block's messages.
378struct MessageChecker {
379    price_list: PriceList,
380    network_version: NetworkVersion,
381    tree: StateTree<DbImpl>,
382    sum_gas_limit: u64,
383    account_sequences: HashMap<Address, u64>,
384}
385
386impl MessageChecker {
387    /// Generic over the message so that a block's BLS and `SECP` lists each get a copy specialized
388    /// to what they carry: the gas floor is charged over the whole chain message, while the rest of
389    /// validation applies to the message the VM executes.
390    fn check(&mut self, msg: &impl MessageRead) -> anyhow::Result<()> {
391        // Phase 1: Syntactic validation
392        let min_gas = self.price_list.on_chain_message(msg.chain_length()?);
393        let msg = msg.vm_message();
394        valid_for_block_inclusion(msg, min_gas.total(), self.network_version)
395            .map_err(|e| anyhow::anyhow!("{e}"))?;
396        self.sum_gas_limit += msg.gas_limit();
397        anyhow::ensure!(
398            self.sum_gas_limit <= BLOCK_GAS_LIMIT,
399            "block gas limit exceeded"
400        );
401
402        // Phase 2: (Partial) Semantic validation
403        // Send exists and is an account actor, and sequence is correct.
404        // From nv13 the sender is keyed by its resolved ID, as Lotus `checkBlockMessages`.
405        // https://github.com/filecoin-project/lotus/blob/0065aa70bb20bf87801b6e96ecb7e7fe707566bd/chain/consensus/common.go#L234-L261
406        let sender = if self.network_version >= NetworkVersion::V13 {
407            self.tree.lookup_required_id_address(&msg.from())?
408        } else {
409            msg.from()
410        };
411
412        let sequence: u64 = match self.account_sequences.get(&sender) {
413            Some(sequence) => *sequence,
414            None => {
415                let actor = self.tree.get_actor(&sender)?.ok_or_else(|| {
416                    anyhow::anyhow!(
417                        "Failed to retrieve nonce for addr: Actor does not exist in state"
418                    )
419                })?;
420                anyhow::ensure!(
421                    is_valid_for_sending(self.network_version, &actor),
422                    "not valid for sending!"
423                );
424                actor.sequence
425            }
426        };
427
428        // Sequence equality check
429        anyhow::ensure!(
430            sequence == msg.sequence(),
431            "Message has incorrect sequence (exp: {} got: {})",
432            sequence,
433            msg.sequence()
434        );
435        self.account_sequences.insert(sender, sequence + 1);
436        Ok(())
437    }
438}
439
440/// Validate messages in a full block, relative to the parent tipset.
441///
442/// This includes:
443/// * signature checks
444/// * gas limits, and prices
445/// * account nonce values
446/// * the message root in the header
447///
448/// NB: This loads/computes the state resulting from the execution of the parent
449/// tipset.
450async fn check_block_messages(
451    state_manager: StateManager,
452    block: Arc<Block>,
453    base_tipset: Tipset,
454) -> Result<(), TipsetSyncerError> {
455    let network_version = state_manager
456        .chain_config()
457        .network_version(block.header.epoch);
458    let eth_chain_id = state_manager.chain_config().eth_chain_id;
459
460    if let Some(sig) = &block.header().bls_aggregate {
461        // Do the initial loop here
462        // check block message and signatures in them
463        let mut pub_keys = Vec::with_capacity(block.bls_msgs().len());
464        let mut cids = Vec::with_capacity(block.bls_msgs().len());
465        let db = state_manager.db();
466        for m in block.bls_msgs() {
467            let pk = StateManager::get_bls_public_key(db, m.from(), *base_tipset.parent_state())?;
468            pub_keys.push(pk);
469            cids.push(m.cid().to_bytes());
470        }
471
472        if !verify_bls_aggregate(
473            &cids.iter().map(|x| x.as_slice()).collect_vec(),
474            &pub_keys,
475            sig,
476        ) {
477            return Err(TipsetSyncerError::BlsAggregateSignatureInvalid(
478                format!("{sig:?}"),
479                format!("{cids:?}"),
480            ));
481        }
482    } else {
483        return Err(TipsetSyncerError::BlockWithoutBlsAggregate);
484    }
485
486    let ExecutedTipset { state_root, .. } = state_manager
487        .load_executed_tipset(&base_tipset)
488        .await
489        .map_err(|e| TipsetSyncerError::Calculation(format!("Could not update state: {e:#}")))?;
490    let tree = StateTree::new_from_root(state_manager.db(), &state_root).map_err(|e| {
491        TipsetSyncerError::Calculation(format!(
492            "Could not load from new state root in state manager: {e:#}"
493        ))
494    })?;
495
496    let mut checker = MessageChecker {
497        price_list: price_list_by_network_version(network_version),
498        network_version,
499        tree,
500        sum_gas_limit: 0,
501        account_sequences: HashMap::default(),
502    };
503
504    // Check validity for BLS messages
505    for (i, msg) in block.bls_msgs().iter().enumerate() {
506        checker.check(msg).map_err(|e| {
507            TipsetSyncerError::Validation(format!(
508                "Block had invalid BLS message at index {i}: {e:#}"
509            ))
510        })?;
511    }
512
513    // Check validity for SECP messages
514    for (i, msg) in block.secp_msgs().iter().enumerate() {
515        if network_version >= NetworkVersion::V14
516            && !msg.signature().is_valid_secpk_sig_type(network_version)
517        {
518            return Err(TipsetSyncerError::SecpSignatureTypeInvalid(
519                i,
520                msg.signature().signature_type(),
521            ));
522        }
523        if msg.signature().signature_type() == SignatureType::Delegated
524            && !is_valid_eth_tx_for_sending(eth_chain_id, network_version, msg)
525        {
526            return Err(TipsetSyncerError::Validation(
527                "Network version must be at least NV23 for legacy Ethereum transactions".to_owned(),
528            ));
529        }
530        checker.check(msg).map_err(|e| {
531            TipsetSyncerError::Validation(format!(
532                "block had an invalid secp message at index {i}: {e:#}"
533            ))
534        })?;
535        // Resolve key address for signature verification
536        let key_addr = state_manager
537            .resolve_to_deterministic_address(msg.from(), &base_tipset)
538            .await
539            .map_err(|e| TipsetSyncerError::ResolvingAddressFromMessage(e.to_string()))?;
540        // SecP256K1 Signature validation
541        msg.signature()
542            .authenticate_msg(eth_chain_id, msg, &key_addr)
543            .map_err(|e| TipsetSyncerError::MessageSignatureInvalid(e.to_string()))?;
544    }
545
546    // Validate message root from header matches message root
547    let msg_root = TipsetValidator::compute_msg_root(
548        state_manager.db(),
549        block.bls_msgs().iter().map(|m| m.cid()),
550        block.secp_msgs().iter().map(|m| m.signed_cid()),
551    )
552    .map_err(|err| TipsetSyncerError::ComputingMessageRoot(err.to_string()))?;
553    if block.header().messages != msg_root {
554        return Err(TipsetSyncerError::BlockMessageRootInvalid(
555            format!("{:?}", block.header().messages),
556            format!("{msg_root:?}"),
557        ));
558    }
559
560    Ok(())
561}
562
563/// Checks optional values in header.
564///
565/// It only looks for fields which are common to all consensus types.
566fn block_sanity_checks(header: &CachingBlockHeader) -> Result<(), TipsetSyncerError> {
567    if header.signature.is_none() {
568        return Err(TipsetSyncerError::BlockWithoutSignature);
569    }
570    if header.bls_aggregate.is_none() {
571        return Err(TipsetSyncerError::BlockWithoutBlsAggregate);
572    }
573    Ok(())
574}
575
576/// Check the clock drift.
577fn block_timestamp_checks(header: &CachingBlockHeader) -> Result<(), TipsetSyncerError> {
578    let time_now = chrono::Utc::now().timestamp() as u64;
579    if header.timestamp > time_now.saturating_add(ALLOWABLE_CLOCK_DRIFT) {
580        return Err(TipsetSyncerError::TimeTravellingBlock(
581            time_now,
582            header.timestamp,
583        ));
584    } else if header.timestamp > time_now {
585        warn!(
586            "Got block from the future, but within clock drift threshold, {} > {}",
587            header.timestamp, time_now
588        );
589    }
590    Ok(())
591}
592
593#[cfg(test)]
594mod tests {
595    use super::*;
596
597    #[test]
598    fn concat_preserves_parent_chain_state_mismatch() {
599        let concatenated = TipsetSyncerError::concat(nunny::vec![
600            TipsetSyncerError::Validation("a".into()),
601            TipsetSyncerError::ParentChainStateMismatch("b".into()),
602        ]);
603        assert!(matches!(
604            concatenated,
605            TipsetSyncerError::ParentChainStateMismatch(_)
606        ));
607
608        let concatenated =
609            TipsetSyncerError::concat(nunny::vec![TipsetSyncerError::Validation("a".into())]);
610        assert!(matches!(concatenated, TipsetSyncerError::Validation(_)));
611    }
612
613    mod nonce_keying {
614        use super::*;
615        use crate::db::{DbImpl, MemoryDB};
616        use crate::shim::econ::TokenAmount;
617        use crate::shim::message::Message;
618        use crate::shim::state_tree::{ActorState, StateTree};
619        use crate::test_utils::{account_actor_code, resolving_state_tree};
620        use rstest::rstest;
621
622        /// Builds a state tree where `f1` resolves (via the init actor's address map) to an account
623        /// at an ID address with nonce `base`. Returns the tree and that ID address.
624        fn tree_with_account(db: &DbImpl, f1: Address, base: u64) -> (StateTree<DbImpl>, Address) {
625            let (mut tree, id) = resolving_state_tree(db, f1);
626            tree.set_actor(
627                &id,
628                ActorState::new(
629                    account_actor_code(),
630                    Cid::default(),
631                    TokenAmount::default(),
632                    base,
633                    None,
634                ),
635            )
636            .unwrap();
637            let root = tree.flush().unwrap();
638            (StateTree::new_from_root(db, &root).unwrap(), id)
639        }
640
641        fn msg(from: Address, sequence: u64) -> Message {
642            Message::builder()
643                .to(Address::new_id(99))
644                .from(from)
645                .sequence(sequence)
646                .gas_limit(BLOCK_GAS_LIMIT / 4)
647                .build()
648        }
649
650        /// One account sends under its key address then its ID address at consecutive nonces. From
651        /// nv13 the resolved ID keys both as one sender and the second is accepted; below the gate
652        /// raw keying treats them as two senders and the second is rejected.
653        #[rstest]
654        #[case::nv17_resolves_id(NetworkVersion::V17, true)]
655        #[case::nv12_keys_raw_sender(NetworkVersion::V12, false)]
656        fn sender_keyed_by_resolved_id_from_nv13(
657            #[case] nv: NetworkVersion,
658            #[case] second_form_accepted: bool,
659        ) {
660            let db: DbImpl = Arc::new(MemoryDB::default()).into();
661            let f1 = Address::new_secp256k1(&[0x04; 65]).unwrap();
662            let (tree, f0) = tree_with_account(&db, f1, 7);
663            // The fixture is only meaningful if `f1` actually resolves to the account's ID.
664            assert_eq!(tree.lookup_required_id_address(&f1).unwrap(), f0);
665
666            let mut checker = MessageChecker {
667                price_list: price_list_by_network_version(nv),
668                network_version: nv,
669                tree,
670                sum_gas_limit: 0,
671                account_sequences: HashMap::default(),
672            };
673            checker.check(&msg(f1, 7)).unwrap();
674            assert_eq!(checker.check(&msg(f0, 8)).is_ok(), second_form_accepted);
675        }
676    }
677
678    mod block_messages {
679        use super::*;
680        use crate::blocks::RawBlockHeader;
681        use crate::db::MemoryDB;
682        use crate::message::SignedMessage;
683        use crate::networks::ChainConfig;
684        use crate::shim::crypto::{BLS_SIG_LEN, SECP_SIG_LEN, Signature};
685        use crate::shim::message::Message;
686        use crate::shim::state_tree::StateTreeVersion;
687
688        /// Wide enough that the CBOR encoding of the field does not change when the placeholder is
689        /// replaced by either of the gas floors under test.
690        const GAS_LIMIT_PLACEHOLDER: u64 = 1_000_000;
691
692        fn chain_config() -> Arc<ChainConfig> {
693            Arc::new(ChainConfig::default())
694        }
695
696        /// An upgrade takes effect at the epoch after the one the schedule names, so the
697        /// `Chocolate` epoch itself is still NV13.
698        fn last_epoch_before_nv14(chain_config: &ChainConfig) -> ChainEpoch {
699            chain_config.epoch(Height::Chocolate)
700        }
701
702        fn first_epoch_at_nv14(chain_config: &ChainConfig) -> ChainEpoch {
703            last_epoch_before_nv14(chain_config) + 1
704        }
705
706        /// The first epoch at NV28, so the floors under test are computed with a price list the
707        /// network has actually scheduled.
708        fn first_epoch_at_nv28(chain_config: &ChainConfig) -> ChainEpoch {
709            chain_config.epoch(Height::FireHorse) + 1
710        }
711
712        fn signed_message(gas_limit: u64, signature: Signature) -> SignedMessage {
713            SignedMessage::new_unchecked(
714                Message::builder()
715                    .to(Address::new_id(1))
716                    .from(Address::new_id(2))
717                    .gas_limit(gas_limit)
718                    .build(),
719                signature,
720            )
721        }
722
723        fn secp_message(gas_limit: u64) -> SignedMessage {
724            signed_message(gas_limit, Signature::new_secp256k1(vec![0; SECP_SIG_LEN]))
725        }
726
727        /// A state manager whose base tipset resolves to an empty state tree, so validation gets
728        /// past the state load and into the per-message checks.
729        fn empty_state_manager(chain_config: Arc<ChainConfig>) -> (StateManager, Tipset) {
730            let db = Arc::new(MemoryDB::default());
731            let genesis = CachingBlockHeader::new(RawBlockHeader {
732                timestamp: 7777,
733                ..Default::default()
734            });
735            let chain_store = ChainStore::new(db, chain_config, genesis).unwrap();
736            let state_manager = StateManager::new(chain_store).unwrap();
737
738            let state_root = StateTree::new(state_manager.db(), StateTreeVersion::V5)
739                .unwrap()
740                .flush()
741                .unwrap();
742            let base_tipset = state_manager.chain_store().heaviest_tipset();
743            state_manager.insert_executed_tipset(
744                base_tipset.key().clone(),
745                ExecutedTipset {
746                    state_root,
747                    receipt_root: Cid::default(),
748                    executed_messages: Arc::new(vec![]),
749                },
750            );
751            (state_manager, base_tipset)
752        }
753
754        fn block_with(epoch: ChainEpoch, secp_message: SignedMessage) -> Arc<Block> {
755            Arc::new(Block {
756                header: CachingBlockHeader::new(RawBlockHeader {
757                    epoch,
758                    bls_aggregate: Some(Signature::new_bls(vec![0; BLS_SIG_LEN])),
759                    ..Default::default()
760                }),
761                bls_messages: vec![],
762                secp_messages: vec![Arc::new(secp_message)],
763            })
764        }
765
766        async fn validate(
767            chain_config: Arc<ChainConfig>,
768            epoch: ChainEpoch,
769            signature: Signature,
770        ) -> TipsetSyncerError {
771            let (state_manager, base_tipset) = empty_state_manager(chain_config);
772            let message = signed_message(u64::from(u32::MAX), signature);
773            check_block_messages(state_manager, block_with(epoch, message), base_tipset)
774                .await
775                .unwrap_err()
776        }
777
778        #[tokio::test]
779        async fn bls_signature_type_is_rejected_in_the_secp_message_list() {
780            let chain_config = chain_config();
781            let epoch = first_epoch_at_nv14(&chain_config);
782            let err = validate(
783                chain_config,
784                epoch,
785                Signature::new_bls(vec![0; BLS_SIG_LEN]),
786            )
787            .await;
788            assert!(
789                matches!(
790                    err,
791                    TipsetSyncerError::SecpSignatureTypeInvalid(0, SignatureType::Bls)
792                ),
793                "got: {err}"
794            );
795        }
796
797        #[tokio::test]
798        async fn secp256k1_signature_type_passes_the_guard() {
799            let chain_config = chain_config();
800            let epoch = first_epoch_at_nv14(&chain_config);
801            let err = validate(
802                chain_config,
803                epoch,
804                Signature::new_secp256k1(vec![0; SECP_SIG_LEN]),
805            )
806            .await;
807            assert!(
808                !matches!(err, TipsetSyncerError::SecpSignatureTypeInvalid(..)),
809                "the guard must not fire, got: {err}"
810            );
811        }
812
813        /// The guard only applies from NV14 onwards, so earlier blocks must keep validating.
814        #[tokio::test]
815        async fn signature_type_is_not_checked_before_nv14() {
816            let chain_config = chain_config();
817            let epoch = last_epoch_before_nv14(&chain_config);
818            let err = validate(
819                chain_config,
820                epoch,
821                Signature::new_bls(vec![0; BLS_SIG_LEN]),
822            )
823            .await;
824            assert!(
825                !matches!(err, TipsetSyncerError::SecpSignatureTypeInvalid(..)),
826                "the guard must not fire, got: {err}"
827            );
828        }
829
830        /// The floor a SECP message must clear is charged over its signed encoding, so a block
831        /// carrying a message that only pays for the unsigned encoding must be rejected.
832        #[tokio::test]
833        async fn secp_gas_floor_is_charged_over_the_signed_encoding() {
834            let (state_manager, base_tipset) = empty_state_manager(chain_config());
835            let epoch = first_epoch_at_nv28(state_manager.chain_config());
836            let price_list =
837                price_list_by_network_version(state_manager.chain_config().network_version(epoch));
838            let floor = |length| price_list.on_chain_message(length).total().round_up();
839
840            let placeholder = secp_message(GAS_LIMIT_PLACEHOLDER);
841            let signed_floor = floor(placeholder.chain_length().unwrap());
842            let unsigned_floor = floor(placeholder.vm_message().chain_length().unwrap());
843            assert!(signed_floor > unsigned_floor);
844
845            let underpaying = secp_message(unsigned_floor);
846            let paying = secp_message(signed_floor);
847            for message in [&underpaying, &paying] {
848                assert_eq!(
849                    message.chain_length().unwrap(),
850                    placeholder.chain_length().unwrap(),
851                    "the gas floors must be exact for the messages they are applied to"
852                );
853            }
854
855            let err = check_block_messages(
856                state_manager.shallow_clone(),
857                block_with(epoch, underpaying),
858                base_tipset.shallow_clone(),
859            )
860            .await
861            .unwrap_err();
862            assert!(
863                err.to_string().contains("less than cost"),
864                "a gas limit covering only the unsigned encoding must be rejected, got: {err}"
865            );
866
867            let err = check_block_messages(state_manager, block_with(epoch, paying), base_tipset)
868                .await
869                .unwrap_err();
870            assert!(
871                err.to_string().contains("Actor does not exist in state"),
872                "a gas limit covering the signed encoding must clear the floor, got: {err}"
873            );
874        }
875    }
876}