forest/rpc/methods/eth/tipset_resolver.rs
1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use super::*;
5use crate::rpc::chain::{ChainGetTipSetFinalityStatus, SAFE_HEIGHT_DISTANCE};
6
7pub struct TipsetResolver<'a, DB>
8where
9 DB: Blockstore + Send + Sync + 'static,
10{
11 ctx: &'a Ctx<DB>,
12 api_version: ApiPaths,
13}
14
15impl<'a, DB> TipsetResolver<'a, DB>
16where
17 DB: Blockstore + Send + Sync + 'static,
18{
19 /// Creates a TipsetResolver that holds a reference to the given chain context and the API version to use for tipset resolution.
20 pub fn new(ctx: &'a Ctx<DB>, api_version: ApiPaths) -> Self {
21 Self { ctx, api_version }
22 }
23
24 /// Resolve a tipset from a block identifier that may be a predefined tag, block height, or block hash.
25 ///
26 /// Attempts to resolve the provided `block_param` into a concrete `Tipset`. The parameter may be:
27 /// - a predefined tag (e.g., `Predefined::Latest`, `Predefined::Safe`, `Predefined::Finalized`),
28 /// - a block height (number or object form), or
29 /// - a block hash (raw hash or object form that can require canonicalization).
30 ///
31 /// # Parameters
32 ///
33 /// - `block_param` — block identifier to resolve; accepts any type convertible to `BlockNumberOrHash`.
34 /// - `resolve` — rule for how to treat null/unknown tipsets when resolving by height/hash.
35 ///
36 /// # Returns
37 ///
38 /// The resolved `Tipset` on success.
39 pub async fn tipset_by_block_number_or_hash(
40 &self,
41 block_param: impl Into<BlockNumberOrHash>,
42 resolve: ResolveNullTipset,
43 ) -> anyhow::Result<Tipset> {
44 match block_param.into() {
45 BlockNumberOrHash::PredefinedBlock(tag) => self.resolve_predefined_tipset(tag).await,
46 BlockNumberOrHash::BlockNumber(block_number)
47 | BlockNumberOrHash::BlockNumberObject(BlockNumber { block_number }) => {
48 resolve_block_number_tipset(self.ctx.chain_store(), block_number, resolve)
49 }
50 BlockNumberOrHash::BlockHash(block_hash) => {
51 resolve_block_hash_tipset(self.ctx.chain_store(), &block_hash, false, resolve)
52 }
53 BlockNumberOrHash::BlockHashObject(BlockHash {
54 block_hash,
55 require_canonical,
56 }) => resolve_block_hash_tipset(
57 self.ctx.chain_store(),
58 &block_hash,
59 require_canonical,
60 resolve,
61 ),
62 }
63 }
64
65 /// Resolve a predefined tipset according to the resolver's API version.
66 ///
67 /// # Returns
68 ///
69 /// The resolved `Tipset`, or an error if resolution fails.
70 async fn resolve_predefined_tipset(&self, tag: Predefined) -> anyhow::Result<Tipset> {
71 match self.api_version {
72 ApiPaths::V2 => self.resolve_predefined_tipset_v2(tag).await,
73 ApiPaths::V1 | ApiPaths::V0 => self.resolve_predefined_tipset_v1(tag).await,
74 }
75 }
76
77 /// Resolves a predefined tipset using the V1 resolution policy, or delegates to the V2 resolver when the
78 /// V1 finality-resolution override is not enabled.
79 ///
80 /// If the environment variable `FOREST_ETH_V1_DISABLE_F3_FINALITY_RESOLUTION` is set to a truthy value,
81 /// this function first attempts common predefined tag resolution (e.g., Pending, Latest). If that yields
82 /// no result, the function uses expected-consensus finality to resolve the "safe" or "finalized" tipset
83 /// for the corresponding `Predefined` tag. When the environment variable is not set or is falsy,
84 /// resolution is delegated to the V2 resolver.
85 ///
86 /// # Errors
87 ///
88 /// Returns an error if the requested predefined tag is unknown or if tipset resolution fails.
89 async fn resolve_predefined_tipset_v1(&self, tag: Predefined) -> anyhow::Result<Tipset> {
90 const ETH_V1_DISABLE_F3_FINALITY_RESOLUTION_ENV_KEY: &str =
91 "FOREST_ETH_V1_DISABLE_F3_FINALITY_RESOLUTION";
92
93 crate::def_is_env_truthy!(
94 f3_finality_disabled,
95 ETH_V1_DISABLE_F3_FINALITY_RESOLUTION_ENV_KEY
96 );
97
98 if f3_finality_disabled() {
99 if let Some(ts) = self.resolve_common_predefined_tipset(tag)? {
100 Ok(ts)
101 } else {
102 match tag {
103 Predefined::Safe => self.get_ec_safe_tipset(),
104 Predefined::Finalized => self.get_ec_finalized_tipset(),
105 tag => anyhow::bail!("unknown block tag: {tag}"),
106 }
107 }
108 } else {
109 self.resolve_predefined_tipset_v2(tag).await
110 }
111 }
112
113 /// Resolves a predefined tipset according to the v2 API behavior.
114 ///
115 /// Uses a common predefined-tipset lookup first; if that yields no result, resolves
116 /// `Safe` and `Finalized` tags via the v2 chain getters. Returns an error for unknown tags
117 /// or on underlying resolution failures.
118 ///
119 /// # Returns
120 ///
121 /// The resolved `Tipset` on success.
122 async fn resolve_predefined_tipset_v2(&self, tag: Predefined) -> anyhow::Result<Tipset> {
123 if let Some(ts) = self.resolve_common_predefined_tipset(tag)? {
124 Ok(ts)
125 } else {
126 match tag {
127 Predefined::Safe => ChainGetTipSetV2::get_latest_safe_tipset(self.ctx).await,
128 Predefined::Finalized => {
129 ChainGetTipSetV2::get_latest_finalized_tipset(self.ctx).await
130 }
131 tag => anyhow::bail!("unknown block tag: {tag}"),
132 }
133 }
134 }
135
136 /// Attempt to resolve a predefined block tag to a commonly-handled tipset.
137 ///
138 /// Returns `Some(Tipset)` for `Predefined::Pending` (current head) and
139 /// `Predefined::Latest` (the tipset at the head's parents). Returns `Ok(None)`
140 /// when the tag is not handled by this common-resolution path (caller should
141 /// try other resolution strategies). Resolving `Predefined::Earliest` fails
142 /// with an error.
143 fn resolve_common_predefined_tipset(&self, tag: Predefined) -> anyhow::Result<Option<Tipset>> {
144 let head = self.ctx.chain_store().heaviest_tipset();
145 match tag {
146 Predefined::Earliest => bail!("block param \"earliest\" is not supported"),
147 Predefined::Pending => Ok(Some(head)),
148 Predefined::Latest => Ok(Some(
149 self.ctx
150 .chain_index()
151 .load_required_tipset(head.parents())?,
152 )),
153 Predefined::Safe | Predefined::Finalized => Ok(None),
154 }
155 }
156
157 /// Returns the tipset considered "safe" relative to the current heaviest tipset.
158 ///
159 /// The safe tipset is the tipset at height `max(head.epoch() - SAFE_HEIGHT_DISTANCE, 0)`.
160 pub fn get_ec_safe_tipset(&self) -> anyhow::Result<Tipset> {
161 let head = self.ctx.chain_store().heaviest_tipset();
162 let safe_height = (head.epoch() - SAFE_HEIGHT_DISTANCE).max(0);
163 Ok(self.ctx.chain_index().tipset_by_height(
164 safe_height,
165 head,
166 ResolveNullTipset::TakeOlder,
167 )?)
168 }
169
170 /// Returns the tipset considered finalized by the expected-consensus finality calculator(`FRC-0089`).
171 pub fn get_ec_finalized_tipset(&self) -> anyhow::Result<Tipset> {
172 let head = self.ctx.chain_store().heaviest_tipset();
173 let (_, ec_finalized_tipset) =
174 ChainGetTipSetFinalityStatus::get_ec_finality_threshold_depth_and_tipset_with_cache(
175 self.ctx,
176 head.clone(),
177 );
178 ec_finalized_tipset.context("failed to resolve EC finalized tipset")
179 }
180}