Skip to main content

forest/rpc/methods/
eth.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4mod bloom;
5pub(crate) mod errors;
6mod eth_tx;
7pub mod filter;
8pub mod pubsub;
9pub(crate) mod pubsub_trait;
10pub mod tipset_resolver;
11pub(crate) mod trace;
12pub mod types;
13mod utils;
14
15use crate::utils::encoding::hex;
16pub use bloom::Bloom;
17pub(crate) use bloom::store_block_logs_bloom;
18use bloom::{EMPTY_BLOOM, FULL_BLOOM, accrue_eth_log, block_logs_bloom};
19pub use tipset_resolver::TipsetResolver;
20use tokio_util::sync::CancellationToken;
21
22use self::eth_tx::*;
23use self::filter::hex_str_to_epoch;
24use self::trace::types::*;
25use self::types::*;
26use super::gas;
27use crate::blocks::{Tipset, TipsetKey};
28use crate::chain::{ChainStore, compute_base_fee, index::ResolveNullTipset};
29use crate::chain_sync::NodeSyncStatus;
30use crate::cid_collections::CidHashSet;
31use crate::db::DbImpl;
32use crate::eth::{
33    EAMMethod, EVMMethod, EthChainId as EthChainIdType, EthEip1559TxArgs, EthLegacyEip155TxArgs,
34    EthLegacyHomesteadTxArgs, parse_eth_transaction,
35};
36use crate::interpreter::VMTrace;
37use crate::lotus_json::{HasLotusJson, NotNullVec, lotus_json_with_self};
38use crate::message::{ChainMessage, MessageRead as _, SignedMessage};
39use crate::networks::Height;
40use crate::prelude::*;
41use crate::rpc::{
42    ApiPaths, Ctx, EthEventHandler, LOOKBACK_NO_LIMIT, Permission, RpcMethod, RpcMethodExt as _,
43    error::ServerError,
44    eth::{
45        errors::{EthErrors, NULL_ROUND_CODE},
46        filter::{
47            EventRevertStatus, SkipEvent, event::EventFilter, mempool::MempoolFilter,
48            tipset::TipSetFilter,
49        },
50    },
51    methods::chain::{ChainGetTipSetV2, PathChange},
52    state::ApiInvocResult,
53    types::{ApiTipsetKey, EventEntry, MessageLookup},
54};
55use crate::shim::actors::{eam, is_evm_actor, system};
56use crate::shim::address::{Address as FilecoinAddress, Protocol};
57use crate::shim::crypto::Signature;
58use crate::shim::econ::{BLOCK_GAS_LIMIT, TokenAmount};
59use crate::shim::executor::{ApplyRet, Receipt};
60use crate::shim::fvm_shared_latest::MethodNum;
61use crate::shim::fvm_shared_latest::address::{Address as VmAddress, DelegatedAddress};
62use crate::shim::fvm_shared_latest::error::ExitCode;
63use crate::shim::gas::GasOutputs;
64use crate::shim::message::Message;
65use crate::shim::{clock::ChainEpoch, state_tree::StateTree};
66use crate::state_manager::{
67    Error as StateManagerError, ExecutedMessage, ExecutedTipset, SenderValidation, StateManager,
68    TipsetState, VMFlush,
69};
70use crate::utils::cache::SizeTrackingCache;
71use crate::utils::encoding::from_slice_with_fallback;
72use crate::utils::misc::env::env_or_default;
73use crate::utils::multihash::prelude::*;
74use ahash::{HashMap, HashSet};
75use anyhow::{Error, Result, anyhow, bail, ensure};
76use enumflags2::{BitFlags, make_bitflags};
77use filter::{ParsedFilter, ParsedFilterTipsets};
78use fvm_ipld_encoding::{CBOR, DAG_CBOR, IPLD_RAW, RawBytes};
79use get_size2::GetSize;
80use ipld_core::ipld::Ipld;
81use nonzero_ext::nonzero;
82use num::{BigInt, Zero};
83use nunny::Vec as NonEmpty;
84use schemars::JsonSchema;
85use serde::{Deserialize, Serialize};
86use std::num::NonZeroUsize;
87use std::ops::RangeInclusive;
88use std::str::FromStr;
89use std::sync::{LazyLock, OnceLock};
90use utils::{ActorStateEthExt as _, decode_payload, lookup_eth_address};
91
92static FOREST_TRACE_FILTER_MAX_RESULT: LazyLock<u64> =
93    LazyLock::new(|| env_or_default("FOREST_TRACE_FILTER_MAX_RESULT", 500));
94
95const MASKED_ID_PREFIX: [u8; 12] = [0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
96
97/// Ethereum address size in bytes.
98const ADDRESS_LENGTH: usize = 20;
99
100/// Ethereum Virtual Machine word size in bytes.
101const EVM_WORD_LENGTH: usize = 32;
102
103/// Keccak-256 of an RLP of an empty array.
104/// In Filecoin, we don't have the concept of uncle blocks but rather use tipsets to reward miners
105/// who craft blocks.
106const EMPTY_UNCLES: &str = "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347";
107
108/// Keccak-256 of the RLP of null.
109const EMPTY_ROOT: &str = "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421";
110
111/// The address used in messages to actors that have since been deleted.
112pub(crate) const REVERTED_ETH_ADDRESS: &str = "0xff0000000000000000000000ffffffffffffffff";
113
114#[derive(
115    Eq,
116    Hash,
117    PartialEq,
118    Debug,
119    Deserialize,
120    Serialize,
121    Default,
122    Clone,
123    Copy,
124    JsonSchema,
125    GetSize,
126    derive_more::From,
127    derive_more::Into,
128    derive_more::Deref,
129)]
130pub struct EthBigInt(
131    // `ethereum_types::U256` serializes as a `0x`-prefixed, leading-zero-trimmed hex string,
132    // which matches the Ethereum JSON-RPC wire format used by Lotus.
133    #[schemars(with = "String")]
134    #[get_size(ignore)]
135    #[serde(deserialize_with = "deserialize_quantity")]
136    ethereum_types::U256,
137);
138lotus_json_with_self!(EthBigInt);
139
140/// Canonical quantities only: `0x` prefix, no leading zeros, at most 256 bits.
141fn deserialize_quantity<'de, D: serde::Deserializer<'de>>(
142    deserializer: D,
143) -> Result<ethereum_types::U256, D::Error> {
144    let s = String::deserialize(deserializer)?;
145    s.strip_prefix("0x")
146        // `from_str_radix` checks the digits and the size, but accepts leading zeros, a second
147        // prefix and no digits at all.
148        .filter(|digits| *digits == "0" || digits.starts_with(|c| c != '0'))
149        .and_then(|digits| ethereum_types::U256::from_str_radix(digits, 16).ok())
150        .ok_or_else(|| {
151            serde::de::Error::invalid_value(
152                serde::de::Unexpected::Str(&s),
153                &"a 0x-prefixed unsigned quantity of at most 256 bits with no leading zeros",
154            )
155        })
156}
157
158impl From<BigInt> for EthBigInt {
159    fn from(value: BigInt) -> Self {
160        (&value).into()
161    }
162}
163
164impl From<&BigInt> for EthBigInt {
165    fn from(value: &BigInt) -> Self {
166        // Eth values are non-negative, so the sign is dropped.
167        let (_sign, bytes) = value.to_bytes_be();
168        // Eth quantities are at most 256 bits; saturate so reporting a wider value never fails.
169        if bytes.len() > 32 {
170            return Self(ethereum_types::U256::MAX);
171        }
172        Self(ethereum_types::U256::from_big_endian(&bytes))
173    }
174}
175
176impl From<u64> for EthBigInt {
177    fn from(value: u64) -> Self {
178        Self(value.into())
179    }
180}
181
182impl From<TokenAmount> for EthBigInt {
183    fn from(amount: TokenAmount) -> Self {
184        (&amount).into()
185    }
186}
187
188impl From<&TokenAmount> for EthBigInt {
189    fn from(amount: &TokenAmount) -> Self {
190        amount.atto().into()
191    }
192}
193
194impl From<EthBigInt> for BigInt {
195    fn from(value: EthBigInt) -> Self {
196        // Eth values are non-negative, so the sign is always positive.
197        BigInt::from_bytes_be(num_bigint::Sign::Plus, &value.to_big_endian())
198    }
199}
200
201impl From<EthBigInt> for TokenAmount {
202    fn from(value: EthBigInt) -> Self {
203        TokenAmount::from_atto(value)
204    }
205}
206
207type GasPriceResult = EthBigInt;
208
209#[derive(PartialEq, Debug, Deserialize, Serialize, Default, Clone, JsonSchema, GetSize)]
210pub struct Nonce(
211    #[schemars(with = "String")]
212    #[serde(with = "crate::lotus_json::hexify_bytes")]
213    #[get_size(ignore)]
214    pub ethereum_types::H64,
215);
216lotus_json_with_self!(Nonce);
217
218#[derive(
219    Eq,
220    Hash,
221    PartialEq,
222    Debug,
223    Deserialize,
224    Serialize,
225    Default,
226    Clone,
227    Copy,
228    JsonSchema,
229    derive_more::From,
230    derive_more::Into,
231    derive_more::Deref,
232    GetSize,
233)]
234pub struct EthUint64(
235    #[schemars(with = "String")]
236    #[serde(with = "crate::lotus_json::hexify")]
237    pub u64,
238);
239
240lotus_json_with_self!(EthUint64);
241
242impl EthUint64 {
243    pub fn from_bytes(data: &[u8]) -> Result<Self> {
244        if data.len() != EVM_WORD_LENGTH {
245            bail!("eth int must be {EVM_WORD_LENGTH} bytes");
246        }
247
248        // big endian format stores u64 in the last 8 bytes,
249        // since ethereum words are 32 bytes, the first 24 bytes must be 0
250        if data
251            .get(..24)
252            .is_none_or(|slice| slice.iter().any(|&byte| byte != 0))
253        {
254            bail!("eth int overflows 64 bits");
255        }
256
257        // Extract the uint64 from the last 8 bytes
258        Ok(Self(u64::from_be_bytes(
259            data.get(24..EVM_WORD_LENGTH)
260                .ok_or_else(|| anyhow::anyhow!("data too short"))?
261                .try_into()?,
262        )))
263    }
264
265    pub fn to_hex_string(self) -> String {
266        hex::encode_prefixed(self.0.to_be_bytes())
267    }
268}
269
270#[derive(
271    PartialEq,
272    Debug,
273    Deserialize,
274    Serialize,
275    Default,
276    Clone,
277    Copy,
278    JsonSchema,
279    derive_more::From,
280    derive_more::Into,
281    derive_more::Deref,
282    GetSize,
283)]
284pub struct EthInt64(
285    #[schemars(with = "String")]
286    #[serde(with = "crate::lotus_json::hexify")]
287    pub i64,
288);
289
290lotus_json_with_self!(EthInt64);
291
292impl EthHash {
293    // Should ONLY be used for blocks and Filecoin messages. Eth transactions expect a different hashing scheme.
294    pub fn to_cid(self) -> cid::Cid {
295        let mh = MultihashCode::Blake2b256
296            .wrap(self.0.as_bytes())
297            .expect("should not fail");
298        Cid::new_v1(DAG_CBOR, mh)
299    }
300
301    pub fn empty_uncles() -> Self {
302        Self(
303            ethereum_types::H256::from_str(EMPTY_UNCLES)
304                .expect("EMPTY_UNCLES is a valid hardcoded H256 hex literal"),
305        )
306    }
307
308    pub fn empty_root() -> Self {
309        Self(
310            ethereum_types::H256::from_str(EMPTY_ROOT)
311                .expect("EMPTY_ROOT is a valid hardcoded H256 hex literal"),
312        )
313    }
314}
315
316impl From<Cid> for EthHash {
317    fn from(cid: Cid) -> Self {
318        let (_, digest, _) = cid.hash().into_inner();
319        EthHash(ethereum_types::H256::from_slice(&digest[0..32]))
320    }
321}
322
323impl From<[u8; EVM_WORD_LENGTH]> for EthHash {
324    fn from(value: [u8; EVM_WORD_LENGTH]) -> Self {
325        Self(ethereum_types::H256(value))
326    }
327}
328
329#[derive(
330    PartialEq,
331    Debug,
332    Clone,
333    Copy,
334    Serialize,
335    Deserialize,
336    Default,
337    JsonSchema,
338    strum::Display,
339    strum::EnumString,
340)]
341#[strum(serialize_all = "lowercase")]
342#[serde(rename_all = "lowercase")]
343pub enum Predefined {
344    Earliest,
345    Pending,
346    #[default]
347    Latest,
348    Safe,
349    Finalized,
350}
351
352#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema)]
353#[serde(rename_all = "camelCase")]
354pub struct BlockNumber {
355    block_number: EthInt64,
356}
357
358#[derive(PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema)]
359#[serde(rename_all = "camelCase")]
360pub struct BlockHash {
361    block_hash: EthHash,
362    #[serde(default)]
363    require_canonical: bool,
364}
365
366#[derive(
367    PartialEq, Debug, Clone, Serialize, Deserialize, JsonSchema, strum::Display, derive_more::From,
368)]
369#[serde(untagged)]
370pub enum BlockNumberOrHash {
371    #[schemars(with = "String")]
372    PredefinedBlock(Predefined),
373    BlockNumber(EthInt64),
374    BlockHash(EthHash),
375    BlockNumberObject(BlockNumber),
376    BlockHashObject(BlockHash),
377}
378lotus_json_with_self!(BlockNumberOrHash);
379
380impl BlockNumberOrHash {
381    pub fn from_block_number(number: i64) -> Self {
382        Self::BlockNumber(EthInt64(number))
383    }
384
385    /// Construct a block number using EIP-1898 Object scheme.
386    ///
387    /// For details see <https://eips.ethereum.org/EIPS/eip-1898>
388    pub fn from_block_number_object(number: i64) -> Self {
389        Self::BlockNumberObject(BlockNumber {
390            block_number: EthInt64(number),
391        })
392    }
393
394    /// Construct a block hash using EIP-1898 Object scheme.
395    ///
396    /// For details see <https://eips.ethereum.org/EIPS/eip-1898>
397    pub fn from_block_hash_object(hash: EthHash, require_canonical: bool) -> Self {
398        Self::BlockHashObject(BlockHash {
399            block_hash: hash,
400            require_canonical,
401        })
402    }
403
404    pub fn from_str(s: &str) -> Result<Self, Error> {
405        if s.starts_with("0x") {
406            let epoch = hex_str_to_epoch(s)?;
407            return Ok(BlockNumberOrHash::from_block_number(epoch));
408        }
409        s.parse::<Predefined>()
410            .map_err(|_| anyhow!("Invalid block identifier"))
411            .map(BlockNumberOrHash::from)
412    }
413}
414
415#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, GetSize)]
416#[serde(untagged)] // try a Vec<String>, then a Vec<Tx>
417pub enum Transactions {
418    Hash(Vec<String>),
419    Full(Vec<ApiEthTx>),
420}
421
422impl Transactions {
423    pub fn is_empty(&self) -> bool {
424        match self {
425            Self::Hash(v) => v.is_empty(),
426            Self::Full(v) => v.is_empty(),
427        }
428    }
429}
430
431impl PartialEq for Transactions {
432    fn eq(&self, other: &Self) -> bool {
433        match (self, other) {
434            (Self::Hash(a), Self::Hash(b)) => a == b,
435            (Self::Full(a), Self::Full(b)) => a == b,
436            _ => self.is_empty() && other.is_empty(),
437        }
438    }
439}
440
441impl Default for Transactions {
442    fn default() -> Self {
443        Self::Hash(vec![])
444    }
445}
446
447#[derive(PartialEq, Debug, Clone, Default, Serialize, Deserialize, JsonSchema, GetSize)]
448#[serde(rename_all = "camelCase")]
449pub struct Block {
450    pub hash: EthHash,
451    pub parent_hash: EthHash,
452    pub sha3_uncles: EthHash,
453    pub miner: EthAddress,
454    pub state_root: EthHash,
455    pub transactions_root: EthHash,
456    pub receipts_root: EthHash,
457    pub logs_bloom: Bloom,
458    pub difficulty: EthUint64,
459    pub total_difficulty: EthUint64,
460    pub number: EthInt64,
461    pub gas_limit: EthUint64,
462    pub gas_used: EthUint64,
463    pub timestamp: EthUint64,
464    pub extra_data: EthBytes,
465    pub mix_hash: EthHash,
466    pub nonce: Nonce,
467    pub base_fee_per_gas: EthBigInt,
468    pub size: EthUint64,
469    // can be Vec<Tx> or Vec<String> depending on query params
470    pub transactions: Transactions,
471    pub uncles: Vec<EthHash>,
472}
473
474/// Specifies the level of detail for transactions in Ethereum blocks.
475#[derive(Debug, Clone, Copy, PartialEq, Eq)]
476pub enum TxInfo {
477    /// Return only transaction hashes
478    Hash,
479    /// Return full transaction objects
480    Full,
481}
482
483impl From<bool> for TxInfo {
484    fn from(full: bool) -> Self {
485        if full { TxInfo::Full } else { TxInfo::Hash }
486    }
487}
488
489impl Block {
490    pub fn new(has_transactions: bool, tipset_len: usize) -> Self {
491        Self {
492            gas_limit: EthUint64(BLOCK_GAS_LIMIT.saturating_mul(tipset_len as _)),
493            logs_bloom: Bloom(ethereum_types::Bloom(FULL_BLOOM)),
494            sha3_uncles: EthHash::empty_uncles(),
495            transactions_root: if has_transactions {
496                EthHash::default()
497            } else {
498                EthHash::empty_root()
499            },
500            ..Default::default()
501        }
502    }
503
504    /// Creates a new Ethereum block from a Filecoin tipset, executing transactions if requested.
505    ///
506    /// Reference: <https://github.com/filecoin-project/lotus/blob/941455f1d23e73b9ee92a1a4ce745d8848969858/node/impl/eth/utils.go#L44>
507    pub async fn from_filecoin_tipset(
508        state_manager: &StateManager,
509        tipset: crate::blocks::Tipset,
510        tx_info: TxInfo,
511    ) -> Result<Arc<Self>> {
512        static ETH_BLOCK_HASH_TX_CACHE: LazyLock<SizeTrackingCache<CidWrapper, Arc<Block>>> =
513            LazyLock::new(|| {
514                SizeTrackingCache::new_with_metrics("eth_block_hash_tx", Block::block_cache_size())
515            });
516
517        match tx_info {
518            TxInfo::Full => Self::from_filecoin_tipset_with_full_tx(state_manager, tipset).await,
519            TxInfo::Hash => {
520                let block_cid = tipset.key().cid()?;
521                ETH_BLOCK_HASH_TX_CACHE
522                    .get_or_insert_async(&CidWrapper::from(block_cid), async move {
523                        let block_with_full_tx =
524                            Self::from_filecoin_tipset_with_full_tx(state_manager, tipset).await?;
525                        Ok(Arc::new(
526                            Arc::unwrap_or_clone(block_with_full_tx)
527                                .downcast_full_transaction_to_hash(),
528                        ))
529                    })
530                    .await
531            }
532        }
533    }
534
535    async fn from_filecoin_tipset_with_full_tx(
536        state_manager: &StateManager,
537        tipset: crate::blocks::Tipset,
538    ) -> Result<Arc<Self>> {
539        static ETH_BLOCK_FULL_TX_CACHE: LazyLock<SizeTrackingCache<CidWrapper, Arc<Block>>> =
540            LazyLock::new(|| {
541                SizeTrackingCache::new_with_metrics("eth_block_full_tx", Block::block_cache_size())
542            });
543
544        let block_cid = tipset.key().cid()?;
545        ETH_BLOCK_FULL_TX_CACHE
546            .get_or_insert_async(&CidWrapper::from(block_cid), async move {
547                let parent_cid = tipset.parents().cid()?;
548                let block_number = EthInt64(tipset.epoch());
549                let block_hash: EthHash = block_cid.into();
550
551                let ExecutedTipset {
552                    state_root,
553                    executed_messages,
554                    ..
555                } = state_manager.load_executed_tipset_for_rpc(&tipset).await?;
556                let has_transactions = !executed_messages.is_empty();
557                let state_tree = state_manager.get_state_tree(&state_root)?;
558
559                let mut full_transactions = vec![];
560                let mut gas_used = 0;
561                for (
562                    i,
563                    ExecutedMessage {
564                        message, receipt, ..
565                    },
566                ) in executed_messages.iter().enumerate()
567                {
568                    let ti = EthUint64(i as u64);
569                    gas_used += receipt.gas_used();
570                    let mut tx = match message {
571                        ChainMessage::Signed(smsg) => new_eth_tx_from_signed_message(
572                            smsg,
573                            &state_tree,
574                            state_manager.chain_config().eth_chain_id,
575                        )?,
576                        ChainMessage::Unsigned(msg) => {
577                            let tx = eth_tx_from_native_message(
578                                msg,
579                                &state_tree,
580                                state_manager.chain_config().eth_chain_id,
581                            )?;
582                            ApiEthTx {
583                                hash: msg.cid().into(),
584                                ..tx
585                            }
586                        }
587                    };
588                    tx.block_hash = block_hash;
589                    tx.block_number = block_number;
590                    tx.transaction_index = ti;
591                    full_transactions.push(tx);
592                }
593
594                let logs_bloom =
595                    block_logs_bloom(state_manager, &tipset, &state_root, &executed_messages)?;
596
597                Ok(Arc::new(Block {
598                    hash: block_hash,
599                    number: block_number,
600                    parent_hash: parent_cid.into(),
601                    timestamp: EthUint64(tipset.block_headers().first().timestamp),
602                    base_fee_per_gas: tipset
603                        .block_headers()
604                        .first()
605                        .parent_base_fee
606                        .clone()
607                        .into(),
608                    gas_used: EthUint64(gas_used),
609                    transactions: Transactions::Full(full_transactions),
610                    logs_bloom,
611                    ..Block::new(has_transactions, tipset.len())
612                }))
613            })
614            .await
615    }
616
617    fn block_cache_size() -> NonZeroUsize {
618        const DEFAULT_CACHE_SIZE: NonZeroUsize = nonzero!(500usize);
619        static CACHE_SIZE: std::sync::LazyLock<NonZeroUsize> = std::sync::LazyLock::new(|| {
620            std::env::var("FOREST_ETH_BLOCK_CACHE_SIZE")
621                .ok()
622                .and_then(|s| s.parse().ok())
623                .unwrap_or(DEFAULT_CACHE_SIZE)
624        });
625        *CACHE_SIZE
626    }
627
628    fn downcast_full_transaction_to_hash(mut self) -> Self {
629        if let Transactions::Full(transactions) = &self.transactions {
630            self.transactions =
631                Transactions::Hash(transactions.iter().map(|tx| tx.hash.to_string()).collect())
632        }
633        self
634    }
635}
636
637lotus_json_with_self!(Block);
638
639#[derive(PartialEq, Debug, Clone, Default, Serialize, Deserialize, JsonSchema, GetSize)]
640#[serde(rename_all = "camelCase")]
641pub struct ApiEthTx {
642    pub chain_id: EthUint64,
643    pub nonce: EthUint64,
644    pub hash: EthHash,
645    pub block_hash: EthHash,
646    pub block_number: EthInt64,
647    pub transaction_index: EthUint64,
648    pub from: EthAddress,
649    // No `skip_serializing_if` (unlike the other `Option` fields): contract-creation txs must
650    // emit `"to": null` rather than drop the key.
651    #[serde(default)]
652    pub to: Option<EthAddress>,
653    pub value: EthBigInt,
654    pub r#type: EthUint64,
655    pub input: EthBytes,
656    pub gas: EthUint64,
657    #[serde(skip_serializing_if = "Option::is_none", default)]
658    pub max_fee_per_gas: Option<EthBigInt>,
659    #[serde(skip_serializing_if = "Option::is_none", default)]
660    pub max_priority_fee_per_gas: Option<EthBigInt>,
661    #[serde(skip_serializing_if = "Option::is_none", default)]
662    pub gas_price: Option<EthBigInt>,
663    #[schemars(with = "Vec<EthHash>")]
664    #[serde(
665        default,
666        skip_serializing_if = "Option::is_none",
667        serialize_with = "crate::lotus_json::serialize",
668        deserialize_with = "crate::lotus_json::deserialize_empty_not_null_opt"
669    )]
670    pub access_list: Option<NotNullVec<EthHash>>,
671    pub v: EthBigInt,
672    pub r: EthBigInt,
673    pub s: EthBigInt,
674}
675lotus_json_with_self!(ApiEthTx);
676
677impl ApiEthTx {
678    fn gas_fee_cap(&self) -> anyhow::Result<EthBigInt> {
679        self.max_fee_per_gas
680            .as_ref()
681            .or(self.gas_price.as_ref())
682            .cloned()
683            .context("gas fee cap is not set")
684    }
685
686    fn gas_premium(&self) -> anyhow::Result<EthBigInt> {
687        self.max_priority_fee_per_gas
688            .as_ref()
689            .or(self.gas_price.as_ref())
690            .cloned()
691            .context("gas premium is not set")
692    }
693}
694
695#[derive(Debug, Clone, Default, PartialEq, Eq)]
696pub struct EthSyncingResult {
697    pub done_sync: bool,
698    pub starting_block: i64,
699    pub current_block: i64,
700    pub highest_block: i64,
701}
702
703#[derive(Debug, PartialEq, Clone, Serialize, Deserialize, JsonSchema)]
704#[serde(untagged)]
705pub enum EthSyncingResultLotusJson {
706    DoneSync(bool),
707    Syncing {
708        #[schemars(with = "i64")]
709        #[serde(rename = "startingBlock", with = "crate::lotus_json::hexify")]
710        starting_block: i64,
711        #[schemars(with = "i64")]
712        #[serde(rename = "currentBlock", with = "crate::lotus_json::hexify")]
713        current_block: i64,
714        #[schemars(with = "i64")]
715        #[serde(rename = "highestBlock", with = "crate::lotus_json::hexify")]
716        highest_block: i64,
717    },
718}
719
720// TODO(forest): https://github.com/ChainSafe/forest/issues/4032
721//               this shouldn't exist
722impl HasLotusJson for EthSyncingResult {
723    type LotusJson = EthSyncingResultLotusJson;
724
725    #[cfg(test)]
726    fn snapshots() -> Vec<(serde_json::Value, Self)> {
727        vec![]
728    }
729
730    fn into_lotus_json(self) -> Self::LotusJson {
731        match self {
732            Self {
733                done_sync: false,
734                starting_block,
735                current_block,
736                highest_block,
737            } => EthSyncingResultLotusJson::Syncing {
738                starting_block,
739                current_block,
740                highest_block,
741            },
742            _ => EthSyncingResultLotusJson::DoneSync(false),
743        }
744    }
745
746    fn from_lotus_json(lotus_json: Self::LotusJson) -> Self {
747        match lotus_json {
748            EthSyncingResultLotusJson::DoneSync(syncing) => {
749                if syncing {
750                    // Dangerous to panic here, log error instead.
751                    tracing::error!("Invalid EthSyncingResultLotusJson: {syncing}");
752                }
753                Self {
754                    done_sync: true,
755                    ..Default::default()
756                }
757            }
758            EthSyncingResultLotusJson::Syncing {
759                starting_block,
760                current_block,
761                highest_block,
762            } => Self {
763                done_sync: false,
764                starting_block,
765                current_block,
766                highest_block,
767            },
768        }
769    }
770}
771
772#[derive(PartialEq, Debug, Default, Clone, Serialize, Deserialize, JsonSchema, GetSize)]
773#[serde(rename_all = "camelCase")]
774pub struct EthTxReceipt {
775    transaction_hash: EthHash,
776    transaction_index: EthUint64,
777    block_hash: EthHash,
778    block_number: EthInt64,
779    from: EthAddress,
780    to: Option<EthAddress>,
781    root: EthHash,
782    status: EthUint64,
783    contract_address: Option<EthAddress>,
784    cumulative_gas_used: EthUint64,
785    gas_used: EthUint64,
786    effective_gas_price: EthBigInt,
787    logs_bloom: EthBytes,
788    logs: Vec<EthLog>,
789    r#type: EthUint64,
790}
791lotus_json_with_self!(EthTxReceipt);
792
793impl EthTxReceipt {
794    fn new() -> Self {
795        Self {
796            logs_bloom: EthBytes(EMPTY_BLOOM.to_vec()),
797            ..Self::default()
798        }
799    }
800}
801
802/// Represents the results of an event filter execution.
803#[derive(PartialEq, Debug, Default, Clone, Serialize, Deserialize, JsonSchema, GetSize)]
804#[serde(rename_all = "camelCase")]
805pub struct EthLog {
806    /// The address of the actor that produced the event log.
807    address: EthAddress,
808    /// The value of the event log, excluding topics.
809    data: EthBytes,
810    /// List of topics associated with the event log.
811    topics: Vec<EthHash>,
812    /// Indicates whether the log was removed due to a chain reorganization.
813    removed: bool,
814    /// The index of the event log in the sequence of events produced by the message execution.
815    /// (this is the index in the events AMT on the message receipt)
816    log_index: EthUint64,
817    /// The index in the tipset of the transaction that produced the event log.
818    /// The index corresponds to the sequence of messages produced by `ChainGetParentMessages`
819    transaction_index: EthUint64,
820    /// The hash of the RLP message that produced the event log.
821    transaction_hash: EthHash,
822    /// The hash of the tipset containing the message that produced the log.
823    block_hash: EthHash,
824    /// The epoch of the tipset containing the message.
825    block_number: EthUint64,
826}
827lotus_json_with_self!(EthLog);
828
829pub enum Web3ClientVersion {}
830impl RpcMethod<0> for Web3ClientVersion {
831    const NAME: &'static str = "Filecoin.Web3ClientVersion";
832    const NAME_ALIAS: Option<&'static str> = Some("web3_clientVersion");
833    const PARAM_NAMES: [&'static str; 0] = [];
834    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
835    const PERMISSION: Permission = Permission::Read;
836    const DESCRIPTION: &'static str = "Returns the client version string of the running node.";
837
838    type Params = ();
839    type Ok = Arc<str>;
840
841    async fn handle(
842        _: Ctx,
843        (): Self::Params,
844        _: &http::Extensions,
845    ) -> Result<Self::Ok, ServerError> {
846        // Version string is baked in at build time; cache once.
847        static CACHED: OnceLock<Arc<str>> = OnceLock::new();
848        Ok(CACHED
849            .get_or_init(|| {
850                Arc::<str>::from(format!(
851                    "forest/{}",
852                    *crate::utils::version::FOREST_VERSION_STRING
853                ))
854            })
855            .clone())
856    }
857}
858
859pub enum EthAccounts {}
860impl RpcMethod<0> for EthAccounts {
861    const NAME: &'static str = "Filecoin.EthAccounts";
862    const NAME_ALIAS: Option<&'static str> = Some("eth_accounts");
863    const PARAM_NAMES: [&'static str; 0] = [];
864    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
865    const PERMISSION: Permission = Permission::Read;
866    const DESCRIPTION: &'static str = "Returns the list of addresses owned by the client; always empty since Forest does not manage private keys.";
867
868    type Params = ();
869    type Ok = NotNullVec<String>;
870
871    async fn handle(
872        _: Ctx,
873        (): Self::Params,
874        _: &http::Extensions,
875    ) -> Result<Self::Ok, ServerError> {
876        // EthAccounts will always return [] since we don't expect Forest to manage private keys
877        Ok(NotNullVec(vec![]))
878    }
879}
880
881pub enum EthBaseFee {}
882
883impl EthBaseFee {
884    fn get_base_fee(ctx: &Ctx, ts: &Tipset) -> anyhow::Result<TokenAmount> {
885        let heights = &ctx.chain_config().height_infos;
886        let smoke_height = heights
887            .get(&Height::Smoke)
888            .context("Missing Smoke height")?
889            .epoch;
890        let firehorse_height = heights
891            .get(&Height::FireHorse)
892            .context("Missing FireHorse height")?
893            .epoch;
894        compute_base_fee(ctx.db(), ts, smoke_height, firehorse_height)
895            .context("failed to compute base fee for eth_baseFee")
896    }
897}
898
899impl RpcMethod<0> for EthBaseFee {
900    const NAME: &'static str = "Filecoin.EthBaseFee";
901    const NAME_ALIAS: Option<&'static str> = Some("eth_baseFee");
902    const PARAM_NAMES: [&'static str; 0] = [];
903    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
904    const PERMISSION: Permission = Permission::Read;
905    const DESCRIPTION: &'static str =
906        "Returns the calculated base fee of the upcoming tipset in attoFIL";
907
908    type Params = ();
909    type Ok = EthBigInt;
910
911    async fn handle(
912        ctx: Ctx,
913        (): Self::Params,
914        _: &http::Extensions,
915    ) -> Result<Self::Ok, ServerError> {
916        let base_fee = Self::get_base_fee(&ctx, &ctx.chain_store().heaviest_tipset())?;
917        Ok(base_fee.atto().into())
918    }
919}
920
921pub enum BaseFeeByHeight {}
922impl RpcMethod<1> for BaseFeeByHeight {
923    const NAME: &'static str = "Forest.BaseFeeByHeight";
924    const NAME_ALIAS: Option<&'static str> = None;
925    const PARAM_NAMES: [&'static str; 1] = ["height"];
926    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
927    const PERMISSION: Permission = Permission::Read;
928    const DESCRIPTION: &'static str =
929        "Returns the calculated upcoming base fee of the tipset at the given height in attoFIL";
930
931    type Params = (ChainEpoch,);
932    type Ok = EthBigInt;
933
934    async fn handle(
935        ctx: Ctx,
936        (height,): Self::Params,
937        _: &http::Extensions,
938    ) -> Result<Self::Ok, ServerError> {
939        let ts = ctx
940            .chain_index()
941            .load_required_tipset_by_height(
942                height,
943                ctx.chain_store().heaviest_tipset(),
944                ResolveNullTipset::TakeOlder,
945            )
946            .await?;
947        let base_fee = EthBaseFee::get_base_fee(&ctx, &ts)?;
948        Ok(base_fee.atto().into())
949    }
950}
951
952pub enum EthBlockNumber {}
953impl RpcMethod<0> for EthBlockNumber {
954    const NAME: &'static str = "Filecoin.EthBlockNumber";
955    const NAME_ALIAS: Option<&'static str> = Some("eth_blockNumber");
956    const PARAM_NAMES: [&'static str; 0] = [];
957    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
958    const PERMISSION: Permission = Permission::Read;
959    const DESCRIPTION: &'static str = "Returns the height of the latest executed tipset, which is the parent of the current head.";
960
961    type Params = ();
962    type Ok = EthUint64;
963
964    async fn handle(
965        ctx: Ctx,
966        (): Self::Params,
967        _: &http::Extensions,
968    ) -> Result<Self::Ok, ServerError> {
969        // `eth_block_number` needs to return the height of the latest committed tipset.
970        // Ethereum clients expect all transactions included in this block to have execution outputs.
971        // This is the parent of the head tipset. The head tipset is speculative, has not been
972        // recognized by the network, and its messages are only included, not executed.
973        // See https://github.com/filecoin-project/ref-fvm/issues/1135.
974        let heaviest = ctx.chain_store().heaviest_tipset();
975        if heaviest.epoch() == 0 {
976            // We're at genesis.
977            return Ok(EthUint64::default());
978        }
979        // First non-null parent.
980        let effective_parent = heaviest.parents();
981        if let Ok(Some(parent)) = ctx.chain_index().load_tipset(effective_parent) {
982            Ok((parent.epoch() as u64).into())
983        } else {
984            Ok(EthUint64::default())
985        }
986    }
987}
988
989pub enum EthChainId {}
990impl RpcMethod<0> for EthChainId {
991    const NAME: &'static str = "Filecoin.EthChainId";
992    const NAME_ALIAS: Option<&'static str> = Some("eth_chainId");
993    const PARAM_NAMES: [&'static str; 0] = [];
994    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
995    const PERMISSION: Permission = Permission::Read;
996    const DESCRIPTION: &'static str = "Returns the EIP-155 chain ID of the current network.";
997
998    type Params = ();
999    type Ok = Arc<str>;
1000
1001    async fn handle(
1002        ctx: Ctx,
1003        (): Self::Params,
1004        _: &http::Extensions,
1005    ) -> Result<Self::Ok, ServerError> {
1006        // `eth_chain_id` is fixed for the process lifetime; cache the hex form.
1007        static CACHED: OnceLock<Arc<str>> = OnceLock::new();
1008        Ok(CACHED
1009            .get_or_init(|| Arc::<str>::from(format!("{:#x}", ctx.chain_config().eth_chain_id)))
1010            .clone())
1011    }
1012}
1013
1014pub enum EthGasPrice {}
1015impl RpcMethod<0> for EthGasPrice {
1016    const NAME: &'static str = "Filecoin.EthGasPrice";
1017    const NAME_ALIAS: Option<&'static str> = Some("eth_gasPrice");
1018    const PARAM_NAMES: [&'static str; 0] = [];
1019    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1020    const PERMISSION: Permission = Permission::Read;
1021    const DESCRIPTION: &'static str = "Returns the current gas price in attoFIL";
1022
1023    type Params = ();
1024    type Ok = GasPriceResult;
1025
1026    async fn handle(
1027        ctx: Ctx,
1028        (): Self::Params,
1029        _: &http::Extensions,
1030    ) -> Result<Self::Ok, ServerError> {
1031        // According to Geth's implementation, eth_gasPrice should return base + tip
1032        // Ref: https://github.com/ethereum/pm/issues/328#issuecomment-853234014
1033        let ts = ctx.chain_store().heaviest_tipset();
1034        let block0 = ts.block_headers().first();
1035        let base_fee = block0.parent_base_fee.atto();
1036        let tip = crate::rpc::gas::estimate_gas_premium(&ctx, 0, &ApiTipsetKey(None))
1037            .await
1038            .map(|gas_premium| gas_premium.atto().to_owned())
1039            .unwrap_or_default();
1040        Ok((base_fee + tip).into())
1041    }
1042}
1043
1044pub enum EthGetBalance {}
1045impl RpcMethod<2> for EthGetBalance {
1046    const NAME: &'static str = "Filecoin.EthGetBalance";
1047    const NAME_ALIAS: Option<&'static str> = Some("eth_getBalance");
1048    const PARAM_NAMES: [&'static str; 2] = ["address", "blockParam"];
1049    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1050    const PERMISSION: Permission = Permission::Read;
1051    const DESCRIPTION: &'static str =
1052        "Returns the balance of an Ethereum address at the specified block state";
1053
1054    type Params = (EthAddress, BlockNumberOrHash);
1055    type Ok = EthBigInt;
1056
1057    async fn handle(
1058        ctx: Ctx,
1059        (address, block_param): Self::Params,
1060        ext: &http::Extensions,
1061    ) -> Result<Self::Ok, ServerError> {
1062        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
1063        let ts = resolver
1064            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::TakeOlder)
1065            .await?;
1066        let balance = eth_get_balance(&ctx, &address, &ts).await?;
1067        Ok(balance)
1068    }
1069}
1070
1071async fn eth_get_balance(ctx: &Ctx, address: &EthAddress, ts: &Tipset) -> Result<EthBigInt> {
1072    let fil_addr = address.to_filecoin_address()?;
1073    let TipsetState { state_root, .. } = ctx.state_manager.load_tipset_state(ts).await?;
1074    let state_tree = ctx.state_manager.get_state_tree(&state_root)?;
1075    match state_tree.get_actor(&fil_addr)? {
1076        Some(actor) => Ok(actor.balance.atto().into()),
1077        None => Ok(EthBigInt::default()), // Balance is 0 if the actor doesn't exist
1078    }
1079}
1080
1081fn get_tipset_from_hash(chain_store: &ChainStore, block_hash: &EthHash) -> anyhow::Result<Tipset> {
1082    let tsk = chain_store.get_required_tipset_key(block_hash)?;
1083    Ok(chain_store.chain_index().load_required_tipset(&tsk)?)
1084}
1085
1086async fn resolve_block_number_tipset(
1087    chain: &ChainStore,
1088    block_number: EthInt64,
1089    resolve: ResolveNullTipset,
1090) -> anyhow::Result<Tipset> {
1091    let head = chain.heaviest_tipset();
1092    let height = ChainEpoch::from(block_number.0);
1093    if height > head.epoch() - 1 {
1094        bail!("requested a future epoch (beyond \"latest\")");
1095    }
1096    chain
1097        .chain_index()
1098        .load_required_tipset_by_height(height, head, resolve)
1099        .await
1100        .map_err(|e| match e {
1101            crate::chain::store::Error::NullRound(epoch) => EthErrors::null_round(epoch).into(),
1102            e => e.into(),
1103        })
1104}
1105
1106async fn resolve_block_hash_tipset(
1107    chain: &ChainStore,
1108    block_hash: &EthHash,
1109    require_canonical: bool,
1110    resolve: ResolveNullTipset,
1111) -> anyhow::Result<Tipset> {
1112    let ts = get_tipset_from_hash(chain, block_hash)?;
1113    // verify that the tipset is in the canonical chain
1114    if require_canonical {
1115        // walk up the current chain (our head) until we reach ts.epoch()
1116        let walk_ts = chain
1117            .chain_index()
1118            .load_required_tipset_by_height(ts.epoch(), chain.heaviest_tipset(), resolve)
1119            .await?;
1120        // verify that it equals the expected tipset
1121        if walk_ts != ts {
1122            bail!("tipset is not canonical");
1123        }
1124    }
1125    Ok(ts)
1126}
1127
1128pub fn is_eth_address(addr: &VmAddress) -> bool {
1129    if addr.protocol() != Protocol::Delegated {
1130        return false;
1131    }
1132    let f4_addr: Result<DelegatedAddress, _> = addr.payload().try_into();
1133
1134    f4_addr.is_ok()
1135}
1136
1137/// `eth_tx_from_signed_eth_message` does NOT populate:
1138/// - `hash`
1139/// - `block_hash`
1140/// - `block_number`
1141/// - `transaction_index`
1142pub fn eth_tx_from_signed_eth_message(
1143    smsg: &SignedMessage,
1144    chain_id: EthChainIdType,
1145) -> Result<(EthAddress, EthTx)> {
1146    // The from address is always an f410f address, never an ID or other address.
1147    let from = smsg.message().from();
1148    if !is_eth_address(&from) {
1149        bail!("sender must be an eth account, was {from}");
1150    }
1151    // This should be impossible to fail as we've already asserted that we have an
1152    // Ethereum Address sender...
1153    let from = EthAddress::from_filecoin_address(&from)?;
1154    let tx = EthTx::from_signed_message(chain_id, smsg)?;
1155    Ok((from, tx))
1156}
1157
1158/// See <https://docs.soliditylang.org/en/latest/abi-spec.html#function-selector-and-argument-encoding>
1159/// for ABI specification
1160fn encode_filecoin_params_as_abi(
1161    method: MethodNum,
1162    codec: u64,
1163    params: &fvm_ipld_encoding::RawBytes,
1164) -> Result<EthBytes> {
1165    let mut buffer: Vec<u8> = vec![0x86, 0x8e, 0x10, 0xc4];
1166    buffer.append(&mut encode_filecoin_returns_as_abi(method, codec, params));
1167    Ok(EthBytes(buffer))
1168}
1169
1170fn encode_filecoin_returns_as_abi(
1171    exit_code: u64,
1172    codec: u64,
1173    data: &fvm_ipld_encoding::RawBytes,
1174) -> Vec<u8> {
1175    encode_as_abi_helper(exit_code, codec, data)
1176}
1177
1178/// Round to the next multiple of `EVM` word length.
1179fn round_up_word(value: usize) -> usize {
1180    value.div_ceil(EVM_WORD_LENGTH) * EVM_WORD_LENGTH
1181}
1182
1183/// Format two numbers followed by an arbitrary byte array as solidity ABI.
1184fn encode_as_abi_helper(param1: u64, param2: u64, data: &[u8]) -> Vec<u8> {
1185    // The first two params are "static" numbers. Then, we record the offset of the "data" arg,
1186    // then, at that offset, we record the length of the data.
1187    //
1188    // In practice, this means we have 4 256-bit words back to back where the third arg (the
1189    // offset) is _always_ '32*3'.
1190    let static_args = [
1191        param1,
1192        param2,
1193        (EVM_WORD_LENGTH * 3) as u64,
1194        data.len() as u64,
1195    ];
1196    let padding = [0u8; 24];
1197    let buf: Vec<u8> = padding
1198        .iter() // Right pad
1199        .chain(static_args[0].to_be_bytes().iter()) // Copy u64
1200        .chain(padding.iter())
1201        .chain(static_args[1].to_be_bytes().iter())
1202        .chain(padding.iter())
1203        .chain(static_args[2].to_be_bytes().iter())
1204        .chain(padding.iter())
1205        .chain(static_args[3].to_be_bytes().iter())
1206        .chain(data.iter()) // Finally, we copy in the data
1207        .chain(std::iter::repeat_n(
1208            &0u8,
1209            round_up_word(data.len()) - data.len(),
1210        )) // Left pad
1211        .cloned()
1212        .collect();
1213
1214    buf
1215}
1216
1217/// Convert a native message to an eth transaction.
1218///
1219///   - The state-tree must be from after the message was applied (ideally the following tipset).
1220///   - In some cases, the "to" address may be `0xff0000000000000000000000ffffffffffffffff`. This
1221///     means that the "to" address has not been assigned in the passed state-tree and can only
1222///     happen if the transaction reverted.
1223///
1224/// `eth_tx_from_native_message` does NOT populate:
1225/// - `hash`
1226/// - `block_hash`
1227/// - `block_number`
1228/// - `transaction_index`
1229fn eth_tx_from_native_message<DB: Blockstore>(
1230    msg: &Message,
1231    state: &StateTree<DB>,
1232    chain_id: EthChainIdType,
1233) -> Result<ApiEthTx> {
1234    // Lookup the from address. This must succeed.
1235    let from = match lookup_eth_address(&msg.from(), state) {
1236        Ok(Some(from)) => from,
1237        _ => bail!(
1238            "failed to lookup sender address {} when converting a native message to an eth txn",
1239            msg.from()
1240        ),
1241    };
1242    // Lookup the to address. If the recipient doesn't exist, we replace the address with a
1243    // known sentinel address.
1244    let mut to = match lookup_eth_address(&msg.to(), state) {
1245        Ok(Some(addr)) => Some(addr),
1246        Ok(None) => Some(EthAddress(
1247            ethereum_types::H160::from_str(REVERTED_ETH_ADDRESS)
1248                .expect("REVERTED_ETH_ADDRESS is a valid hardcoded H160 hex literal"),
1249        )),
1250        Err(err) => {
1251            bail!(err)
1252        }
1253    };
1254
1255    // Finally, convert the input parameters to "solidity ABI".
1256
1257    // For empty, we use "0" as the codec. Otherwise, we use CBOR for message
1258    // parameters.
1259    let codec = if !msg.params().is_empty() { CBOR } else { 0 };
1260
1261    // We try to decode the input as an EVM method invocation and/or a contract creation. If
1262    // that fails, we encode the "native" parameters as Solidity ABI.
1263    let input = 'decode: {
1264        if (msg.method_num() == EVMMethod::InvokeContract as MethodNum
1265            || msg.method_num() == EAMMethod::CreateExternal as MethodNum)
1266            && let Ok(buffer) = decode_payload(msg.params(), codec)
1267        {
1268            // If this is a valid "create external", unset the "to" address.
1269            if msg.method_num() == EAMMethod::CreateExternal as MethodNum {
1270                to = None;
1271            }
1272            break 'decode buffer;
1273        }
1274        // Yeah, we're going to ignore errors here because the user can send whatever they
1275        // want and may send garbage.
1276        encode_filecoin_params_as_abi(msg.method_num(), codec, msg.params())?
1277    };
1278
1279    Ok(ApiEthTx {
1280        to,
1281        from,
1282        input,
1283        nonce: EthUint64(msg.sequence()),
1284        chain_id: EthUint64(chain_id),
1285        value: msg.value().into(),
1286        r#type: EthUint64(EIP_1559_TX_TYPE.into()),
1287        gas: EthUint64(msg.gas_limit()),
1288        max_fee_per_gas: Some(msg.gas_fee_cap().into()),
1289        max_priority_fee_per_gas: Some(msg.gas_premium().into()),
1290        access_list: Some(NotNullVec(vec![])),
1291        ..ApiEthTx::default()
1292    })
1293}
1294
1295pub fn new_eth_tx_from_signed_message<DB: Blockstore>(
1296    smsg: &SignedMessage,
1297    state: &StateTree<DB>,
1298    chain_id: EthChainIdType,
1299) -> Result<ApiEthTx> {
1300    let (tx, hash) = if smsg.is_delegated() {
1301        // This is an eth tx
1302        let (from, tx) = eth_tx_from_signed_eth_message(smsg, chain_id)?;
1303        let hash = tx.eth_hash()?.into();
1304        let tx = ApiEthTx { from, ..tx.into() };
1305        (tx, hash)
1306    } else if smsg.is_secp256k1() {
1307        // Secp Filecoin Message
1308        let tx = eth_tx_from_native_message(smsg.message(), state, chain_id)?;
1309        (tx, smsg.cid().into())
1310    } else {
1311        // BLS Filecoin message
1312        let tx = eth_tx_from_native_message(smsg.message(), state, chain_id)?;
1313        (tx, smsg.message().cid().into())
1314    };
1315    Ok(ApiEthTx { hash, ..tx })
1316}
1317
1318/// Creates an Ethereum transaction from Filecoin message lookup. If `None` is passed for `tx_index`,
1319/// it looks up the transaction index of the message in the tipset.
1320/// Otherwise, it uses some index passed into the function.
1321fn new_eth_tx_from_message_lookup(
1322    ctx: &Ctx,
1323    message_lookup: &MessageLookup,
1324    tx_index: Option<u64>,
1325) -> Result<ApiEthTx> {
1326    let ts = ctx
1327        .chain_store()
1328        .load_required_tipset_or_heaviest(&message_lookup.tipset)?;
1329
1330    // This transaction is located in the parent tipset
1331    let parent_ts = ctx
1332        .chain_store()
1333        .load_required_tipset_or_heaviest(ts.parents())?;
1334
1335    let parent_ts_cid = parent_ts.key().cid()?;
1336
1337    // Lookup the transaction index
1338    let tx_index = tx_index.map_or_else(
1339        || {
1340            let msgs = ctx.chain_store().messages_for_tipset(&parent_ts)?;
1341            msgs.iter()
1342                .position(|msg| msg.cid() == message_lookup.message)
1343                .context("cannot find the msg in the tipset")
1344                .map(|i| i as u64)
1345        },
1346        Ok,
1347    )?;
1348
1349    let smsg = get_signed_message(ctx, message_lookup.message)?;
1350
1351    let state = ctx.state_manager.get_state_tree(ts.parent_state())?;
1352
1353    Ok(ApiEthTx {
1354        block_hash: parent_ts_cid.into(),
1355        block_number: parent_ts.epoch().into(),
1356        transaction_index: tx_index.into(),
1357        ..new_eth_tx_from_signed_message(&smsg, &state, ctx.chain_config().eth_chain_id)?
1358    })
1359}
1360
1361fn new_eth_tx(
1362    ctx: &Ctx,
1363    state: &StateTree<DbImpl>,
1364    block_height: ChainEpoch,
1365    msg_tipset_cid: &Cid,
1366    msg_cid: &Cid,
1367    tx_index: u64,
1368) -> Result<ApiEthTx> {
1369    let smsg = get_signed_message(ctx, *msg_cid)?;
1370    let tx = new_eth_tx_from_signed_message(&smsg, state, ctx.chain_config().eth_chain_id)?;
1371
1372    Ok(ApiEthTx {
1373        block_hash: (*msg_tipset_cid).into(),
1374        block_number: block_height.into(),
1375        transaction_index: tx_index.into(),
1376        ..tx
1377    })
1378}
1379
1380fn new_eth_tx_receipt(
1381    tipset: &Tipset,
1382    tx: &ApiEthTx,
1383    msg_receipt: &Receipt,
1384    logs: Vec<EthLog>,
1385) -> anyhow::Result<EthTxReceipt> {
1386    let mut tx_receipt = EthTxReceipt {
1387        transaction_hash: tx.hash,
1388        from: tx.from,
1389        to: tx.to,
1390        transaction_index: tx.transaction_index,
1391        block_hash: tx.block_hash,
1392        block_number: tx.block_number,
1393        r#type: tx.r#type,
1394        status: (u64::from(msg_receipt.exit_code().is_success())).into(),
1395        gas_used: msg_receipt.gas_used().into(),
1396        ..EthTxReceipt::new()
1397    };
1398
1399    tx_receipt.cumulative_gas_used = EthUint64::default();
1400
1401    let gas_fee_cap = tx.gas_fee_cap()?;
1402    let gas_premium = tx.gas_premium()?;
1403
1404    let gas_outputs = GasOutputs::compute(
1405        msg_receipt.gas_used(),
1406        tx.gas.into(),
1407        &tipset.block_headers().first().parent_base_fee,
1408        &gas_fee_cap.into(),
1409        &gas_premium.into(),
1410    );
1411    let total_spent: BigInt = gas_outputs.total_spent().into();
1412
1413    let mut effective_gas_price = EthBigInt::default();
1414    if msg_receipt.gas_used() > 0 {
1415        effective_gas_price = (total_spent / msg_receipt.gas_used()).into();
1416    }
1417    tx_receipt.effective_gas_price = effective_gas_price;
1418
1419    if tx_receipt.to.is_none() && msg_receipt.exit_code().is_success() {
1420        // Create and Create2 return the same things.
1421        let ret: eam::CreateExternalReturn =
1422            from_slice_with_fallback(msg_receipt.return_data().bytes())?;
1423
1424        tx_receipt.contract_address = Some(ret.eth_address.0.into());
1425    }
1426
1427    tx_receipt.logs = logs;
1428
1429    let mut bloom = Bloom::default();
1430    for log in tx_receipt.logs.iter() {
1431        accrue_eth_log(&mut bloom, &log.address, &log.topics);
1432    }
1433    tx_receipt.logs_bloom = bloom.into();
1434
1435    Ok(tx_receipt)
1436}
1437
1438pub async fn eth_logs_for_block_and_transaction(
1439    ctx: &Ctx,
1440    ts: &Tipset,
1441    block_hash: &EthHash,
1442    msg_cid: &Cid,
1443) -> anyhow::Result<Vec<EthLog>> {
1444    // Refuse to serve events for tipsets at or after head (deferred execution).
1445    let heaviest_epoch = ctx.chain_store().heaviest_tipset().epoch();
1446    if ts.epoch() >= heaviest_epoch {
1447        return Err(EthErrors::EventsNotYetAvailable.into());
1448    }
1449
1450    let parsed_filter = ParsedFilter::new_with_tipset_and_msg(
1451        ParsedFilterTipsets::Hash(*block_hash),
1452        Some(*msg_cid),
1453    );
1454    let mut events = vec![];
1455    EthEventHandler::collect_events(
1456        &ctx.state_manager,
1457        ts,
1458        None,
1459        Some(&parsed_filter),
1460        SkipEvent::OnUnresolvedAddress,
1461        &mut events,
1462    )
1463    .await?;
1464    eth_filter_logs_from_events(ctx, &events)
1465}
1466
1467/// Collects all Ethereum logs produced by a tipset's already-executed messages, in tipset order.
1468fn collect_block_logs(
1469    ctx: &Ctx,
1470    tipset: &Tipset,
1471    executed_tipset: &ExecutedTipset,
1472    revert_status: EventRevertStatus,
1473) -> anyhow::Result<Vec<EthLog>> {
1474    let mut events = vec![];
1475    EthEventHandler::collect_events_from_messages(
1476        &ctx.state_manager,
1477        tipset,
1478        executed_tipset,
1479        None::<&ParsedFilter>,
1480        SkipEvent::OnUnresolvedAddress,
1481        revert_status,
1482        &mut events,
1483    )?;
1484    eth_filter_logs_from_events(ctx, &events)
1485}
1486
1487/// Collects the logs produced by a single chain head change, for the logs
1488/// subscription.
1489pub(in crate::rpc) async fn eth_logs_for_head_change(
1490    ctx: &Ctx,
1491    change: &PathChange<Tipset>,
1492) -> anyhow::Result<Vec<EthLog>> {
1493    let (receipt_ts, revert_status) = match change {
1494        PathChange::Revert(ts) => (ts, EventRevertStatus::Reverted),
1495        PathChange::Apply(ts) => (ts, EventRevertStatus::Applied),
1496    };
1497    // Genesis carries no events and has no parent message tipset to load.
1498    if receipt_ts.epoch() == 0 {
1499        return Ok(vec![]);
1500    }
1501    let msg_ts = ctx
1502        .chain_index()
1503        .load_required_tipset(receipt_ts.parents())?;
1504    let executed_ts = ctx
1505        .state_manager
1506        .load_executed_tipset_with_receipt(&msg_ts, receipt_ts)
1507        .await?;
1508    collect_block_logs(ctx, &msg_ts, &executed_ts, revert_status)
1509}
1510
1511fn get_signed_message(ctx: &Ctx, message_cid: Cid) -> Result<SignedMessage> {
1512    let result: Result<SignedMessage, crate::chain::Error> =
1513        crate::chain::message_from_cid(ctx.db(), &message_cid);
1514
1515    result.or_else(|_| {
1516        // We couldn't find the signed message, it might be a BLS message, so search for a regular message.
1517        let msg: Message = crate::chain::message_from_cid(ctx.db(), &message_cid)
1518            .with_context(|| format!("failed to find msg {message_cid}"))?;
1519        Ok(SignedMessage::new_unchecked(
1520            msg,
1521            Signature::new_bls(vec![]),
1522        ))
1523    })
1524}
1525
1526pub enum EthGetBlockByHash {}
1527impl RpcMethod<2> for EthGetBlockByHash {
1528    const NAME: &'static str = "Filecoin.EthGetBlockByHash";
1529    const NAME_ALIAS: Option<&'static str> = Some("eth_getBlockByHash");
1530    const PARAM_NAMES: [&'static str; 2] = ["blockHash", "fullTxInfo"];
1531    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1532    const PERMISSION: Permission = Permission::Read;
1533    const DESCRIPTION: &'static str =
1534        "Retrieves a block by its hash, optionally including full transaction objects.";
1535
1536    type Params = (EthHash, bool);
1537    type Ok = Arc<Block>;
1538
1539    async fn handle(
1540        ctx: Ctx,
1541        (block_hash, full_tx_info): Self::Params,
1542        ext: &http::Extensions,
1543    ) -> Result<Self::Ok, ServerError> {
1544        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
1545        let ts = resolver
1546            .tipset_by_block_number_or_hash(block_hash, ResolveNullTipset::TakeOlder)
1547            .await?;
1548        Block::from_filecoin_tipset(&ctx.state_manager, ts, full_tx_info.into())
1549            .await
1550            .map_err(ServerError::from)
1551    }
1552}
1553
1554pub enum EthGetBlockByNumber {}
1555impl RpcMethod<2> for EthGetBlockByNumber {
1556    const NAME: &'static str = "Filecoin.EthGetBlockByNumber";
1557    const NAME_ALIAS: Option<&'static str> = Some("eth_getBlockByNumber");
1558    const PARAM_NAMES: [&'static str; 2] = ["blockParam", "fullTxInfo"];
1559    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1560    const PERMISSION: Permission = Permission::Read;
1561    const DESCRIPTION: &'static str = "Retrieves a block by its number or a special tag.";
1562
1563    type Params = (BlockNumberOrPredefined, bool);
1564    type Ok = Arc<Block>;
1565
1566    async fn handle(
1567        ctx: Ctx,
1568        (block_param, full_tx_info): Self::Params,
1569        ext: &http::Extensions,
1570    ) -> Result<Self::Ok, ServerError> {
1571        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
1572        let ts = resolver
1573            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::Fail)
1574            .await?;
1575        Block::from_filecoin_tipset(&ctx.state_manager, ts, full_tx_info.into())
1576            .await
1577            .map_err(ServerError::from)
1578    }
1579}
1580
1581async fn get_block_receipts(
1582    ctx: &Ctx,
1583    ts: Tipset,
1584    limit: Option<ChainEpoch>,
1585) -> Result<Vec<EthTxReceipt>> {
1586    if let Some(limit) = limit
1587        && limit > LOOKBACK_NO_LIMIT
1588        && ts.epoch() < ctx.chain_store().heaviest_tipset().epoch() - limit
1589    {
1590        bail!(
1591            "tipset {} is older than the allowed lookback limit",
1592            ts.key().format_lotus()
1593        );
1594    }
1595    let ts_ref = Arc::new(ts);
1596    let ts_key = ts_ref.key();
1597
1598    // Execute the tipset to get the messages and receipts
1599    let executed_tipset = ctx
1600        .state_manager
1601        .load_executed_tipset_for_rpc(&ts_ref)
1602        .await?;
1603    let executed_messages = &executed_tipset.executed_messages;
1604
1605    // Load the state tree
1606    let state_tree = ctx
1607        .state_manager
1608        .get_state_tree(&executed_tipset.state_root)?;
1609
1610    // Collect the whole tipset's logs in a single pass and scatter them back to their messages.
1611    let heaviest_epoch = ctx.chain_store().heaviest_tipset().epoch();
1612    if ts_ref.epoch() >= heaviest_epoch
1613        && executed_messages
1614            .iter()
1615            .any(|em| em.receipt.events_root().is_some())
1616    {
1617        return Err(EthErrors::EventsNotYetAvailable.into());
1618    }
1619
1620    let mut logs_by_msg: Vec<Vec<EthLog>> = vec![Vec::new(); executed_messages.len()];
1621    for log in collect_block_logs(ctx, &ts_ref, &executed_tipset, EventRevertStatus::Applied)? {
1622        // `transaction_index` is the message's index in `executed_messages` (this loop's slice), always a valid bucket.
1623        if let Some(bucket) = logs_by_msg.get_mut(log.transaction_index.0 as usize) {
1624            bucket.push(log);
1625        }
1626    }
1627
1628    let block_cid = ts_key.cid()?;
1629    let mut eth_receipts = Vec::with_capacity(executed_messages.len());
1630    for (i, (executed, logs)) in executed_messages.iter().zip(logs_by_msg).enumerate() {
1631        let ExecutedMessage {
1632            message, receipt, ..
1633        } = executed;
1634        let tx = new_eth_tx(
1635            ctx,
1636            &state_tree,
1637            ts_ref.epoch(),
1638            &block_cid,
1639            &message.cid(),
1640            i as u64,
1641        )?;
1642
1643        let receipt = new_eth_tx_receipt(&ts_ref, &tx, receipt, logs)?;
1644        eth_receipts.push(receipt);
1645    }
1646    Ok(eth_receipts)
1647}
1648
1649pub enum EthGetBlockReceipts {}
1650impl RpcMethod<1> for EthGetBlockReceipts {
1651    const NAME: &'static str = "Filecoin.EthGetBlockReceipts";
1652    const NAME_ALIAS: Option<&'static str> = Some("eth_getBlockReceipts");
1653    const PARAM_NAMES: [&'static str; 1] = ["blockParam"];
1654    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1655    const PERMISSION: Permission = Permission::Read;
1656    const DESCRIPTION: &'static str =
1657        "Retrieves all transaction receipts for a block by its number, hash or a special tag.";
1658
1659    type Params = (BlockNumberOrHash,);
1660    type Ok = NotNullVec<EthTxReceipt>;
1661
1662    async fn handle(
1663        ctx: Ctx,
1664        (block_param,): Self::Params,
1665        ext: &http::Extensions,
1666    ) -> Result<Self::Ok, ServerError> {
1667        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
1668        let ts = resolver
1669            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::Fail)
1670            .await?;
1671        get_block_receipts(&ctx, ts, None)
1672            .await
1673            .map(NotNullVec)
1674            .map_err(ServerError::from)
1675    }
1676}
1677
1678pub enum EthGetBlockReceiptsLimited {}
1679impl RpcMethod<2> for EthGetBlockReceiptsLimited {
1680    const NAME: &'static str = "Filecoin.EthGetBlockReceiptsLimited";
1681    const NAME_ALIAS: Option<&'static str> = Some("eth_getBlockReceiptsLimited");
1682    const PARAM_NAMES: [&'static str; 2] = ["blockParam", "limit"];
1683    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1684    const PERMISSION: Permission = Permission::Read;
1685    const DESCRIPTION: &'static str = "Retrieves all transaction receipts for a block identified by its number, hash or a special tag along with an optional limit on the chain epoch for state resolution.";
1686
1687    type Params = (BlockNumberOrHash, ChainEpoch);
1688    type Ok = NotNullVec<EthTxReceipt>;
1689
1690    async fn handle(
1691        ctx: Ctx,
1692        (block_param, limit): Self::Params,
1693        ext: &http::Extensions,
1694    ) -> Result<Self::Ok, ServerError> {
1695        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
1696        let ts = resolver
1697            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::Fail)
1698            .await?;
1699        get_block_receipts(&ctx, ts, Some(limit))
1700            .await
1701            .map(NotNullVec)
1702            .map_err(ServerError::from)
1703    }
1704}
1705
1706pub enum EthGetBlockTransactionCountByHash {}
1707impl RpcMethod<1> for EthGetBlockTransactionCountByHash {
1708    const NAME: &'static str = "Filecoin.EthGetBlockTransactionCountByHash";
1709    const NAME_ALIAS: Option<&'static str> = Some("eth_getBlockTransactionCountByHash");
1710    const PARAM_NAMES: [&'static str; 1] = ["blockHash"];
1711    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1712    const PERMISSION: Permission = Permission::Read;
1713    const DESCRIPTION: &'static str =
1714        "Returns the number of messages in the tipset identified by the given block hash.";
1715
1716    type Params = (EthHash,);
1717    type Ok = EthUint64;
1718
1719    async fn handle(
1720        ctx: Ctx,
1721        (block_hash,): Self::Params,
1722        _: &http::Extensions,
1723    ) -> Result<Self::Ok, ServerError> {
1724        let ts = get_tipset_from_hash(ctx.chain_store(), &block_hash)?;
1725
1726        let head = ctx.chain_store().heaviest_tipset();
1727        if ts.epoch() > head.epoch() {
1728            return Err(anyhow::anyhow!("requested a future epoch (beyond \"latest\")").into());
1729        }
1730        let count = count_messages_in_tipset(ctx.db(), &ts)?;
1731        Ok(EthUint64(count as _))
1732    }
1733}
1734
1735pub enum EthGetBlockTransactionCountByNumber {}
1736impl RpcMethod<1> for EthGetBlockTransactionCountByNumber {
1737    const NAME: &'static str = "Filecoin.EthGetBlockTransactionCountByNumber";
1738    const NAME_ALIAS: Option<&'static str> = Some("eth_getBlockTransactionCountByNumber");
1739    const PARAM_NAMES: [&'static str; 1] = ["blockNumber"];
1740    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1741    const PERMISSION: Permission = Permission::Read;
1742    const DESCRIPTION: &'static str = "Returns the number of transactions in a block identified by its block number or a special tag.";
1743
1744    type Params = (BlockNumberOrPredefined,);
1745    type Ok = EthUint64;
1746
1747    async fn handle(
1748        ctx: Ctx,
1749        (block_number,): Self::Params,
1750        ext: &http::Extensions,
1751    ) -> Result<Self::Ok, ServerError> {
1752        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
1753        let ts = resolver
1754            .tipset_by_block_number_or_hash(block_number, ResolveNullTipset::Fail)
1755            .await?;
1756        let count = count_messages_in_tipset(ctx.db(), &ts)?;
1757        Ok(EthUint64(count as _))
1758    }
1759}
1760
1761pub enum EthGetMessageCidByTransactionHash {}
1762impl RpcMethod<1> for EthGetMessageCidByTransactionHash {
1763    const NAME: &'static str = "Filecoin.EthGetMessageCidByTransactionHash";
1764    const NAME_ALIAS: Option<&'static str> = Some("eth_getMessageCidByTransactionHash");
1765    const PARAM_NAMES: [&'static str; 1] = ["txHash"];
1766    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1767    const PERMISSION: Permission = Permission::Read;
1768    const DESCRIPTION: &'static str = "Returns the CID of the Filecoin message corresponding to the given Ethereum transaction hash.";
1769
1770    type Params = (EthHash,);
1771    type Ok = Option<Cid>;
1772
1773    async fn handle(
1774        ctx: Ctx,
1775        (tx_hash,): Self::Params,
1776        _: &http::Extensions,
1777    ) -> Result<Self::Ok, ServerError> {
1778        let result = ctx.chain_store().get_mapping(&tx_hash);
1779        match result {
1780            Ok(Some(cid)) => return Ok(Some(cid)),
1781            Ok(None) => tracing::debug!("Undefined key {tx_hash}"),
1782            _ => {
1783                result?;
1784            }
1785        }
1786
1787        // This isn't an eth transaction we have the mapping for, so let's try looking it up as a filecoin message
1788        let cid = tx_hash.to_cid();
1789
1790        let result: Result<Vec<SignedMessage>, crate::chain::Error> =
1791            crate::chain::messages_from_cids(ctx.db(), &[cid]);
1792        if result.is_ok() {
1793            // This is an Eth Tx, Secp message, Or BLS message in the mpool
1794            return Ok(Some(cid));
1795        }
1796
1797        let result: Result<Vec<Message>, crate::chain::Error> =
1798            crate::chain::messages_from_cids(ctx.db(), &[cid]);
1799        if result.is_ok() {
1800            // This is a BLS message
1801            return Ok(Some(cid));
1802        }
1803
1804        // Ethereum clients expect an empty response when the message was not found
1805        Ok(None)
1806    }
1807}
1808
1809fn count_messages_in_tipset(store: &impl Blockstore, ts: &Tipset) -> anyhow::Result<usize> {
1810    let mut message_cids = CidHashSet::default();
1811    for block in ts.block_headers() {
1812        let (bls_messages, secp_messages) = crate::chain::store::block_messages(store, block)?;
1813        for m in bls_messages {
1814            message_cids.insert(m.cid());
1815        }
1816        for m in secp_messages {
1817            message_cids.insert(m.cid());
1818        }
1819    }
1820    Ok(message_cids.len())
1821}
1822
1823pub enum EthSyncing {}
1824impl RpcMethod<0> for EthSyncing {
1825    const NAME: &'static str = "Filecoin.EthSyncing";
1826    const NAME_ALIAS: Option<&'static str> = Some("eth_syncing");
1827    const PARAM_NAMES: [&'static str; 0] = [];
1828    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1829    const PERMISSION: Permission = Permission::Read;
1830    const DESCRIPTION: &'static str =
1831        "Returns the node's sync status, or `false` if the node is not currently syncing.";
1832
1833    type Params = ();
1834    type Ok = EthSyncingResult;
1835
1836    async fn handle(
1837        ctx: Ctx,
1838        (): Self::Params,
1839        ext: &http::Extensions,
1840    ) -> Result<Self::Ok, ServerError> {
1841        let sync_status = crate::rpc::sync::SyncStatus::handle(ctx, (), ext).await?;
1842        match sync_status.status {
1843            NodeSyncStatus::Synced => Ok(EthSyncingResult {
1844                done_sync: true,
1845                // Once the node is synced, other fields are not relevant for the API
1846                ..Default::default()
1847            }),
1848            NodeSyncStatus::Syncing => {
1849                let starting_block = match sync_status.get_min_starting_block() {
1850                    Some(e) => Ok(e),
1851                    None => Err(ServerError::internal_error(
1852                        "missing syncing information, try again",
1853                        None,
1854                    )),
1855                }?;
1856
1857                Ok(EthSyncingResult {
1858                    done_sync: sync_status.is_synced(),
1859                    starting_block,
1860                    current_block: sync_status.current_head_epoch,
1861                    highest_block: sync_status.network_head_epoch,
1862                })
1863            }
1864            _ => Err(ServerError::internal_error("node is not syncing", None)),
1865        }
1866    }
1867}
1868
1869pub enum EthEstimateGas {}
1870
1871impl RpcMethod<2> for EthEstimateGas {
1872    const NAME: &'static str = "Filecoin.EthEstimateGas";
1873    const NAME_ALIAS: Option<&'static str> = Some("eth_estimateGas");
1874    const N_REQUIRED_PARAMS: usize = 1;
1875    const PARAM_NAMES: [&'static str; 2] = ["tx", "blockParam"];
1876    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
1877    const PERMISSION: Permission = Permission::Read;
1878    const DESCRIPTION: &'static str =
1879        "Estimates the amount of gas required to execute the given transaction.";
1880
1881    type Params = (EthCallMessage, Option<BlockNumberOrHash>);
1882    type Ok = EthUint64;
1883
1884    async fn handle(
1885        ctx: Ctx,
1886        (tx, block_param): Self::Params,
1887        ext: &http::Extensions,
1888    ) -> Result<Self::Ok, ServerError> {
1889        let price = tx.max_gas_price()?;
1890        let caller_cap = tx.gas_cap().unwrap_or(BLOCK_GAS_LIMIT);
1891        let msg = Message::try_from(tx)?;
1892        let tipset = if let Some(block_param) = block_param {
1893            let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
1894            resolver
1895                .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::TakeOlder)
1896                .await?
1897        } else {
1898            ctx.chain_store().heaviest_tipset()
1899        };
1900        eth_estimate_gas(&ctx, msg, price, caller_cap, tipset).await
1901    }
1902}
1903
1904/// Estimates the gas limit `msg` needs on `tipset`, never above `caller_cap` or, with a `price`,
1905/// the gas the sender can pay for.
1906///
1907/// `msg`'s own gas limit is not used: the measurement runs at the block gas limit.
1908///
1909/// Mirrors Lotus's `EthEstimateGas`:
1910/// <https://github.com/filecoin-project/lotus/blob/v1.38.0/node/impl/eth/gas.go#L193-L307>
1911async fn eth_estimate_gas(
1912    ctx: &Ctx,
1913    msg: Message,
1914    price: Option<TokenAmount>,
1915    caller_cap: u64,
1916    tipset: Tipset,
1917) -> Result<EthUint64, ServerError> {
1918    // The sender as it is after `tipset`'s messages, so one funded in that block counts.
1919    let TipsetState { state_root, .. } = ctx.state_manager.load_tipset_state(&tipset).await?;
1920    let sender = ctx.state_manager.get_actor(&msg.from(), state_root)?;
1921    // An EVM contract fails the FVM's sender check, so it is estimated on the skip-sender path from
1922    // the start; any other sender the check rejects, such as one that does not exist, is retried there.
1923    let sender_validation = match &sender {
1924        Some(actor) if is_evm_actor(&actor.code) => SenderValidation::Skip,
1925        _ => SenderValidation::Enforce,
1926    };
1927    let gas_cap = match price {
1928        Some(price) => {
1929            let balance = sender
1930                .map(|actor| TokenAmount::from(&actor.balance))
1931                .unwrap_or_default();
1932            caller_cap.min(gas_allowance(&balance, msg.value(), &price)?)
1933        }
1934        None => caller_cap,
1935    };
1936
1937    let measure = |sender_validation| {
1938        gas::GasEstimateGasLimit::estimate_gas_limit(ctx, msg.clone(), &tipset, sender_validation)
1939    };
1940    let (sender_validation, measured) = match measure(sender_validation).await {
1941        Err(err) if is_sender_validation_failed(&err) => (
1942            SenderValidation::Skip,
1943            measure(SenderValidation::Skip).await,
1944        ),
1945        result => (sender_validation, result),
1946    };
1947    let gas_used = measured.map_err(|err| estimate_gas_error(err, gas_cap))?;
1948
1949    let gas_limit = (gas_used as f64 * ctx.mpool.gas_limit_overestimation()) as u64;
1950    let msg = msg
1951        .into_builder()
1952        .gas_limit(gas_limit.min(BLOCK_GAS_LIMIT))
1953        .build();
1954    let gas = eth_gas_search(ctx, msg, &tipset, sender_validation, gas_cap).await?;
1955    Ok(gas.into())
1956}
1957
1958/// Maps an estimate that failed at the block gas limit to the error returned to the caller.
1959///
1960/// Out of gas there cannot fit `gas_cap` either, so it is reported against `gas_cap`; typed errors
1961/// keep their JSON-RPC codes, any other error keeps its cause.
1962fn estimate_gas_error(err: anyhow::Error, gas_cap: u64) -> ServerError {
1963    match err.downcast_ref::<EthErrors>() {
1964        Some(EthErrors::OutOfGas) => EthErrors::InsufficientGasLimit { gas_limit: gas_cap }.into(),
1965        Some(_) => err.into(),
1966        None => ServerError::internal_error(format!("failed to estimate gas: {err:#}"), None),
1967    }
1968}
1969
1970/// Returns the gas the sender can pay for at `price` after sending `value`, up to the block gas limit.
1971///
1972/// `price` must be non-zero.
1973///
1974/// # Errors
1975///
1976/// [`EthErrors::InsufficientFunds`] when `balance` is below `value`;
1977/// [`EthErrors::GasRequiredExceedsAllowance`] when the sender affords no gas at all.
1978fn gas_allowance(
1979    balance: &TokenAmount,
1980    value: &TokenAmount,
1981    price: &TokenAmount,
1982) -> Result<u64, EthErrors> {
1983    debug_assert!(!price.is_zero(), "gas price must be positive");
1984    if balance < value {
1985        return Err(EthErrors::InsufficientFunds {
1986            balance: balance.clone(),
1987            value: value.clone(),
1988        });
1989    }
1990    let gas = (balance - value).atto() / price.atto();
1991    let allowance = u64::try_from(gas).unwrap_or(u64::MAX).min(BLOCK_GAS_LIMIT);
1992    if allowance == 0 {
1993        return Err(EthErrors::GasRequiredExceedsAllowance { gas_limit: 0 });
1994    }
1995    Ok(allowance)
1996}
1997
1998fn is_sender_validation_failed(err: &anyhow::Error) -> bool {
1999    matches!(
2000        err.downcast_ref(),
2001        Some(StateManagerError::SenderValidationFailed(_))
2002    )
2003}
2004
2005fn needs_skip_sender(result: &Result<(ApiInvocResult, Option<Cid>), Error>) -> bool {
2006    match result {
2007        Err(e) => is_sender_validation_failed(e),
2008        Ok((invoc_res, _)) => invoc_res
2009            .msg_rct
2010            .as_ref()
2011            .is_some_and(|rct| rct.exit_code() == ExitCode::SYS_SENDER_INVALID),
2012    }
2013}
2014
2015/// Applies `msg` with sender validation, then again without it if the sender was rejected.
2016/// A contract or missing `from` still runs, same as `eth_call`
2017/// ([lotus#13724](https://github.com/filecoin-project/lotus/pull/13724)).
2018async fn apply_on_state_accepting_any_sender(
2019    ctx: &Ctx,
2020    tipset: Option<&Tipset>,
2021    msg: &Message,
2022    vm_flush: VMFlush,
2023    vm_trace: VMTrace,
2024) -> Result<(ApiInvocResult, Option<Cid>), Error> {
2025    let result = ctx
2026        .state_manager
2027        .apply_on_state_with_gas(tipset, msg, vm_flush, vm_trace, SenderValidation::Enforce)
2028        .await;
2029
2030    if !needs_skip_sender(&result) {
2031        return result.context("failed to apply on state with gas");
2032    }
2033
2034    ctx.state_manager
2035        .apply_on_state_with_gas(tipset, msg, vm_flush, vm_trace, SenderValidation::Skip)
2036        .await
2037        .context("failed to apply on state with gas (skipping sender validation)")
2038}
2039
2040async fn apply_message(
2041    ctx: &Ctx,
2042    tipset: Option<&Tipset>,
2043    msg: &Message,
2044) -> Result<ApiInvocResult, Error> {
2045    if let Some(ts) = tipset
2046        && ts.epoch() > 0
2047        && ctx
2048            .chain_config()
2049            .has_expensive_fork_between(ts.epoch(), ts.epoch() + 1)
2050    {
2051        return Err(crate::state_manager::Error::ExpensiveFork { epoch: ts.epoch() }.into());
2052    }
2053
2054    let (invoc_res, _) =
2055        apply_on_state_accepting_any_sender(ctx, tipset, msg, VMFlush::Skip, VMTrace::NotTraced)
2056            .await?;
2057
2058    // Extract receipt or return early if none
2059    match &invoc_res.msg_rct {
2060        None => return Err(anyhow::anyhow!("no message receipt in execution result")),
2061        Some(receipt) => {
2062            if !receipt.exit_code().is_success() {
2063                return Err(EthErrors::execution_reverted_from_result(
2064                    receipt.exit_code(),
2065                    receipt.return_data(),
2066                    &invoc_res.error,
2067                )
2068                .into());
2069            }
2070        }
2071    };
2072
2073    Ok(invoc_res)
2074}
2075
2076/// Maps a message that failed within `gas_cap` to the error returned to the caller.
2077///
2078/// Execution failures are blamed on `gas_cap`, since the measurement already succeeded at the
2079/// block gas limit.
2080fn gas_cap_error(apply_ret: &ApplyRet, gas_cap: u64) -> EthErrors {
2081    let exit_code = apply_ret.exit_code();
2082    // Preflight rejects without executing anything, so it charges no gas.
2083    let preflight = apply_ret.gas_used() == 0;
2084    if preflight && exit_code == ExitCode::SYS_OUT_OF_GAS {
2085        EthErrors::GasRequiredExceedsAllowance { gas_limit: gas_cap }
2086    } else if preflight {
2087        EthErrors::execution_reverted_from_apply_ret(apply_ret)
2088    } else {
2089        EthErrors::InsufficientGasLimit { gas_limit: gas_cap }
2090    }
2091}
2092
2093/// Searches for the gas limit `msg` needs, never exceeding `gas_cap`.
2094async fn eth_gas_search(
2095    ctx: &Ctx,
2096    msg: Message,
2097    tipset: &Tipset,
2098    sender_validation: SenderValidation,
2099    gas_cap: u64,
2100) -> anyhow::Result<u64> {
2101    let gas_limit = msg.gas_limit().min(gas_cap);
2102    let msg = gas::without_fees(msg, gas_limit);
2103    // Probe the message at its own limit: the question is whether *that* limit suffices, which the
2104    // block maximum would always answer yes to.
2105    let (apply_ret, prior_messages, head, from) = gas::GasEstimateGasLimit::probe_as_specified(
2106        ctx,
2107        msg.clone(),
2108        tipset,
2109        VMTrace::NotTraced,
2110        sender_validation,
2111    )
2112    .await?;
2113    if apply_ret.exit_code().is_success() {
2114        return Ok(gas_limit);
2115    }
2116    let err = gas_cap_error(&apply_ret, gas_cap);
2117    // At the cap any failure is final; below it, only a preflight rejection unrelated to gas is.
2118    if gas_limit == gas_cap || matches!(err, EthErrors::ExecutionReverted { .. }) {
2119        return Err(err.into());
2120    }
2121
2122    let apply = |limit: u64| {
2123        let msg = msg.clone().into_builder().gas_limit(limit).build();
2124        let (prior_messages, head) = (prior_messages.shallow_clone(), head.shallow_clone());
2125        async move {
2126            let (apply_ret, ..) = ctx
2127                .state_manager
2128                .call_with_gas(
2129                    msg,
2130                    from.protocol(),
2131                    prior_messages,
2132                    Some(head),
2133                    VMFlush::Skip,
2134                    VMTrace::NotTraced,
2135                    sender_validation,
2136                )
2137                .await?;
2138            anyhow::Ok(apply_ret)
2139        }
2140    };
2141    gas_search(
2142        gas_limit,
2143        gas_cap,
2144        ctx.mpool.gas_limit_overestimation(),
2145        apply,
2146    )
2147    .await
2148}
2149
2150/// Finds the gas limit `apply` needs: the lowest limit, within 1%, at which it succeeds, plus the
2151/// `overestimation` margin when `apply` still succeeds with it; never above `gas_cap`.
2152///
2153/// The gas a run *uses* is not a limit it can run with: a nested `CALL` forwards at most 63/64 of
2154/// the remaining gas, and a contract can `revert` on `gasleft()`, so only runs at other limits
2155/// tell which limits work. `start` is a limit the caller already saw fail.
2156///
2157/// # Errors
2158///
2159/// [`EthErrors`] from [`gas_cap_error`] when the message does not fit in `gas_cap`.
2160async fn gas_search<F>(
2161    start: u64,
2162    gas_cap: u64,
2163    overestimation: f64,
2164    apply: impl Fn(u64) -> F,
2165) -> anyhow::Result<u64>
2166where
2167    F: Future<Output = anyhow::Result<ApplyRet>>,
2168{
2169    let can_succeed = async |limit: u64| anyhow::Ok(apply(limit).await?.exit_code().is_success());
2170    let mut low = start;
2171    // A floor of 1 keeps the doubling below able to make progress.
2172    let mut high = start.saturating_mul(2).max(1).min(gas_cap);
2173
2174    while high < gas_cap {
2175        if can_succeed(high).await? {
2176            break;
2177        }
2178        low = high;
2179        high = high.saturating_mul(2).min(gas_cap);
2180    }
2181    // The doubling stops at the cap without trying it.
2182    if high == gas_cap {
2183        let apply_ret = apply(gas_cap).await?;
2184        if !apply_ret.exit_code().is_success() {
2185            return Err(gas_cap_error(&apply_ret, gas_cap).into());
2186        }
2187    }
2188
2189    // At least 1, or bisection below 100 gas never terminates once `high` and `low` are adjacent.
2190    let mut check_threshold = (high / 100).max(1);
2191    while (high - low) > check_threshold {
2192        let median = (high + low) / 2;
2193        if can_succeed(median).await? {
2194            high = median;
2195        } else {
2196            low = median;
2197        }
2198        check_threshold = (median / 100).max(1);
2199    }
2200
2201    // A contract that checks `gasleft()` can fail with more gas, so keep the tested limit if the
2202    // margin breaks the call.
2203    let with_margin = ((high as f64 * overestimation) as u64).min(gas_cap);
2204    if with_margin == high || !can_succeed(with_margin).await? {
2205        return Ok(high);
2206    }
2207    Ok(with_margin)
2208}
2209
2210pub enum EthFeeHistory {}
2211
2212impl RpcMethod<3> for EthFeeHistory {
2213    const NAME: &'static str = "Filecoin.EthFeeHistory";
2214    const NAME_ALIAS: Option<&'static str> = Some("eth_feeHistory");
2215    const N_REQUIRED_PARAMS: usize = 2;
2216    const PARAM_NAMES: [&'static str; 3] = ["blockCount", "newestBlockNumber", "rewardPercentiles"];
2217    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2218    const PERMISSION: Permission = Permission::Read;
2219    const DESCRIPTION: &'static str = "Returns historical gas information for a range of blocks, including base fee per gas, gas used ratio, and priority fee percentiles.";
2220
2221    type Params = (EthUint64, BlockNumberOrPredefined, Option<Vec<f64>>);
2222    type Ok = EthFeeHistoryResult;
2223
2224    async fn handle(
2225        ctx: Ctx,
2226        (EthUint64(block_count), newest_block_number, reward_percentiles): Self::Params,
2227        ext: &http::Extensions,
2228    ) -> Result<Self::Ok, ServerError> {
2229        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
2230        let tipset = resolver
2231            .tipset_by_block_number_or_hash(newest_block_number, ResolveNullTipset::TakeOlder)
2232            .await?;
2233        eth_fee_history(ctx, tipset, block_count, reward_percentiles).await
2234    }
2235}
2236
2237async fn eth_fee_history(
2238    ctx: Ctx,
2239    tipset: Tipset,
2240    block_count: u64,
2241    reward_percentiles: Option<Vec<f64>>,
2242) -> Result<EthFeeHistoryResult, ServerError> {
2243    if block_count > 1024 {
2244        return Err(anyhow::anyhow!("block count should be smaller than 1024").into());
2245    }
2246
2247    let reward_percentiles = reward_percentiles.unwrap_or_default();
2248    validate_reward_percentiles(&reward_percentiles)?;
2249
2250    let mut oldest_block_height = 1;
2251    // NOTE: baseFeePerGas should include the next block after the newest of the returned range,
2252    //  because the next base fee can be inferred from the messages in the newest block.
2253    //  However, this is NOT the case in Filecoin due to deferred execution, so the best
2254    //  we can do is duplicate the last value.
2255    let mut base_fee_array = vec![EthBigInt::from(
2256        &tipset.block_headers().first().parent_base_fee,
2257    )];
2258    let mut rewards_array = vec![];
2259    let mut gas_used_ratio_array = vec![];
2260    // The walk goes newest -> oldest, so each tipset is the child of the next. Carry it forward as the
2261    // receipt source for the next (older) tipset, so only the newest needs a `load_child_tipset` lookup
2262    // (`None` on the first pass).
2263    let mut child: Option<Tipset> = None;
2264    for ts in tipset
2265        .chain(ctx.db())
2266        .filter(|i| i.epoch() > 0)
2267        .take(block_count as _)
2268    {
2269        let base_fee = &ts.block_headers().first().parent_base_fee;
2270        let message_receipts = ctx
2271            .state_manager
2272            .tipset_message_receipts(&ts, child.as_ref())
2273            .await?;
2274        let tx_gas_rewards = message_receipts
2275            .iter()
2276            .map(|(message, receipt)| GasReward {
2277                gas_used: receipt.gas_used(),
2278                premium: message.effective_gas_premium(base_fee),
2279            })
2280            .collect_vec();
2281        let (rewards, total_gas_used) =
2282            calculate_rewards_and_gas_used(&reward_percentiles, tx_gas_rewards);
2283        let max_gas = BLOCK_GAS_LIMIT * (ts.block_headers().len() as u64);
2284
2285        // arrays should be reversed at the end
2286        base_fee_array.push(EthBigInt::from(base_fee));
2287        gas_used_ratio_array.push((total_gas_used as f64) / (max_gas as f64));
2288        rewards_array.push(rewards);
2289
2290        oldest_block_height = ts.epoch();
2291        // This tipset is the receipt source (child) of the next (older) one.
2292        child = Some(ts);
2293    }
2294
2295    // Reverse the arrays; we collected them newest to oldest; the client expects oldest to newest.
2296    base_fee_array.reverse();
2297    gas_used_ratio_array.reverse();
2298    rewards_array.reverse();
2299
2300    Ok(EthFeeHistoryResult {
2301        oldest_block: EthUint64(oldest_block_height as _),
2302        base_fee_per_gas: base_fee_array,
2303        gas_used_ratio: gas_used_ratio_array,
2304        reward: if reward_percentiles.is_empty() {
2305            None
2306        } else {
2307            Some(rewards_array)
2308        },
2309    })
2310}
2311
2312fn validate_reward_percentiles(reward_percentiles: &[f64]) -> anyhow::Result<()> {
2313    if reward_percentiles.len() > 100 {
2314        anyhow::bail!("length of the reward percentile array cannot be greater than 100");
2315    }
2316
2317    for (&rp_prev, &rp) in std::iter::once(&0.0)
2318        .chain(reward_percentiles.iter())
2319        .tuple_windows()
2320    {
2321        if !(0. ..=100.).contains(&rp) {
2322            anyhow::bail!("invalid reward percentile: {rp} should be between 0 and 100");
2323        }
2324        if rp < rp_prev {
2325            anyhow::bail!(
2326                "invalid reward percentile: {rp} should be larger than or equal to {rp_prev}"
2327            );
2328        }
2329    }
2330
2331    Ok(())
2332}
2333
2334fn calculate_rewards_and_gas_used(
2335    reward_percentiles: &[f64],
2336    mut tx_gas_rewards: Vec<GasReward>,
2337) -> (Vec<EthBigInt>, u64) {
2338    const MIN_GAS_PREMIUM: u64 = 100000;
2339
2340    let gas_used_total = tx_gas_rewards.iter().map(|i| i.gas_used).sum();
2341    let mut rewards = reward_percentiles
2342        .iter()
2343        .map(|_| EthBigInt::from(MIN_GAS_PREMIUM))
2344        .collect_vec();
2345    if !tx_gas_rewards.is_empty() {
2346        tx_gas_rewards.sort_by(|a, b| a.premium.cmp(&b.premium));
2347        let mut idx = 0;
2348        let mut sum = 0;
2349        #[allow(clippy::indexing_slicing)]
2350        for (i, &percentile) in reward_percentiles.iter().enumerate() {
2351            let threshold = ((gas_used_total as f64) * percentile / 100.) as u64;
2352            while sum < threshold && idx < tx_gas_rewards.len() - 1 {
2353                sum += tx_gas_rewards[idx].gas_used;
2354                idx += 1;
2355            }
2356            rewards[i] = (&tx_gas_rewards[idx].premium).into();
2357        }
2358    }
2359    (rewards, gas_used_total)
2360}
2361
2362pub enum EthGetCode {}
2363impl RpcMethod<2> for EthGetCode {
2364    const NAME: &'static str = "Filecoin.EthGetCode";
2365    const NAME_ALIAS: Option<&'static str> = Some("eth_getCode");
2366    const PARAM_NAMES: [&'static str; 2] = ["ethAddress", "blockNumberOrHash"];
2367    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2368    const PERMISSION: Permission = Permission::Read;
2369    const DESCRIPTION: &'static str = "Retrieves the contract code at a specific address and block state, identified by its number, hash, or a special tag.";
2370
2371    type Params = (EthAddress, BlockNumberOrHash);
2372    type Ok = EthBytes;
2373
2374    async fn handle(
2375        ctx: Ctx,
2376        (eth_address, block_param): Self::Params,
2377        ext: &http::Extensions,
2378    ) -> Result<Self::Ok, ServerError> {
2379        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
2380        let ts = resolver
2381            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::TakeOlder)
2382            .await?;
2383        eth_get_code(&ctx, &ts, &eth_address).await
2384    }
2385}
2386
2387async fn eth_get_code(
2388    ctx: &Ctx,
2389    ts: &Tipset,
2390    eth_address: &EthAddress,
2391) -> Result<EthBytes, ServerError> {
2392    let to_address = FilecoinAddress::try_from(eth_address)?;
2393    let TipsetState { state_root, .. } = ctx.state_manager.load_tipset_state(ts).await?;
2394    let Some(actor) = ctx
2395        .state_manager
2396        .get_actor(&to_address, state_root)
2397        .with_context(|| format!("failed to lookup contract {}", eth_address.0))?
2398    else {
2399        return Ok(Default::default());
2400    };
2401
2402    Ok(actor.eth_bytecode(ctx.db())?.unwrap_or_default())
2403}
2404
2405pub enum EthGetStorageAt {}
2406impl RpcMethod<3> for EthGetStorageAt {
2407    const NAME: &'static str = "Filecoin.EthGetStorageAt";
2408    const NAME_ALIAS: Option<&'static str> = Some("eth_getStorageAt");
2409    const PARAM_NAMES: [&'static str; 3] = ["ethAddress", "position", "blockNumberOrHash"];
2410    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2411    const PERMISSION: Permission = Permission::Read;
2412    const DESCRIPTION: &'static str =
2413        "Retrieves the storage value at a specific position for a contract
2414        at a given block state, identified by its number, hash, or a special tag.";
2415
2416    type Params = (EthAddress, EthBytes, BlockNumberOrHash);
2417    type Ok = EthBytes;
2418
2419    async fn handle(
2420        ctx: Ctx,
2421        (eth_address, position, block_number_or_hash): Self::Params,
2422        ext: &http::Extensions,
2423    ) -> Result<Self::Ok, ServerError> {
2424        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
2425        let ts = resolver
2426            .tipset_by_block_number_or_hash(block_number_or_hash, ResolveNullTipset::TakeOlder)
2427            .await?;
2428        eth_get_storage_at(&ctx, &ts, eth_address, position).await
2429    }
2430}
2431
2432async fn eth_get_storage_at(
2433    ctx: &Ctx,
2434    ts: &Tipset,
2435    eth_address: EthAddress,
2436    position: EthBytes,
2437) -> Result<EthBytes, ServerError> {
2438    // Validate and left-pad before touching state, as Lotus does.
2439    let position = GetStorageAtParams::new(position.0)?.0;
2440    let to_address = FilecoinAddress::try_from(&eth_address)?;
2441    let TipsetState { state_root, .. } = ctx.state_manager.load_tipset_state(ts).await?;
2442    let value = match ctx
2443        .state_manager
2444        .get_actor(&to_address, state_root)
2445        .with_context(|| format!("failed to lookup contract {}", eth_address.0))?
2446    {
2447        Some(actor) => actor.eth_storage_at(ctx.db(), &position)?,
2448        None => [0; EVM_WORD_LENGTH],
2449    };
2450    Ok(EthBytes(value.to_vec()))
2451}
2452
2453pub enum EthGetTransactionCount {}
2454impl RpcMethod<2> for EthGetTransactionCount {
2455    const NAME: &'static str = "Filecoin.EthGetTransactionCount";
2456    const NAME_ALIAS: Option<&'static str> = Some("eth_getTransactionCount");
2457    const PARAM_NAMES: [&'static str; 2] = ["sender", "blockParam"];
2458    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2459    const PERMISSION: Permission = Permission::Read;
2460    const DESCRIPTION: &'static str = "Returns the number of transactions sent from an address (its nonce) at the specified block state.";
2461
2462    type Params = (EthAddress, BlockNumberOrHash);
2463    type Ok = EthUint64;
2464
2465    async fn handle(
2466        ctx: Ctx,
2467        (sender, block_param): Self::Params,
2468        ext: &http::Extensions,
2469    ) -> Result<Self::Ok, ServerError> {
2470        let addr = sender.to_filecoin_address()?;
2471        match block_param {
2472            BlockNumberOrHash::PredefinedBlock(Predefined::Pending) => {
2473                Ok(EthUint64(ctx.mpool.get_sequence(&addr).await?))
2474            }
2475            _ => {
2476                let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
2477                let ts = resolver
2478                    .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::TakeOlder)
2479                    .await?;
2480                eth_get_transaction_count(&ctx, &ts, addr).await
2481            }
2482        }
2483    }
2484}
2485
2486async fn eth_get_transaction_count(
2487    ctx: &Ctx,
2488    ts: &Tipset,
2489    addr: FilecoinAddress,
2490) -> Result<EthUint64, ServerError> {
2491    let TipsetState { state_root, .. } = ctx.state_manager.load_tipset_state(ts).await?;
2492
2493    let state_tree = ctx.state_manager.get_state_tree(&state_root)?;
2494    let actor = match state_tree.get_actor(&addr)? {
2495        Some(actor) => actor,
2496        None => return Ok(EthUint64(0)),
2497    };
2498
2499    Ok(actor.eth_nonce(ctx.db())?)
2500}
2501
2502pub enum EthMaxPriorityFeePerGas {}
2503impl RpcMethod<0> for EthMaxPriorityFeePerGas {
2504    const NAME: &'static str = "Filecoin.EthMaxPriorityFeePerGas";
2505    const NAME_ALIAS: Option<&'static str> = Some("eth_maxPriorityFeePerGas");
2506    const PARAM_NAMES: [&'static str; 0] = [];
2507    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2508    const PERMISSION: Permission = Permission::Read;
2509    const DESCRIPTION: &'static str = "Returns an estimate of the priority fee per gas (tip) needed for timely inclusion, in attoFIL.";
2510
2511    type Params = ();
2512    type Ok = EthBigInt;
2513
2514    async fn handle(
2515        ctx: Ctx,
2516        (): Self::Params,
2517        _: &http::Extensions,
2518    ) -> Result<Self::Ok, ServerError> {
2519        match gas::estimate_gas_premium(&ctx, 0, &ApiTipsetKey(None)).await {
2520            Ok(gas_premium) => Ok(gas_premium.atto().into()),
2521            Err(_) => Ok(EthBigInt::default()),
2522        }
2523    }
2524}
2525
2526pub enum EthProtocolVersion {}
2527impl RpcMethod<0> for EthProtocolVersion {
2528    const NAME: &'static str = "Filecoin.EthProtocolVersion";
2529    const NAME_ALIAS: Option<&'static str> = Some("eth_protocolVersion");
2530    const PARAM_NAMES: [&'static str; 0] = [];
2531    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2532    const PERMISSION: Permission = Permission::Read;
2533    const DESCRIPTION: &'static str =
2534        "Returns the current Filecoin network version, reported as the Ethereum protocol version.";
2535
2536    type Params = ();
2537    type Ok = EthUint64;
2538
2539    async fn handle(
2540        ctx: Ctx,
2541        (): Self::Params,
2542        _: &http::Extensions,
2543    ) -> Result<Self::Ok, ServerError> {
2544        let epoch = ctx.chain_store().heaviest_tipset().epoch();
2545        let version = u32::from(ctx.state_manager.get_network_version(epoch).0);
2546        Ok(EthUint64(version.into()))
2547    }
2548}
2549
2550pub enum EthGetTransactionByBlockNumberAndIndex {}
2551impl RpcMethod<2> for EthGetTransactionByBlockNumberAndIndex {
2552    const NAME: &'static str = "Filecoin.EthGetTransactionByBlockNumberAndIndex";
2553    const NAME_ALIAS: Option<&'static str> = Some("eth_getTransactionByBlockNumberAndIndex");
2554    const PARAM_NAMES: [&'static str; 2] = ["blockParam", "txIndex"];
2555    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2556    const PERMISSION: Permission = Permission::Read;
2557    const DESCRIPTION: &'static str = "Retrieves a transaction by its block number and index.";
2558
2559    type Params = (BlockNumberOrPredefined, EthUint64);
2560    type Ok = Option<ApiEthTx>;
2561
2562    async fn handle(
2563        ctx: Ctx,
2564        (block_param, tx_index): Self::Params,
2565        ext: &http::Extensions,
2566    ) -> Result<Self::Ok, ServerError> {
2567        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
2568        let ts = resolver
2569            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::Fail)
2570            .await?;
2571        eth_tx_by_tipset_and_idx(&ctx, &ts, tx_index).await
2572    }
2573}
2574
2575async fn eth_tx_by_tipset_and_idx(
2576    ctx: &Ctx,
2577    ts: &Tipset,
2578    tx_index: EthUint64,
2579) -> Result<Option<ApiEthTx>, ServerError> {
2580    let messages = ctx.chain_store().messages_for_tipset(ts)?;
2581
2582    let EthUint64(index) = tx_index;
2583    let msg = messages.get(index as usize).with_context(|| {
2584        format!(
2585            "transaction index {index} out of range: tipset contains {} messages",
2586            messages.len()
2587        )
2588    })?;
2589
2590    // Resolve addresses against the tipset's post-execution state so that newly created actors
2591    // are included correctly.
2592    let TipsetState { state_root, .. } = ctx.state_manager.load_tipset_state(ts).await?;
2593    let state = ctx.state_manager.get_state_tree(&state_root)?;
2594
2595    let tx = new_eth_tx(ctx, &state, ts.epoch(), &ts.key().cid()?, &msg.cid(), index)?;
2596
2597    Ok(Some(tx))
2598}
2599
2600pub enum EthGetTransactionByBlockHashAndIndex {}
2601impl RpcMethod<2> for EthGetTransactionByBlockHashAndIndex {
2602    const NAME: &'static str = "Filecoin.EthGetTransactionByBlockHashAndIndex";
2603    const NAME_ALIAS: Option<&'static str> = Some("eth_getTransactionByBlockHashAndIndex");
2604    const PARAM_NAMES: [&'static str; 2] = ["blockHash", "txIndex"];
2605    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2606    const PERMISSION: Permission = Permission::Read;
2607    const DESCRIPTION: &'static str = "Retrieves a transaction by its block hash and index.";
2608
2609    type Params = (EthHash, EthUint64);
2610    type Ok = Option<ApiEthTx>;
2611
2612    async fn handle(
2613        ctx: Ctx,
2614        (block_hash, tx_index): Self::Params,
2615        _: &http::Extensions,
2616    ) -> Result<Self::Ok, ServerError> {
2617        let ts = get_tipset_from_hash(ctx.chain_store(), &block_hash)?;
2618        eth_tx_by_tipset_and_idx(&ctx, &ts, tx_index).await
2619    }
2620}
2621
2622pub enum EthGetTransactionByHash {}
2623impl RpcMethod<1> for EthGetTransactionByHash {
2624    const NAME: &'static str = "Filecoin.EthGetTransactionByHash";
2625    const NAME_ALIAS: Option<&'static str> = Some("eth_getTransactionByHash");
2626    const PARAM_NAMES: [&'static str; 1] = ["txHash"];
2627    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2628    const PERMISSION: Permission = Permission::Read;
2629    const DESCRIPTION: &'static str = "Retrieves a transaction by its hash.";
2630
2631    type Params = (EthHash,);
2632    type Ok = Option<ApiEthTx>;
2633
2634    async fn handle(
2635        ctx: Ctx,
2636        (tx_hash,): Self::Params,
2637        _: &http::Extensions,
2638    ) -> Result<Self::Ok, ServerError> {
2639        let cancellation_token = CancellationToken::new();
2640        let _drop_guard = cancellation_token.drop_guard_ref();
2641        get_eth_transaction_by_hash(&ctx, &tx_hash, None, &cancellation_token).await
2642    }
2643}
2644
2645pub enum EthGetTransactionByHashLimited {}
2646impl RpcMethod<2> for EthGetTransactionByHashLimited {
2647    const NAME: &'static str = "Filecoin.EthGetTransactionByHashLimited";
2648    const NAME_ALIAS: Option<&'static str> = Some("eth_getTransactionByHashLimited");
2649    const PARAM_NAMES: [&'static str; 2] = ["txHash", "limit"];
2650    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2651    const PERMISSION: Permission = Permission::Read;
2652    const DESCRIPTION: &'static str =
2653        "Retrieves a transaction by its hash, limiting state resolution to the given chain epoch.";
2654
2655    type Params = (EthHash, ChainEpoch);
2656    type Ok = Option<ApiEthTx>;
2657
2658    async fn handle(
2659        ctx: Ctx,
2660        (tx_hash, limit): Self::Params,
2661        _: &http::Extensions,
2662    ) -> Result<Self::Ok, ServerError> {
2663        let cancellation_token = CancellationToken::new();
2664        let _drop_guard = cancellation_token.drop_guard_ref();
2665        get_eth_transaction_by_hash(&ctx, &tx_hash, Some(limit), &cancellation_token).await
2666    }
2667}
2668
2669async fn get_eth_transaction_by_hash(
2670    ctx: &Ctx,
2671    tx_hash: &EthHash,
2672    limit: Option<ChainEpoch>,
2673    cancellation_token: &CancellationToken,
2674) -> Result<Option<ApiEthTx>, ServerError> {
2675    let mapping = ctx.chain_store().get_mapping(tx_hash)?;
2676    let message_cid = mapping.unwrap_or_else(|| {
2677        tracing::debug!(
2678            "could not find transaction hash {} in Ethereum mapping",
2679            tx_hash
2680        );
2681        // This isn't an eth transaction we have the mapping for, so let's look it up as a filecoin message
2682        tx_hash.to_cid()
2683    });
2684
2685    // First, try to get the cid from mined transactions
2686    if let Ok(Some((tipset, receipt))) = ctx
2687        .state_manager
2688        .search_for_message(None, message_cid, limit, Some(true), cancellation_token)
2689        .await
2690    {
2691        let ipld = receipt.return_data().deserialize().unwrap_or(Ipld::Null);
2692        let message_lookup = MessageLookup {
2693            receipt,
2694            tipset: tipset.key().clone(),
2695            height: tipset.epoch(),
2696            message: message_cid,
2697            return_dec: ipld,
2698        };
2699
2700        if let Ok(tx) = new_eth_tx_from_message_lookup(ctx, &message_lookup, None) {
2701            return Ok(Some(tx));
2702        }
2703    }
2704
2705    // If not found, try to get it from the mempool
2706    let (pending, _) = ctx.mpool.pending();
2707
2708    // We only return pending eth-account messages because we can't guarantee
2709    // that the from/to addresses of other messages are conversable to 0x-style
2710    // addresses. So we just ignore them.
2711    //
2712    // This should be "fine" as anyone using an "Ethereum-centric" block
2713    // explorer shouldn't care about seeing pending messages from native
2714    // accounts.
2715    let eth_chain_id = ctx.chain_config().eth_chain_id;
2716    let pending_tx = match mapping {
2717        Some(cid) => pending
2718            .iter()
2719            .find(|smsg| smsg.cid() == cid)
2720            .and_then(|smsg| eth_tx_from_delegated_message(smsg, eth_chain_id).ok()),
2721        // Without a mapping `tx_hash.to_cid()` never matches a delegated message's CID, so those
2722        // are found by their Ethereum hash.
2723        None => pending
2724            .iter()
2725            .filter_map(|smsg| eth_tx_from_delegated_message(smsg, eth_chain_id).ok())
2726            .find(|tx| tx.hash == *tx_hash),
2727    };
2728
2729    // Ethereum clients expect an empty response when the message was not found
2730    Ok(pending_tx)
2731}
2732
2733/// The API transaction of a delegated message, with its sender and hash; fails when it is not an
2734/// Ethereum transaction.
2735fn eth_tx_from_delegated_message(
2736    smsg: &SignedMessage,
2737    eth_chain_id: EthChainIdType,
2738) -> anyhow::Result<ApiEthTx> {
2739    let (from, tx) = eth_tx_from_signed_eth_message(smsg, eth_chain_id)?;
2740    let hash = tx.eth_hash()?.into();
2741    Ok(ApiEthTx {
2742        from,
2743        hash,
2744        ..tx.into()
2745    })
2746}
2747
2748pub enum EthGetTransactionHashByCid {}
2749
2750impl EthGetTransactionHashByCid {
2751    fn run(db: &DbImpl, eth_chain_id: EthChainIdType, cid: Cid) -> anyhow::Result<Option<EthHash>> {
2752        let smsgs_result: Result<Vec<SignedMessage>, crate::chain::Error> =
2753            crate::chain::messages_from_cids(db, &[cid]);
2754        if let Ok(smsgs) = smsgs_result
2755            && let Some(smsg) = smsgs.first()
2756        {
2757            return Ok(Some(eth_tx_hash_from_signed_message(smsg, eth_chain_id)?));
2758        }
2759
2760        let msg_result = crate::chain::get_chain_message(db, &cid);
2761        if let Ok(msg) = msg_result {
2762            return Ok(Some(msg.cid().into()));
2763        }
2764
2765        Ok(None)
2766    }
2767}
2768
2769impl RpcMethod<1> for EthGetTransactionHashByCid {
2770    const NAME: &'static str = "Filecoin.EthGetTransactionHashByCid";
2771    const NAME_ALIAS: Option<&'static str> = Some("eth_getTransactionHashByCid");
2772    const PARAM_NAMES: [&'static str; 1] = ["cid"];
2773    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2774    const PERMISSION: Permission = Permission::Read;
2775    const DESCRIPTION: &'static str =
2776        "Returns the Ethereum transaction hash for the given Filecoin message CID.";
2777
2778    type Params = (Cid,);
2779    type Ok = Option<EthHash>;
2780
2781    async fn handle(
2782        ctx: Ctx,
2783        (cid,): Self::Params,
2784        _: &http::Extensions,
2785    ) -> Result<Self::Ok, ServerError> {
2786        Ok(Self::run(ctx.db(), ctx.chain_config().eth_chain_id, cid)?)
2787    }
2788}
2789
2790pub enum EthCall {}
2791impl RpcMethod<2> for EthCall {
2792    const NAME: &'static str = "Filecoin.EthCall";
2793    const NAME_ALIAS: Option<&'static str> = Some("eth_call");
2794    const N_REQUIRED_PARAMS: usize = 2;
2795    const PARAM_NAMES: [&'static str; 2] = ["tx", "blockParam"];
2796    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2797    const PERMISSION: Permission = Permission::Read;
2798    const DESCRIPTION: &'static str = "Executes a read-only message call against the given block state without creating an on-chain transaction, returning the call output.";
2799    type Params = (EthCallMessage, BlockNumberOrHash);
2800    type Ok = EthBytes;
2801    async fn handle(
2802        ctx: Ctx,
2803        (tx, block_param): Self::Params,
2804        ext: &http::Extensions,
2805    ) -> Result<Self::Ok, ServerError> {
2806        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
2807        let ts = resolver
2808            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::TakeOlder)
2809            .await?;
2810        eth_call(&ctx, tx, ts).await
2811    }
2812}
2813
2814async fn eth_call(ctx: &Ctx, tx: EthCallMessage, ts: Tipset) -> Result<EthBytes, ServerError> {
2815    let msg = Message::try_from(tx)?;
2816    let invoke_result = apply_message(ctx, Some(&ts), &msg).await?;
2817
2818    if msg.to() == FilecoinAddress::ETHEREUM_ACCOUNT_MANAGER_ACTOR {
2819        Ok(EthBytes::default())
2820    } else {
2821        let msg_rct = invoke_result.msg_rct.context("no message receipt")?;
2822        let return_data = msg_rct.return_data();
2823        if return_data.is_empty() {
2824            Ok(Default::default())
2825        } else {
2826            let bytes = decode_payload(&return_data, CBOR)?;
2827            Ok(bytes)
2828        }
2829    }
2830}
2831
2832pub enum EthNewFilter {}
2833impl RpcMethod<1> for EthNewFilter {
2834    const NAME: &'static str = "Filecoin.EthNewFilter";
2835    const NAME_ALIAS: Option<&'static str> = Some("eth_newFilter");
2836    const PARAM_NAMES: [&'static str; 1] = ["filterSpec"];
2837    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2838    const PERMISSION: Permission = Permission::Read;
2839    const DESCRIPTION: &'static str =
2840        "Installs a persistent filter for matching event logs based on the given filter spec.";
2841
2842    type Params = (EthFilterSpec,);
2843    type Ok = FilterID;
2844
2845    async fn handle(
2846        ctx: Ctx,
2847        (filter_spec,): Self::Params,
2848        _: &http::Extensions,
2849    ) -> Result<Self::Ok, ServerError> {
2850        let eth_event_handler = ctx.eth_event_handler.clone();
2851        let chain_height = ctx.chain_store().heaviest_tipset().epoch();
2852        Ok(eth_event_handler.eth_new_filter(&filter_spec, chain_height)?)
2853    }
2854}
2855
2856pub enum EthNewPendingTransactionFilter {}
2857impl RpcMethod<0> for EthNewPendingTransactionFilter {
2858    const NAME: &'static str = "Filecoin.EthNewPendingTransactionFilter";
2859    const NAME_ALIAS: Option<&'static str> = Some("eth_newPendingTransactionFilter");
2860    const PARAM_NAMES: [&'static str; 0] = [];
2861    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2862    const PERMISSION: Permission = Permission::Read;
2863    const DESCRIPTION: &'static str =
2864        "Installs a persistent filter that tracks new messages arriving in the message pool.";
2865
2866    type Params = ();
2867    type Ok = FilterID;
2868
2869    async fn handle(
2870        ctx: Ctx,
2871        (): Self::Params,
2872        _: &http::Extensions,
2873    ) -> Result<Self::Ok, ServerError> {
2874        let eth_event_handler = ctx.eth_event_handler.clone();
2875        Ok(eth_event_handler.eth_new_pending_transaction_filter()?)
2876    }
2877}
2878
2879pub enum EthNewBlockFilter {}
2880impl RpcMethod<0> for EthNewBlockFilter {
2881    const NAME: &'static str = "Filecoin.EthNewBlockFilter";
2882    const NAME_ALIAS: Option<&'static str> = Some("eth_newBlockFilter");
2883    const PARAM_NAMES: [&'static str; 0] = [];
2884    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2885    const PERMISSION: Permission = Permission::Read;
2886    const DESCRIPTION: &'static str =
2887        "Installs a persistent filter that tracks the arrival of new blocks.";
2888
2889    type Params = ();
2890    type Ok = FilterID;
2891
2892    async fn handle(
2893        ctx: Ctx,
2894        (): Self::Params,
2895        _: &http::Extensions,
2896    ) -> Result<Self::Ok, ServerError> {
2897        let eth_event_handler = ctx.eth_event_handler.clone();
2898
2899        Ok(eth_event_handler.eth_new_block_filter()?)
2900    }
2901}
2902
2903pub enum EthUninstallFilter {}
2904impl RpcMethod<1> for EthUninstallFilter {
2905    const NAME: &'static str = "Filecoin.EthUninstallFilter";
2906    const NAME_ALIAS: Option<&'static str> = Some("eth_uninstallFilter");
2907    const PARAM_NAMES: [&'static str; 1] = ["filterId"];
2908    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2909    const PERMISSION: Permission = Permission::Read;
2910    const DESCRIPTION: &'static str = "Uninstalls the filter with the given ID.";
2911
2912    type Params = (FilterID,);
2913    type Ok = bool;
2914
2915    async fn handle(
2916        ctx: Ctx,
2917        (filter_id,): Self::Params,
2918        _: &http::Extensions,
2919    ) -> Result<Self::Ok, ServerError> {
2920        let eth_event_handler = ctx.eth_event_handler.clone();
2921
2922        Ok(eth_event_handler.eth_uninstall_filter(&filter_id)?)
2923    }
2924}
2925
2926pub enum EthUnsubscribe {}
2927impl RpcMethod<0> for EthUnsubscribe {
2928    const NAME: &'static str = "Filecoin.EthUnsubscribe";
2929    const NAME_ALIAS: Option<&'static str> = Some("eth_unsubscribe");
2930    const PARAM_NAMES: [&'static str; 0] = [];
2931    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2932    const PERMISSION: Permission = Permission::Read;
2933    const DESCRIPTION: &'static str =
2934        "Cancels an existing websocket subscription identified by its subscription ID.";
2935    const SUBSCRIPTION: bool = true;
2936
2937    type Params = ();
2938    type Ok = ();
2939
2940    // This method is a placeholder and is never actually called.
2941    // Subscription handling is performed in [`pubsub.rs`](pubsub).
2942    //
2943    // We still need to implement the [`RpcMethod`] trait to expose method metadata
2944    // like [`NAME`](Self::NAME), [`NAME_ALIAS`](Self::NAME_ALIAS), [`PERMISSION`](Self::PERMISSION), etc..
2945    async fn handle(
2946        _: Ctx,
2947        (): Self::Params,
2948        _: &http::Extensions,
2949    ) -> Result<Self::Ok, ServerError> {
2950        Ok(())
2951    }
2952}
2953
2954pub enum EthSubscribe {}
2955impl RpcMethod<0> for EthSubscribe {
2956    const NAME: &'static str = "Filecoin.EthSubscribe";
2957    const NAME_ALIAS: Option<&'static str> = Some("eth_subscribe");
2958    const PARAM_NAMES: [&'static str; 0] = [];
2959    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2960    const PERMISSION: Permission = Permission::Read;
2961    const DESCRIPTION: &'static str = "Creates a websocket subscription that streams events (new heads, pending transactions, or logs) to the client.";
2962    const SUBSCRIPTION: bool = true;
2963
2964    type Params = ();
2965    type Ok = ();
2966
2967    // This method is a placeholder and is never actually called.
2968    // Subscription handling is performed in [`pubsub.rs`](pubsub).
2969    //
2970    // We still need to implement the [`RpcMethod`] trait to expose method metadata
2971    // like [`NAME`](Self::NAME), [`NAME_ALIAS`](Self::NAME_ALIAS), [`PERMISSION`](Self::PERMISSION), etc..
2972    async fn handle(
2973        _: Ctx,
2974        (): Self::Params,
2975        _: &http::Extensions,
2976    ) -> Result<Self::Ok, ServerError> {
2977        Ok(())
2978    }
2979}
2980
2981pub enum EthAddressToFilecoinAddress {}
2982impl RpcMethod<1> for EthAddressToFilecoinAddress {
2983    const NAME: &'static str = "Filecoin.EthAddressToFilecoinAddress";
2984    const PARAM_NAMES: [&'static str; 1] = ["ethAddress"];
2985    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
2986    const PERMISSION: Permission = Permission::Read;
2987    const DESCRIPTION: &'static str = "Converts an EthAddress into an f410 Filecoin Address";
2988    type Params = (EthAddress,);
2989    type Ok = FilecoinAddress;
2990    async fn handle(
2991        _ctx: Ctx,
2992        (eth_address,): Self::Params,
2993        _: &http::Extensions,
2994    ) -> Result<Self::Ok, ServerError> {
2995        Ok(eth_address.to_filecoin_address()?)
2996    }
2997}
2998
2999pub enum FilecoinAddressToEthAddress {}
3000impl RpcMethod<2> for FilecoinAddressToEthAddress {
3001    const NAME: &'static str = "Filecoin.FilecoinAddressToEthAddress";
3002    const N_REQUIRED_PARAMS: usize = 1;
3003    const PARAM_NAMES: [&'static str; 2] = ["filecoinAddress", "blockParam"];
3004    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3005    const PERMISSION: Permission = Permission::Read;
3006    const DESCRIPTION: &'static str = "Converts any Filecoin address to an EthAddress";
3007    type Params = (FilecoinAddress, Option<BlockNumberOrPredefined>);
3008    type Ok = EthAddress;
3009    async fn handle(
3010        ctx: Ctx,
3011        (address, block_param): Self::Params,
3012        ext: &http::Extensions,
3013    ) -> Result<Self::Ok, ServerError> {
3014        if let Ok(eth_address) = EthAddress::from_filecoin_address(&address) {
3015            Ok(eth_address)
3016        } else {
3017            let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
3018            // Default to Finalized for Lotus parity
3019            let block_param = block_param.unwrap_or_else(|| Predefined::Finalized.into());
3020            let ts = resolver
3021                .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::TakeOlder)
3022                .await?;
3023
3024            let id_address = ctx.state_manager.lookup_required_id(&address, &ts)?;
3025            Ok(EthAddress::from_filecoin_address(&id_address)?)
3026        }
3027    }
3028}
3029
3030#[derive(Clone, Debug, GetSize)]
3031struct CachedReceipt {
3032    // `None` means "not found" by a full search.
3033    receipt: Option<EthTxReceipt>,
3034    // Head this result was computed against. Mutable entries (`None` and
3035    // non-final receipts) are only valid while the head is unchanged.
3036    head_key: TipsetKey,
3037    // A finalized receipt is immutable, so it is never invalidated.
3038    finalized: bool,
3039}
3040
3041fn is_finalized(ctx: &Ctx, head_epoch: ChainEpoch, receipt_epoch: ChainEpoch) -> bool {
3042    receipt_epoch <= head_epoch - ctx.chain_config().policy.chain_finality
3043}
3044
3045async fn get_eth_transaction_receipt_with_cache(
3046    ctx: Ctx,
3047    tx_hash: EthHash,
3048    limit: Option<ChainEpoch>,
3049    cancellation_token: &CancellationToken,
3050) -> Result<Option<EthTxReceipt>, ServerError> {
3051    static CACHE: LazyLock<SizeTrackingCache<EthHash, CachedReceipt>> = LazyLock::new(|| {
3052        const DEFAULT_CACHE_SIZE: NonZeroUsize = nonzero!(10000usize); // ~12.5MiB on mainnet
3053        let cache_size = env_or_default(
3054            "FOREST_ETH_TRANSACTION_RECEIPT_CACHE_SIZE",
3055            DEFAULT_CACHE_SIZE,
3056        );
3057        SizeTrackingCache::new_with_metrics("eth_transaction_receipt", cache_size)
3058    });
3059
3060    let head = ctx.chain_store().heaviest_tipset();
3061    let head_key = head.key().clone();
3062    let head_epoch = head.epoch();
3063
3064    // Drop stale mutable entries so they are recomputed at the new head.
3065    CACHE.remove_if(&tx_hash, |e| !e.finalized && e.head_key != head_key);
3066
3067    enum Uncacheable {
3068        // A bounded search found nothing; the receipt may still exist.
3069        NotFoundWithinLimit,
3070        Error(ServerError),
3071    }
3072
3073    let receipt = match CACHE
3074        .get_or_insert_async(&tx_hash, {
3075            let ctx = ctx.shallow_clone();
3076            let head_key = head_key.clone();
3077            async move {
3078                let receipt = get_eth_transaction_receipt(
3079                    ctx.shallow_clone(),
3080                    tx_hash,
3081                    limit,
3082                    cancellation_token,
3083                )
3084                .await
3085                .map_err(Uncacheable::Error)?;
3086                if receipt.is_none() && limit.is_some_and(|limit| limit > 0) {
3087                    return Err(Uncacheable::NotFoundWithinLimit);
3088                }
3089                let finalized = receipt
3090                    .as_ref()
3091                    .is_some_and(|r| is_finalized(&ctx, head.epoch(), r.block_number.0));
3092                Ok::<_, Uncacheable>(CachedReceipt {
3093                    receipt,
3094                    head_key,
3095                    finalized,
3096                })
3097            }
3098        })
3099        .await
3100    {
3101        Ok(CachedReceipt { receipt, .. }) => receipt,
3102        Err(Uncacheable::NotFoundWithinLimit) => None,
3103        Err(Uncacheable::Error(e)) => return Err(e),
3104    };
3105
3106    let Some(r) = receipt else { return Ok(None) };
3107    let within_lookback = StateManager::max_lookback_epoch_inclusive(head_epoch, limit)
3108        .is_some_and(|max| r.block_number.0 >= max);
3109    Ok(within_lookback.then_some(r))
3110}
3111
3112async fn get_eth_transaction_receipt(
3113    ctx: Ctx,
3114    tx_hash: EthHash,
3115    limit: Option<ChainEpoch>,
3116    cancellation_token: &CancellationToken,
3117) -> Result<Option<EthTxReceipt>, ServerError> {
3118    let msg_cid = ctx.chain_store().get_mapping(&tx_hash)?.unwrap_or_else(|| {
3119        tracing::debug!(
3120            "could not find transaction hash {} in Ethereum mapping",
3121            tx_hash
3122        );
3123        // This isn't an eth transaction we have the mapping for, so let's look it up as a filecoin message
3124        tx_hash.to_cid()
3125    });
3126
3127    let option = ctx
3128        .state_manager
3129        .search_for_message(None, msg_cid, limit, Some(true), cancellation_token)
3130        .await
3131        .with_context(|| format!("failed to lookup Eth Txn {tx_hash} as {msg_cid}"));
3132
3133    // Ethereum clients expect an empty response when the message was not found
3134    // or not executed yet
3135    let (tipset, receipt) = match option {
3136        Ok(Some(found)) => found,
3137        Ok(None) => return Ok(None),
3138        Err(e) => {
3139            tracing::debug!("could not find transaction receipt for hash {tx_hash}: {e:#}");
3140            return Ok(None);
3141        }
3142    };
3143    let ipld = receipt.return_data().deserialize().unwrap_or(Ipld::Null);
3144    let message_lookup = MessageLookup {
3145        receipt,
3146        tipset: tipset.key().clone(),
3147        height: tipset.epoch(),
3148        message: msg_cid,
3149        return_dec: ipld,
3150    };
3151
3152    let tx = new_eth_tx_from_message_lookup(&ctx, &message_lookup, None)
3153        .with_context(|| format!("failed to convert {tx_hash} into an Eth Tx"))?;
3154
3155    let ts = ctx
3156        .chain_index()
3157        .load_required_tipset(&message_lookup.tipset)?;
3158
3159    // The tx is located in the parent tipset
3160    let parent_ts = ctx
3161        .chain_index()
3162        .load_required_tipset(ts.parents())
3163        .map_err(|e| {
3164            format!(
3165                "failed to lookup tipset {} when constructing the eth txn receipt: {}",
3166                ts.parents(),
3167                e
3168            )
3169        })?;
3170
3171    let logs = if message_lookup.receipt.events_root().is_some() {
3172        eth_logs_for_block_and_transaction(&ctx, &parent_ts, &tx.block_hash, &msg_cid).await?
3173    } else {
3174        vec![]
3175    };
3176    let tx_receipt = new_eth_tx_receipt(&parent_ts, &tx, &message_lookup.receipt, logs)?;
3177
3178    Ok(Some(tx_receipt))
3179}
3180
3181pub enum EthGetTransactionReceipt {}
3182impl RpcMethod<1> for EthGetTransactionReceipt {
3183    const NAME: &'static str = "Filecoin.EthGetTransactionReceipt";
3184    const NAME_ALIAS: Option<&'static str> = Some("eth_getTransactionReceipt");
3185    const N_REQUIRED_PARAMS: usize = 1;
3186    const PARAM_NAMES: [&'static str; 1] = ["txHash"];
3187    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3188    const PERMISSION: Permission = Permission::Read;
3189    const DESCRIPTION: &'static str =
3190        "Returns the receipt of a transaction identified by its hash.";
3191    type Params = (EthHash,);
3192    type Ok = Option<EthTxReceipt>;
3193    async fn handle(
3194        ctx: Ctx,
3195        (tx_hash,): Self::Params,
3196        _: &http::Extensions,
3197    ) -> Result<Self::Ok, ServerError> {
3198        let cancellation_token = CancellationToken::new();
3199        let _drop_guard = cancellation_token.drop_guard_ref();
3200        get_eth_transaction_receipt_with_cache(ctx, tx_hash, None, &cancellation_token).await
3201    }
3202}
3203
3204pub enum EthGetTransactionReceiptLimited {}
3205impl RpcMethod<2> for EthGetTransactionReceiptLimited {
3206    const NAME: &'static str = "Filecoin.EthGetTransactionReceiptLimited";
3207    const NAME_ALIAS: Option<&'static str> = Some("eth_getTransactionReceiptLimited");
3208    const N_REQUIRED_PARAMS: usize = 1;
3209    const PARAM_NAMES: [&'static str; 2] = ["txHash", "limit"];
3210    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3211    const PERMISSION: Permission = Permission::Read;
3212    const DESCRIPTION: &'static str = "Returns the receipt of a transaction identified by its hash, limiting state resolution to the given chain epoch.";
3213    type Params = (EthHash, ChainEpoch);
3214    type Ok = Option<EthTxReceipt>;
3215    async fn handle(
3216        ctx: Ctx,
3217        (tx_hash, limit): Self::Params,
3218        _: &http::Extensions,
3219    ) -> Result<Self::Ok, ServerError> {
3220        let cancellation_token = CancellationToken::new();
3221        let _drop_guard = cancellation_token.drop_guard_ref();
3222        get_eth_transaction_receipt_with_cache(ctx, tx_hash, Some(limit), &cancellation_token).await
3223    }
3224}
3225
3226fn eth_tx_hash_and_signed_message(
3227    raw_tx: &EthBytes,
3228    eth_chain_id: EthChainIdType,
3229) -> anyhow::Result<(EthHash, SignedMessage)> {
3230    let tx_args =
3231        parse_eth_transaction(&raw_tx.0).context("failed to parse raw Ethereum transaction")?;
3232    let smsg = tx_args
3233        .get_signed_message(eth_chain_id)
3234        .context("failed to construct signed message from raw Ethereum transaction")?;
3235    // Same derivation `process_signed_messages` uses when re-indexing on mining.
3236    let tx_hash = eth_tx_hash_from_signed_message(&smsg, eth_chain_id)
3237        .context("failed to derive Ethereum transaction hash from signed message")?;
3238    Ok((tx_hash, smsg))
3239}
3240
3241/// Indexes a just-submitted tx immediately; `process_signed_messages` also indexes it once mined.
3242fn index_sent_tx(ctx: &Ctx, tx_hash: EthHash, cid: Cid) -> Result<(), ServerError> {
3243    ctx.chain_store()
3244        .put_mapping(tx_hash, cid, chrono::Utc::now().timestamp() as u64)?;
3245    Ok(())
3246}
3247
3248pub enum EthSendRawTransaction {}
3249impl RpcMethod<1> for EthSendRawTransaction {
3250    const NAME: &'static str = "Filecoin.EthSendRawTransaction";
3251    const NAME_ALIAS: Option<&'static str> = Some("eth_sendRawTransaction");
3252    const PARAM_NAMES: [&'static str; 1] = ["rawTx"];
3253    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3254    const PERMISSION: Permission = Permission::Read;
3255    const DESCRIPTION: &'static str =
3256        "Submits a signed raw transaction to the message pool and returns its transaction hash.";
3257
3258    type Params = (EthBytes,);
3259    type Ok = EthHash;
3260
3261    async fn handle(
3262        ctx: Ctx,
3263        (raw_tx,): Self::Params,
3264        _: &http::Extensions,
3265    ) -> Result<Self::Ok, ServerError> {
3266        let (tx_hash, smsg) =
3267            eth_tx_hash_and_signed_message(&raw_tx, ctx.chain_config().eth_chain_id)?;
3268        let cid = ctx.mpool.push(smsg).await?;
3269        index_sent_tx(&ctx, tx_hash, cid)?;
3270        Ok(tx_hash)
3271    }
3272}
3273
3274pub enum EthSendRawTransactionUntrusted {}
3275impl RpcMethod<1> for EthSendRawTransactionUntrusted {
3276    const NAME: &'static str = "Filecoin.EthSendRawTransactionUntrusted";
3277    const NAME_ALIAS: Option<&'static str> = Some("eth_sendRawTransactionUntrusted");
3278    const PARAM_NAMES: [&'static str; 1] = ["rawTx"];
3279    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3280    const PERMISSION: Permission = Permission::Read;
3281    const DESCRIPTION: &'static str = "Submits a signed raw transaction from an untrusted source to the message pool and returns its transaction hash.";
3282
3283    type Params = (EthBytes,);
3284    type Ok = EthHash;
3285
3286    async fn handle(
3287        ctx: Ctx,
3288        (raw_tx,): Self::Params,
3289        _: &http::Extensions,
3290    ) -> Result<Self::Ok, ServerError> {
3291        let (tx_hash, smsg) =
3292            eth_tx_hash_and_signed_message(&raw_tx, ctx.chain_config().eth_chain_id)?;
3293        let cid = ctx.mpool.push_untrusted(smsg).await?;
3294        index_sent_tx(&ctx, tx_hash, cid)?;
3295        Ok(tx_hash)
3296    }
3297}
3298
3299#[derive(Clone, Debug, PartialEq)]
3300pub struct CollectedEvent {
3301    pub(crate) entries: Vec<EventEntry>,
3302    pub(crate) emitter_addr: crate::shim::address::Address,
3303    pub(crate) event_idx: u64,
3304    pub(crate) reverted: bool,
3305    pub(crate) height: ChainEpoch,
3306    pub(crate) tipset_key: TipsetKey,
3307    msg_idx: u64,
3308    pub(crate) msg_cid: Cid,
3309}
3310
3311/// Positions `(message index, event index)` of collected events, grouped by tipset.
3312/// Identifies events without retaining their entry payloads; grouping by tipset lets
3313/// membership checks borrow the tipset key and stores each distinct key only once.
3314pub type SeenEventPositions = HashMap<TipsetKey, HashSet<(u64, u64)>>;
3315
3316fn match_key(key: &str) -> Option<usize> {
3317    match key.get(0..2) {
3318        Some("t1") => Some(0),
3319        Some("t2") => Some(1),
3320        Some("t3") => Some(2),
3321        Some("t4") => Some(3),
3322        _ => None,
3323    }
3324}
3325
3326fn eth_log_from_event(entries: &[EventEntry]) -> Option<(EthBytes, Vec<EthHash>)> {
3327    let mut topics_found = [false; 4];
3328    let mut topics_found_count = 0;
3329    let mut data_found = false;
3330    let mut data: EthBytes = EthBytes::default();
3331    let mut topics: Vec<EthHash> = Vec::default();
3332    for entry in entries {
3333        // Drop events with non-raw topics. Built-in actors emit CBOR, and anything else would be
3334        // invalid anyway.
3335        if entry.codec != IPLD_RAW {
3336            return None;
3337        }
3338        // Check if the key is t1..t4
3339        if let Some(idx) = match_key(&entry.key) {
3340            // Drop events with mis-sized topics.
3341            let result: Result<[u8; EVM_WORD_LENGTH], _> = entry.value.0.as_slice().try_into();
3342            let bytes = if let Ok(value) = result {
3343                value
3344            } else {
3345                tracing::warn!(
3346                    "got an EVM event topic with an invalid size (key: {}, size: {})",
3347                    entry.key,
3348                    entry.value.0.len()
3349                );
3350                return None;
3351            };
3352            // Drop events with duplicate topics.
3353            if *topics_found.get(idx).expect("Infallible") {
3354                tracing::warn!("got a duplicate EVM event topic (key: {})", entry.key);
3355                return None;
3356            }
3357            *topics_found.get_mut(idx).expect("Infallible") = true;
3358            topics_found_count += 1;
3359            // Extend the topics array
3360            if topics.len() <= idx {
3361                topics.resize(idx + 1, EthHash::default());
3362            }
3363            *topics.get_mut(idx).expect("Infallible") = bytes.into();
3364        } else if entry.key == "d" {
3365            // Drop events with duplicate data fields.
3366            if data_found {
3367                tracing::warn!("got duplicate EVM event data");
3368                return None;
3369            }
3370            data_found = true;
3371            data = EthBytes(entry.value.0.clone());
3372        } else {
3373            // Skip entries we don't understand (makes it easier to extend things).
3374            // But we warn for now because we don't expect them.
3375            tracing::warn!("unexpected event entry (key: {})", entry.key);
3376        }
3377    }
3378    // Drop events with skipped topics.
3379    if topics.len() != topics_found_count {
3380        tracing::warn!(
3381            "EVM event topic length mismatch (expected: {}, actual: {})",
3382            topics.len(),
3383            topics_found_count
3384        );
3385        return None;
3386    }
3387    Some((data, topics))
3388}
3389
3390pub(crate) fn eth_tx_hash_from_signed_message(
3391    message: &SignedMessage,
3392    eth_chain_id: EthChainIdType,
3393) -> anyhow::Result<EthHash> {
3394    if message.is_delegated() {
3395        let (_, tx) = eth_tx_from_signed_eth_message(message, eth_chain_id)?;
3396        Ok(tx.eth_hash()?.into())
3397    } else if message.is_secp256k1() {
3398        Ok(message.cid().into())
3399    } else {
3400        Ok(message.message().cid().into())
3401    }
3402}
3403
3404/// Returns the Ethereum transaction hash of the message at `message_cid`.
3405///
3406/// # Errors
3407/// Fails when the message can be read neither as a signed nor as an unsigned message. The error
3408/// names the CID and carries both read failures.
3409fn eth_tx_hash_from_message_cid<DB: Blockstore>(
3410    blockstore: &DB,
3411    message_cid: &Cid,
3412    eth_chain_id: EthChainIdType,
3413) -> anyhow::Result<EthHash> {
3414    let signed_err =
3415        match crate::chain::message_from_cid::<_, SignedMessage>(blockstore, message_cid) {
3416            // This is an Eth Tx, Secp message, Or BLS message in the mpool
3417            Ok(smsg) => return eth_tx_hash_from_signed_message(&smsg, eth_chain_id),
3418            Err(e) => e,
3419        };
3420    // An unsigned/BLS message fails signed decoding, so always try the fallback.
3421    match crate::chain::message_from_cid::<_, Message>(blockstore, message_cid) {
3422        // This is a BLS message
3423        Ok(_) => Ok((*message_cid).into()),
3424        Err(unsigned_err) => Err(anyhow!(
3425            "failed to load event message {message_cid}: {signed_err}; {unsigned_err}"
3426        )),
3427    }
3428}
3429
3430fn eth_filter_logs_from_tipsets(events: &[CollectedEvent]) -> anyhow::Result<Vec<EthHash>> {
3431    events
3432        .iter()
3433        .map(|event| event.tipset_key.cid().map(Into::into))
3434        .collect()
3435}
3436
3437fn eth_filter_logs_from_events(
3438    ctx: &Ctx,
3439    events: &[CollectedEvent],
3440) -> anyhow::Result<Vec<EthLog>> {
3441    let chain_id = ctx.state_manager.chain_config().eth_chain_id;
3442    let mut tx_hash_by_msg: HashMap<Cid, EthHash> = HashMap::new();
3443    let mut block_hash_by_tipset: HashMap<TipsetKey, EthHash> = HashMap::new();
3444    let mut eth_addr_by_emitter: HashMap<FilecoinAddress, EthAddress> = HashMap::new();
3445
3446    let mut logs = Vec::with_capacity(events.len());
3447    for event in events {
3448        let (data, topics) = match eth_log_from_event(&event.entries) {
3449            Some(parts) => parts,
3450            None => {
3451                tracing::debug!("Ignoring event");
3452                continue;
3453            }
3454        };
3455
3456        let transaction_hash = if let Some(h) = tx_hash_by_msg.get(&event.msg_cid) {
3457            *h
3458        } else {
3459            let h = eth_tx_hash_from_message_cid(ctx.db(), &event.msg_cid, chain_id)?;
3460            tx_hash_by_msg.insert(event.msg_cid, h);
3461            h
3462        };
3463
3464        let block_hash = if let Some(h) = block_hash_by_tipset.get(&event.tipset_key) {
3465            *h
3466        } else {
3467            let h: EthHash = event.tipset_key.cid()?.into();
3468            block_hash_by_tipset.insert(event.tipset_key.clone(), h);
3469            h
3470        };
3471
3472        let address = if let Some(a) = eth_addr_by_emitter.get(&event.emitter_addr) {
3473            *a
3474        } else {
3475            let a = EthAddress::from_filecoin_address(&event.emitter_addr)?;
3476            eth_addr_by_emitter.insert(event.emitter_addr, a);
3477            a
3478        };
3479
3480        logs.push(EthLog {
3481            address,
3482            data,
3483            topics,
3484            removed: event.reverted,
3485            log_index: event.event_idx.into(),
3486            transaction_index: event.msg_idx.into(),
3487            transaction_hash,
3488            block_hash,
3489            block_number: (event.height as u64).into(),
3490        });
3491    }
3492    Ok(logs)
3493}
3494
3495/// Accrues a single Ethereum log's address and topics into `bloom` using the standard `M3:2048` scheme.
3496fn eth_filter_result_from_events(
3497    ctx: &Ctx,
3498    events: &[CollectedEvent],
3499) -> anyhow::Result<EthFilterResult> {
3500    Ok(EthFilterResult::Logs(eth_filter_logs_from_events(
3501        ctx, events,
3502    )?))
3503}
3504
3505fn eth_filter_result_from_tipsets(events: &[CollectedEvent]) -> anyhow::Result<EthFilterResult> {
3506    Ok(EthFilterResult::Hashes(eth_filter_logs_from_tipsets(
3507        events,
3508    )?))
3509}
3510
3511pub enum EthGetLogs {}
3512impl RpcMethod<1> for EthGetLogs {
3513    const NAME: &'static str = "Filecoin.EthGetLogs";
3514    const NAME_ALIAS: Option<&'static str> = Some("eth_getLogs");
3515    const N_REQUIRED_PARAMS: usize = 1;
3516    const PARAM_NAMES: [&'static str; 1] = ["ethFilter"];
3517    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3518    const PERMISSION: Permission = Permission::Read;
3519    const DESCRIPTION: &'static str = "Returns event logs matching the given filter specification.";
3520    type Params = (EthFilterSpec,);
3521    type Ok = EthFilterResult;
3522    async fn handle(
3523        ctx: Ctx,
3524        (eth_filter,): Self::Params,
3525        _: &http::Extensions,
3526    ) -> Result<Self::Ok, ServerError> {
3527        let pf = Arc::new(
3528            ctx.eth_event_handler
3529                .parse_eth_filter_spec(&ctx, &eth_filter)
3530                .map_err(|e| {
3531                    if e.downcast_ref::<EthErrors>().is_some_and(|eth_err| {
3532                        matches!(eth_err, EthErrors::BlockRangeExceeded { .. })
3533                    }) {
3534                        return e;
3535                    }
3536                    e.context("failed to parse events for filter")
3537                })?,
3538        );
3539        let events = ctx
3540            .eth_event_handler
3541            .get_events_for_parsed_filter(&ctx, &pf, SkipEvent::OnUnresolvedAddress)
3542            .await
3543            .context("failed to get events for filter")?;
3544        Ok(eth_filter_result_from_events(&ctx, &events)?)
3545    }
3546}
3547
3548/// Shared implementation of `eth_getFilterLogs` / `eth_getFilterChanges` for installed event
3549/// filters: collects the filter's full result set from the canonical chain, returns only the
3550/// events that were not present in the previous poll.
3551async fn poll_event_filter(
3552    ctx: &Ctx,
3553    event_filter: &EventFilter,
3554) -> anyhow::Result<Vec<CollectedEvent>> {
3555    let events = ctx
3556        .eth_event_handler
3557        .get_events_for_parsed_filter(
3558            ctx,
3559            &Arc::new(event_filter.into()),
3560            SkipEvent::OnUnresolvedAddress,
3561        )
3562        .await?;
3563    Ok(event_filter.take_unseen(events))
3564}
3565
3566pub enum EthGetFilterLogs {}
3567impl RpcMethod<1> for EthGetFilterLogs {
3568    const NAME: &'static str = "Filecoin.EthGetFilterLogs";
3569    const NAME_ALIAS: Option<&'static str> = Some("eth_getFilterLogs");
3570    const N_REQUIRED_PARAMS: usize = 1;
3571    const PARAM_NAMES: [&'static str; 1] = ["filterId"];
3572    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3573    const PERMISSION: Permission = Permission::Write;
3574    const DESCRIPTION: &'static str = "Returns event logs matching the filter with the given ID that have not been collected since the last poll.";
3575    type Params = (FilterID,);
3576    type Ok = EthFilterResult;
3577    async fn handle(
3578        ctx: Ctx,
3579        (filter_id,): Self::Params,
3580        _: &http::Extensions,
3581    ) -> Result<Self::Ok, ServerError> {
3582        let eth_event_handler = ctx.eth_event_handler.clone();
3583        if let Some(store) = &eth_event_handler.filter_store {
3584            let filter = store.get(&filter_id)?;
3585            if let Some(event_filter) = filter.as_any().downcast_ref::<EventFilter>() {
3586                let recent_events = poll_event_filter(&ctx, event_filter).await?;
3587                return Ok(eth_filter_result_from_events(&ctx, &recent_events)?);
3588            }
3589        }
3590        Err(anyhow::anyhow!("method not supported").into())
3591    }
3592}
3593
3594pub enum EthGetFilterChanges {}
3595impl RpcMethod<1> for EthGetFilterChanges {
3596    const NAME: &'static str = "Filecoin.EthGetFilterChanges";
3597    const NAME_ALIAS: Option<&'static str> = Some("eth_getFilterChanges");
3598    const N_REQUIRED_PARAMS: usize = 1;
3599    const PARAM_NAMES: [&'static str; 1] = ["filterId"];
3600    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3601    const PERMISSION: Permission = Permission::Write;
3602    const DESCRIPTION: &'static str = "Returns event logs which occurred since the last poll";
3603
3604    type Params = (FilterID,);
3605    type Ok = EthFilterResult;
3606    async fn handle(
3607        ctx: Ctx,
3608        (filter_id,): Self::Params,
3609        _: &http::Extensions,
3610    ) -> Result<Self::Ok, ServerError> {
3611        let eth_event_handler = ctx.eth_event_handler.clone();
3612        if let Some(store) = &eth_event_handler.filter_store {
3613            let filter = store.get(&filter_id)?;
3614            if let Some(event_filter) = filter.as_any().downcast_ref::<EventFilter>() {
3615                let recent_events = poll_event_filter(&ctx, event_filter).await?;
3616                return Ok(eth_filter_result_from_events(&ctx, &recent_events)?);
3617            }
3618            if let Some(tipset_filter) = filter.as_any().downcast_ref::<TipSetFilter>() {
3619                let events = ctx
3620                    .eth_event_handler
3621                    .get_events_for_parsed_filter(
3622                        &ctx,
3623                        &Arc::new(ParsedFilter::new_with_tipset(ParsedFilterTipsets::Range(
3624                            // heaviest tipset doesn't have events because its messages haven't been executed yet
3625                            RangeInclusive::new(
3626                                tipset_filter.collected().unwrap_or_else(|| {
3627                                    ctx.chain_store().heaviest_tipset().epoch() - 1
3628                                }),
3629                                // Use -1 to indicate that the range extends until the latest available tipset.
3630                                -1,
3631                            ),
3632                        ))),
3633                        SkipEvent::OnUnresolvedAddress,
3634                    )
3635                    .await?;
3636                let new_collected = events
3637                    .iter()
3638                    .max_by_key(|event| event.height)
3639                    .map(|e| e.height);
3640                if let Some(height) = new_collected {
3641                    tipset_filter.set_collected(height);
3642                }
3643                return Ok(eth_filter_result_from_tipsets(&events)?);
3644            }
3645            if let Some(mempool_filter) = filter.as_any().downcast_ref::<MempoolFilter>() {
3646                return Ok(EthFilterResult::Hashes(mempool_filter.drain()));
3647            }
3648        }
3649        Err(anyhow::anyhow!("method not supported").into())
3650    }
3651}
3652
3653pub enum EthTraceBlock {}
3654impl RpcMethod<1> for EthTraceBlock {
3655    const NAME: &'static str = "Filecoin.EthTraceBlock";
3656    const NAME_ALIAS: Option<&'static str> = Some("trace_block");
3657    const N_REQUIRED_PARAMS: usize = 1;
3658    const PARAM_NAMES: [&'static str; 1] = ["blockParam"];
3659    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
3660    const PERMISSION: Permission = Permission::Read;
3661    const DESCRIPTION: &'static str = "Returns traces created at given block.";
3662
3663    type Params = (BlockNumberOrHash,);
3664    type Ok = NotNullVec<EthBlockTrace>;
3665    async fn handle(
3666        ctx: Ctx,
3667        (block_param,): Self::Params,
3668        ext: &http::Extensions,
3669    ) -> Result<Self::Ok, ServerError> {
3670        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
3671        let ts = resolver
3672            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::Fail)
3673            .await?;
3674        let txs = eth_tipset_traces(&ctx.state_manager, &ts, CallSource::External).await?;
3675        Ok(NotNullVec(to_block_traces(&ts, txs.iter())?))
3676    }
3677}
3678
3679/// Replays a tipset and resolves every non-system transaction into a [`trace::TipsetTraceEntry`].
3680async fn execute_tipset_traces(
3681    state_manager: &StateManager,
3682    ts: &Tipset,
3683    source: CallSource,
3684) -> Result<(StateTree<DbImpl>, Vec<trace::TipsetTraceEntry>), ServerError> {
3685    let (state_root, raw_traces) = state_manager.execution_trace(ts, source).await?;
3686    let state = state_manager.get_state_tree(&state_root)?;
3687
3688    // Resolve every non-system message's tx hash in parallel. Each lookup is
3689    // an independent DB read; running them sequentially adds O(N) IO
3690    // latency to every trace_block response.
3691    let raw = non_system_traces_with_positions(raw_traces).collect_vec();
3692    let mut entries: Vec<trace::TipsetTraceEntry> = Vec::with_capacity(raw.len());
3693    let mut join_set = tokio::task::JoinSet::new();
3694    let db = state_manager.db();
3695    let eth_chain_id = state_manager.chain_config().eth_chain_id;
3696    for (msg_position, invoc_result) in raw {
3697        let db = db.shallow_clone();
3698        join_set.spawn_blocking(move || {
3699            let tx_hash = EthGetTransactionHashByCid::run(&db, eth_chain_id, invoc_result.msg_cid)?
3700                .with_context(|| {
3701                    format!(
3702                        "cannot find transaction hash for cid {}",
3703                        invoc_result.msg_cid
3704                    )
3705                })?;
3706            anyhow::Ok(trace::TipsetTraceEntry {
3707                tx_hash,
3708                msg_position,
3709                invoc_result,
3710            })
3711        });
3712    }
3713    while let Some(joined) = join_set.join_next().await {
3714        entries.push(joined.context("trace tx-hash task panicked")??);
3715    }
3716    entries.sort_by_key(|e| e.msg_position);
3717
3718    Ok((state, entries))
3719}
3720
3721/// Yields non-system traces paired with 0-indexed positions matching
3722/// `transactionIndex` from `eth_getBlockByNumber`. System-actor messages
3723/// are filtered out without consuming a position.
3724fn non_system_traces_with_positions(
3725    raw_traces: impl IntoIterator<Item = Arc<ApiInvocResult>>,
3726) -> impl Iterator<Item = (i64, Arc<ApiInvocResult>)> {
3727    raw_traces
3728        .into_iter()
3729        .filter(|ir| ir.msg.from() != system::ADDRESS.into())
3730        .enumerate()
3731        .map(|(idx, ir)| (idx as i64, ir))
3732}
3733
3734/// Builds the per-transaction Ethereum traces for `ts`, caching the result by tipset.
3735/// Unlike [`StateManager::execution_trace`], this also caches the tx-hash
3736/// lookups and parity-trace construction.
3737pub(crate) async fn eth_tipset_traces(
3738    state_manager: &StateManager,
3739    ts: &Tipset,
3740    source: CallSource,
3741) -> Result<Arc<Vec<EthTxTraces>>, ServerError> {
3742    state_manager
3743        .eth_trace_cache()
3744        .get_or_insert_async(ts.key(), async move {
3745            let (state, entries) = execute_tipset_traces(state_manager, ts, source).await?;
3746            entries
3747                .into_iter()
3748                .map(|entry| {
3749                    Ok(EthTxTraces {
3750                        traces: entry.build_parity_traces(&state)?,
3751                        tx_hash: entry.tx_hash,
3752                        msg_position: entry.msg_position,
3753                    })
3754                })
3755                .collect::<Result<Vec<_>, ServerError>>()
3756                .map(Arc::new)
3757        })
3758        .await
3759}
3760
3761/// Flattens the traces of `txs`, all belonging to `ts`, into block traces.
3762fn to_block_traces<'a>(
3763    ts: &Tipset,
3764    txs: impl Iterator<Item = &'a EthTxTraces>,
3765) -> Result<Vec<EthBlockTrace>> {
3766    let block_hash: EthHash = ts.key().cid()?.into();
3767    Ok(txs
3768        .flat_map(|tx| tx.block_traces(block_hash, ts.epoch()))
3769        .collect_vec())
3770}
3771
3772pub enum EthDebugTraceTransaction {}
3773impl RpcMethod<2> for EthDebugTraceTransaction {
3774    const N_REQUIRED_PARAMS: usize = 1;
3775    const NAME: &'static str = "Forest.EthDebugTraceTransaction";
3776    const NAME_ALIAS: Option<&'static str> = Some("debug_traceTransaction");
3777    const PARAM_NAMES: [&'static str; 2] = ["txHash", "opts"];
3778    const API_PATHS: BitFlags<ApiPaths> = make_bitflags!(ApiPaths::{ V1 | V2 });
3779    const PERMISSION: Permission = Permission::Read;
3780    const DESCRIPTION: &'static str =
3781        "Replays a transaction and returns execution traces in Geth-compatible format.";
3782
3783    type Params = (String, Option<GethDebugTracingOptions>);
3784    type Ok = GethTrace;
3785
3786    async fn handle(
3787        ctx: Ctx,
3788        (tx_hash, opts): Self::Params,
3789        ext: &http::Extensions,
3790    ) -> Result<Self::Ok, ServerError> {
3791        let opts = opts.unwrap_or_default();
3792        let cancellation_token = CancellationToken::new();
3793        let _drop_guard = cancellation_token.drop_guard_ref();
3794        debug_trace_transaction(
3795            ctx,
3796            Self::api_path(ext)?,
3797            tx_hash,
3798            opts,
3799            &cancellation_token,
3800            CallSource::External,
3801        )
3802        .await
3803    }
3804}
3805
3806async fn debug_trace_transaction(
3807    ctx: Ctx,
3808    api_path: ApiPaths,
3809    tx_hash: String,
3810    opts: GethDebugTracingOptions,
3811    cancellation_token: &CancellationToken,
3812    source: CallSource,
3813) -> Result<GethTrace, ServerError> {
3814    let tracer = match &opts.tracer {
3815        Some(t) => t.clone(),
3816        None => {
3817            tracing::debug!(
3818                "no tracer specified for debug_traceTransaction; defaulting to callTracer (struct logger not supported)"
3819            );
3820            GethDebugBuiltInTracerType::Call
3821        }
3822    };
3823
3824    let eth_hash = EthHash::from_str(&tx_hash).context("invalid transaction hash")?;
3825    let eth_txn = get_eth_transaction_by_hash(&ctx, &eth_hash, None, cancellation_token)
3826        .await?
3827        .ok_or_else(|| ServerError::internal_error("transaction not found", None))?;
3828
3829    // Mempool/pending transactions cannot be traced — they have no containing tipset.
3830    if eth_txn.block_hash == EthHash::default() {
3831        return Err(ServerError::invalid_params(
3832            "no trace for pending transactions",
3833            None,
3834        ));
3835    }
3836
3837    if tracer == GethDebugBuiltInTracerType::Noop {
3838        return Ok(GethTrace::Noop(NoopFrame {}));
3839    }
3840
3841    let resolver = TipsetResolver::new(&ctx, api_path);
3842    let ts = resolver
3843        .tipset_by_block_number_or_hash(eth_txn.block_number, ResolveNullTipset::TakeOlder)
3844        .await?;
3845
3846    // prestateTracer uses per-message replay for exact state boundaries,
3847    // so it does not need the full tipset trace.
3848    if tracer == GethDebugBuiltInTracerType::PreState {
3849        let prestate_config = opts.prestate_config()?;
3850
3851        let message_cid = ctx
3852            .chain_store()
3853            .get_mapping(&eth_hash)?
3854            .unwrap_or_else(|| eth_hash.to_cid());
3855
3856        let (pre_root, invoc_result, post_root) = ctx
3857            .state_manager
3858            .replay_for_prestate(ts.shallow_clone(), message_cid)
3859            .await
3860            .map_err(|e| anyhow::anyhow!("replay for prestate failed: {e}"))?;
3861
3862        let execution_trace = invoc_result
3863            .execution_trace
3864            .context("no execution trace for transaction")?;
3865
3866        let mut touched = extract_touched_eth_addresses(&execution_trace);
3867        if let Ok(addr) = EthAddress::from_filecoin_address(&invoc_result.msg.from()) {
3868            touched.insert(addr);
3869        }
3870
3871        if let Ok(addr) = EthAddress::from_filecoin_address(&invoc_result.msg.to()) {
3872            touched.insert(addr);
3873        }
3874
3875        let pre_state = StateTree::new_from_root(ctx.db(), &pre_root)?;
3876        let post_state = StateTree::new_from_root(ctx.db(), &post_root)?;
3877
3878        let frame = trace::build_prestate_frame(
3879            ctx.db(),
3880            &pre_state,
3881            &post_state,
3882            &touched,
3883            &prestate_config,
3884        )?;
3885
3886        return Ok(GethTrace::PreState(frame));
3887    }
3888
3889    let (state, entries) = execute_tipset_traces(&ctx.state_manager, &ts, source).await?;
3890    let entry = entries
3891        .into_iter()
3892        .find(|e| e.tx_hash == eth_hash)
3893        .ok_or_else(|| ServerError::internal_error("transaction trace not found in block", None))?;
3894
3895    let execution_trace = entry
3896        .invoc_result
3897        .execution_trace
3898        .clone()
3899        .context("no execution trace for transaction")?;
3900
3901    let mut env = trace::base_environment(&state, &entry.invoc_result.msg.from()).map_err(|e| {
3902        anyhow::anyhow!(
3903            "when processing message {}: {e}",
3904            entry.invoc_result.msg_cid
3905        )
3906    })?;
3907
3908    match tracer {
3909        GethDebugBuiltInTracerType::Call => {
3910            let call_config = opts.call_config()?;
3911            let frame = trace::build_geth_call_frame(&mut env, execution_trace, &call_config)?;
3912            Ok(GethTrace::Call(frame.unwrap_or_default()))
3913        }
3914        GethDebugBuiltInTracerType::FlatCall => {
3915            trace::build_traces(&mut env, &[], execution_trace)?;
3916            let block_hash: EthHash = ts.key().cid()?.into();
3917            let traces = env
3918                .traces
3919                .into_iter()
3920                .map(|t| EthBlockTrace {
3921                    trace: t,
3922                    block_hash,
3923                    block_number: ts.epoch(),
3924                    transaction_hash: eth_hash,
3925                    transaction_position: entry.msg_position,
3926                })
3927                .collect();
3928            Ok(GethTrace::FlatCall(traces))
3929        }
3930        _ => Err(anyhow::anyhow!(
3931            "unexpected tracer type: noopTracer and prestateTracer should be handled above"
3932        )
3933        .into()),
3934    }
3935}
3936
3937pub enum EthTraceCall {}
3938impl RpcMethod<3> for EthTraceCall {
3939    const NAME: &'static str = "Forest.EthTraceCall";
3940    const NAME_ALIAS: Option<&'static str> = Some("trace_call");
3941    const N_REQUIRED_PARAMS: usize = 1;
3942    const PARAM_NAMES: [&'static str; 3] = ["tx", "traceTypes", "blockParam"];
3943    const API_PATHS: BitFlags<ApiPaths> = make_bitflags!(ApiPaths::{ V1 | V2 });
3944    const PERMISSION: Permission = Permission::Read;
3945    const DESCRIPTION: &'static str =
3946        "Returns parity style trace results for the given transaction.";
3947
3948    type Params = (
3949        EthCallMessage,
3950        NonEmpty<EthTraceType>,
3951        Option<BlockNumberOrHash>,
3952    );
3953    type Ok = EthTraceResults;
3954    async fn handle(
3955        ctx: Ctx,
3956        (tx, trace_types, block_param): Self::Params,
3957        ext: &http::Extensions,
3958    ) -> Result<Self::Ok, ServerError> {
3959        let msg = Message::try_from(tx)?;
3960        let block_param = block_param.unwrap_or_else(|| Predefined::Latest.into());
3961        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
3962        let ts = resolver
3963            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::TakeOlder)
3964            .await?;
3965
3966        let TipsetState {
3967            state_root: pre_state_root,
3968            ..
3969        } = ctx
3970            .state_manager
3971            .load_tipset_state(&ts)
3972            .await
3973            .context("failed to get tipset state")?;
3974        let pre_state = StateTree::new_from_root(ctx.db(), &pre_state_root)?;
3975
3976        let (invoke_result, post_state_root) = apply_on_state_accepting_any_sender(
3977            &ctx,
3978            Some(&ts),
3979            &msg,
3980            VMFlush::Flush,
3981            VMTrace::Traced,
3982        )
3983        .await?;
3984        let post_state_root =
3985            post_state_root.context("post-execution state root required for trace call")?;
3986        let post_state = StateTree::new_from_root(ctx.db(), &post_state_root)?;
3987
3988        let mut trace_results = EthTraceResults {
3989            output: get_trace_output(&msg, &invoke_result)?,
3990            ..Default::default()
3991        };
3992
3993        // Extract touched addresses for state diff (do this before consuming exec_trace)
3994        let touched_addresses = invoke_result
3995            .execution_trace
3996            .as_ref()
3997            .map(extract_touched_eth_addresses)
3998            .unwrap_or_default();
3999
4000        // Build call traces if requested
4001        if trace_types.contains(&EthTraceType::Trace)
4002            && let Some(exec_trace) = invoke_result.execution_trace
4003        {
4004            let mut env = trace::base_environment(&post_state, &msg.from())
4005                .context("failed to create trace environment")?;
4006            trace::build_traces(&mut env, &[], exec_trace)?;
4007            trace_results.trace = env.traces;
4008        }
4009
4010        // Build state diff if requested
4011        if trace_types.contains(&EthTraceType::StateDiff) {
4012            // Add the caller address to touched addresses
4013            let mut all_touched = touched_addresses;
4014            if let Ok(caller_eth) = EthAddress::from_filecoin_address(&msg.from()) {
4015                all_touched.insert(caller_eth);
4016            }
4017            if let Ok(to_eth) = EthAddress::from_filecoin_address(&msg.to()) {
4018                all_touched.insert(to_eth);
4019            }
4020
4021            let state_diff =
4022                trace::build_state_diff(ctx.db(), &pre_state, &post_state, &all_touched)?;
4023            trace_results.state_diff = Some(state_diff);
4024        }
4025
4026        Ok(trace_results)
4027    }
4028}
4029
4030/// Get output bytes from trace execution result.
4031fn get_trace_output(msg: &Message, invoke_result: &ApiInvocResult) -> Result<EthBytes> {
4032    if msg.to() == FilecoinAddress::ETHEREUM_ACCOUNT_MANAGER_ACTOR {
4033        return Ok(EthBytes::default());
4034    }
4035
4036    let msg_rct = invoke_result
4037        .msg_rct
4038        .as_ref()
4039        .context("missing message receipt")?;
4040    let return_data = msg_rct.return_data();
4041
4042    if return_data.is_empty() {
4043        return Ok(EthBytes::default());
4044    }
4045
4046    decode_payload(&return_data, CBOR).context("failed to decode return data")
4047}
4048
4049/// Extract all unique Ethereum addresses touched during execution from the trace.
4050fn extract_touched_eth_addresses(trace: &crate::rpc::state::ExecutionTrace) -> HashSet<EthAddress> {
4051    let mut addresses = HashSet::default();
4052    let mut stack = vec![trace];
4053
4054    while let Some(current) = stack.pop() {
4055        if let Ok(eth_addr) = EthAddress::from_filecoin_address(&current.msg.from) {
4056            addresses.insert(eth_addr);
4057        }
4058        if let Ok(eth_addr) = EthAddress::from_filecoin_address(&current.msg.to) {
4059            addresses.insert(eth_addr);
4060        }
4061        stack.extend(&current.subcalls);
4062    }
4063
4064    addresses
4065}
4066
4067pub enum EthTraceTransaction {}
4068impl RpcMethod<1> for EthTraceTransaction {
4069    const NAME: &'static str = "Filecoin.EthTraceTransaction";
4070    const NAME_ALIAS: Option<&'static str> = Some("trace_transaction");
4071    const N_REQUIRED_PARAMS: usize = 1;
4072    const PARAM_NAMES: [&'static str; 1] = ["txHash"];
4073    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
4074    const PERMISSION: Permission = Permission::Read;
4075    const DESCRIPTION: &'static str = "Returns the traces for a specific transaction.";
4076
4077    type Params = (String,);
4078    type Ok = NotNullVec<EthBlockTrace>;
4079    async fn handle(
4080        ctx: Ctx,
4081        (tx_hash,): Self::Params,
4082        ext: &http::Extensions,
4083    ) -> Result<Self::Ok, ServerError> {
4084        let cancellation_token = CancellationToken::new();
4085        let _drop_guard = cancellation_token.drop_guard_ref();
4086        let eth_hash = EthHash::from_str(&tx_hash).context("invalid transaction hash")?;
4087        let eth_txn = get_eth_transaction_by_hash(&ctx, &eth_hash, None, &cancellation_token)
4088            .await?
4089            .ok_or_else(|| ServerError::internal_error("transaction not found", None))?;
4090
4091        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
4092        let ts = resolver
4093            .tipset_by_block_number_or_hash(eth_txn.block_number, ResolveNullTipset::TakeOlder)
4094            .await?;
4095
4096        let txs = eth_tipset_traces(&ctx.state_manager, &ts, CallSource::External).await?;
4097        let traces = to_block_traces(&ts, txs.iter().filter(|tx| tx.tx_hash == eth_hash))?;
4098        Ok(NotNullVec(traces))
4099    }
4100}
4101
4102pub enum EthTraceReplayBlockTransactions {}
4103impl RpcMethod<2> for EthTraceReplayBlockTransactions {
4104    const N_REQUIRED_PARAMS: usize = 2;
4105    const NAME: &'static str = "Filecoin.EthTraceReplayBlockTransactions";
4106    const NAME_ALIAS: Option<&'static str> = Some("trace_replayBlockTransactions");
4107    const PARAM_NAMES: [&'static str; 2] = ["blockParam", "traceTypes"];
4108    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
4109    const PERMISSION: Permission = Permission::Read;
4110    const DESCRIPTION: &'static str =
4111        "Replays all transactions in a block returning the requested traces for each transaction.";
4112
4113    type Params = (BlockNumberOrHash, Vec<String>);
4114    type Ok = NotNullVec<EthReplayBlockTransactionTrace>;
4115
4116    async fn handle(
4117        ctx: Ctx,
4118        (block_param, trace_types): Self::Params,
4119        ext: &http::Extensions,
4120    ) -> Result<Self::Ok, ServerError> {
4121        if trace_types.as_slice() != ["trace"] {
4122            return Err(ServerError::invalid_params(
4123                "only 'trace' is supported",
4124                None,
4125            ));
4126        }
4127
4128        let resolver = TipsetResolver::new(&ctx, Self::api_path(ext)?);
4129        let ts = resolver
4130            .tipset_by_block_number_or_hash(block_param, ResolveNullTipset::Fail)
4131            .await?;
4132
4133        let txs = eth_tipset_traces(&ctx.state_manager, &ts, CallSource::External).await?;
4134        Ok(NotNullVec(
4135            txs.iter()
4136                .map(|tx| EthReplayBlockTransactionTrace {
4137                    full_trace: EthTraceResults::from_parity_traces(tx.traces.clone()),
4138                    transaction_hash: tx.tx_hash,
4139                    vm_trace: None,
4140                })
4141                .collect_vec(),
4142        ))
4143    }
4144}
4145
4146async fn get_eth_block_number_from_string(
4147    ctx: &Ctx,
4148    block: Option<&str>,
4149    resolve: ResolveNullTipset,
4150    api_path: ApiPaths,
4151) -> Result<EthUint64> {
4152    let block_param = block
4153        .map(BlockNumberOrHash::from_str)
4154        .transpose()?
4155        .unwrap_or(BlockNumberOrHash::PredefinedBlock(Predefined::Latest));
4156    let resolver = TipsetResolver::new(ctx, api_path);
4157    Ok(EthUint64(
4158        resolver
4159            .tipset_by_block_number_or_hash(block_param, resolve)
4160            .await?
4161            .epoch() as u64,
4162    ))
4163}
4164
4165pub enum EthTraceFilter {}
4166impl RpcMethod<1> for EthTraceFilter {
4167    const N_REQUIRED_PARAMS: usize = 1;
4168    const NAME: &'static str = "Filecoin.EthTraceFilter";
4169    const NAME_ALIAS: Option<&'static str> = Some("trace_filter");
4170    const PARAM_NAMES: [&'static str; 1] = ["filter"];
4171    const API_PATHS: BitFlags<ApiPaths> = ApiPaths::all_with_v2();
4172    const PERMISSION: Permission = Permission::Read;
4173    const DESCRIPTION: &'static str =
4174        "Returns the traces for transactions matching the filter criteria.";
4175    type Params = (EthTraceFilterCriteria,);
4176    type Ok = NotNullVec<EthBlockTrace>;
4177
4178    async fn handle(
4179        ctx: Ctx,
4180        (filter,): Self::Params,
4181        ext: &http::Extensions,
4182    ) -> Result<Self::Ok, ServerError> {
4183        let api_path = Self::api_path(ext)?;
4184        let from_block = get_eth_block_number_from_string(
4185            &ctx,
4186            filter.from_block.as_deref(),
4187            ResolveNullTipset::TakeNewer,
4188            api_path,
4189        )
4190        .await
4191        .context("cannot parse fromBlock")?;
4192
4193        let to_block = get_eth_block_number_from_string(
4194            &ctx,
4195            filter.to_block.as_deref(),
4196            ResolveNullTipset::TakeOlder,
4197            api_path,
4198        )
4199        .await
4200        .context("cannot parse toBlock")?;
4201
4202        let max_block_range = ctx.eth_event_handler.max_filter_height_range;
4203        if max_block_range > 0 && to_block.0 > from_block.0 {
4204            let range = i64::try_from(to_block.0.saturating_sub(from_block.0))
4205                .context("block range overflow")?;
4206            if range > max_block_range {
4207                return Err(EthErrors::limit_exceeded(max_block_range, range).into());
4208            }
4209        }
4210        Ok(NotNullVec(
4211            trace_filter(ctx, filter, from_block, to_block, ext).await?,
4212        ))
4213    }
4214}
4215
4216async fn trace_filter(
4217    ctx: Ctx,
4218    filter: EthTraceFilterCriteria,
4219    from_block: EthUint64,
4220    to_block: EthUint64,
4221    ext: &http::Extensions,
4222) -> Result<Vec<EthBlockTrace>> {
4223    let mut results = HashSet::default();
4224    if let Some(EthUint64(0)) = filter.count {
4225        return Ok(Vec::new());
4226    }
4227    let count = *filter.count.unwrap_or_default();
4228    ensure!(
4229        count <= *FOREST_TRACE_FILTER_MAX_RESULT,
4230        "invalid response count, requested {}, maximum supported is {}",
4231        count,
4232        *FOREST_TRACE_FILTER_MAX_RESULT
4233    );
4234
4235    let mut trace_counter = 0;
4236    'blocks: for blk_num in from_block.0..=to_block.0 {
4237        // For BlockNumber, EthTraceBlock and EthTraceBlockV2 are equivalent.
4238        let block_traces = match EthTraceBlock::handle(
4239            ctx.clone(),
4240            (BlockNumberOrHash::from_block_number(blk_num as i64),),
4241            ext,
4242        )
4243        .await
4244        {
4245            Ok(block_traces) => block_traces,
4246            Err(e) if e.code() == NULL_ROUND_CODE => continue 'blocks,
4247            Err(e) => return Err(e.into()),
4248        };
4249        for block_trace in block_traces.0 {
4250            if block_trace
4251                .trace
4252                .match_filter_criteria(filter.from_address.as_ref(), filter.to_address.as_ref())?
4253            {
4254                trace_counter += 1;
4255                if let Some(after) = filter.after
4256                    && trace_counter <= after.0
4257                {
4258                    continue;
4259                }
4260
4261                results.insert(block_trace);
4262
4263                if filter.count.is_some() && results.len() >= count as usize {
4264                    break 'blocks;
4265                } else if results.len() > *FOREST_TRACE_FILTER_MAX_RESULT as usize {
4266                    bail!(
4267                        "too many results, maximum supported is {}, try paginating requests with After and Count",
4268                        *FOREST_TRACE_FILTER_MAX_RESULT
4269                    );
4270                }
4271            }
4272        }
4273    }
4274
4275    Ok(results
4276        .into_iter()
4277        .sorted_unstable_by(|a, b| a.sort_key().cmp(&b.sort_key()))
4278        .collect_vec())
4279}
4280
4281#[cfg(test)]
4282mod test {
4283    use super::*;
4284    use crate::rpc::eth::EventEntry;
4285    use crate::rpc::state::{ExecutionTrace, MessageTrace, ReturnTrace};
4286    use crate::shim::actors::evm::EVM_CONTRACT_REVERTED;
4287    use crate::shim::fvm_shared_latest::event::Flags;
4288    use crate::shim::{econ::TokenAmount, error::ExitCode};
4289    use crate::{
4290        db::MemoryDB,
4291        test_utils::{construct_bls_messages, construct_eth_messages, construct_messages},
4292    };
4293    use jsonrpsee::types::error::INTERNAL_ERROR_CODE;
4294    use quickcheck::Arbitrary;
4295    use quickcheck_macros::quickcheck;
4296    use rstest::rstest;
4297
4298    impl Arbitrary for EthHash {
4299        fn arbitrary(g: &mut quickcheck::Gen) -> Self {
4300            let arr: [u8; 32] = std::array::from_fn(|_ix| u8::arbitrary(g));
4301            Self(ethereum_types::H256(arr))
4302        }
4303    }
4304
4305    #[test]
4306    fn execution_reverted_from_receipt_decodes_reason_and_data() {
4307        // A receipt carries its return payload CBOR-wrapped. The `Error(string)` ABI decode is
4308        // covered by `eth/utils.rs`; here a non-ABI payload (which decodes to hex) is enough to
4309        // check that the helper threads reason, data, exit code and vm error through.
4310        let payload = b"Ph'nglui mglw'nafh Cthulhu R'lyeh wgah'nagl fhtagn".to_vec();
4311        let return_data =
4312            RawBytes::new(fvm_ipld_encoding::to_vec(&RawBytes::new(payload.clone())).unwrap());
4313        let receipt = Receipt::V4(fvm_shared4::receipt::Receipt {
4314            exit_code: EVM_CONTRACT_REVERTED.into(),
4315            return_data,
4316            gas_used: 0,
4317            events_root: None,
4318        });
4319
4320        let err = EthErrors::execution_reverted_from_result(
4321            receipt.exit_code(),
4322            receipt.return_data(),
4323            "backtrace",
4324        );
4325        let EthErrors::ExecutionReverted { message, data } = err.clone() else {
4326            panic!("expected ExecutionReverted, got {err:?}");
4327        };
4328        let payload_hex = hex::encode_prefixed(&payload);
4329        assert_eq!(
4330            message,
4331            format!(
4332                "message execution failed (exit=[33], revert reason=[{payload_hex}], vm error=[backtrace])"
4333            )
4334        );
4335        assert_eq!(data, payload_hex);
4336
4337        // Surfaces to eth clients as the standard code-3 execution-reverted error.
4338        let server: ServerError = err.into();
4339        assert_eq!(server.code(), errors::EXECUTION_REVERTED_CODE);
4340    }
4341
4342    fn invoc_result_with_exit_code(exit_code: fvm_shared4::error::ExitCode) -> ApiInvocResult {
4343        ApiInvocResult {
4344            msg_rct: Some(Receipt::V4(fvm_shared4::receipt::Receipt {
4345                exit_code,
4346                return_data: RawBytes::default(),
4347                gas_used: 0,
4348                events_root: None,
4349            })),
4350            ..Default::default()
4351        }
4352    }
4353
4354    #[test]
4355    fn needs_skip_sender_covers_both_shapes_of_sender_rejection() {
4356        assert!(needs_skip_sender(&Err(
4357            crate::state_manager::Error::SenderValidationFailed("sender t410f... not found".into())
4358                .into()
4359        )));
4360
4361        assert!(needs_skip_sender(&Ok((
4362            invoc_result_with_exit_code(fvm_shared4::error::ExitCode::SYS_SENDER_INVALID),
4363            None
4364        ))));
4365
4366        assert!(!needs_skip_sender(&Ok((
4367            invoc_result_with_exit_code(fvm_shared4::error::ExitCode::USR_ASSERTION_FAILED),
4368            None
4369        ))));
4370        assert!(!needs_skip_sender(&Ok((
4371            invoc_result_with_exit_code(fvm_shared4::error::ExitCode::OK),
4372            None
4373        ))));
4374        assert!(!needs_skip_sender(&Err(anyhow::anyhow!(
4375            "blockstore read failed"
4376        ))));
4377        assert!(!needs_skip_sender(&Ok((ApiInvocResult::default(), None))));
4378    }
4379
4380    /// An `ApplyRet` that exited with `exit_code` after charging `gas_used`; zero gas means preflight
4381    /// rejected it before it ran.
4382    fn apply_ret(exit_code: u32, gas_used: u64) -> ApplyRet {
4383        use crate::shim::fvm_shared_latest;
4384        let mut ret = crate::shim::fvm_latest::executor::ApplyRet::prevalidation_fail(
4385            fvm_shared_latest::error::ExitCode::new(exit_code),
4386            "",
4387            fvm_shared_latest::econ::TokenAmount::default(),
4388        );
4389        ret.msg_receipt.gas_used = gas_used;
4390        ApplyRet::V4(ret)
4391    }
4392
4393    #[rstest]
4394    #[case::below_inclusion_cost(ExitCode::SYS_OUT_OF_GAS.value(), 0, errors::INVALID_INPUT_CODE)]
4395    #[case::non_gas_preflight_rejection(ExitCode::SYS_INSUFFICIENT_FUNDS.value(), 0, errors::EXECUTION_REVERTED_CODE)]
4396    #[case::out_of_gas_while_executing(ExitCode::SYS_OUT_OF_GAS.value(), 1, errors::TRANSACTION_REJECTED_CODE)]
4397    #[case::revert_while_executing(EVM_CONTRACT_REVERTED.value(), 1, errors::TRANSACTION_REJECTED_CODE)]
4398    fn gas_cap_error_tells_preflight_from_execution(
4399        #[case] exit_code: u32,
4400        #[case] gas_used: u64,
4401        #[case] expected_code: i32,
4402    ) {
4403        let err: ServerError = gas_cap_error(&apply_ret(exit_code, gas_used), 1000).into();
4404        assert_eq!(err.code(), expected_code);
4405    }
4406
4407    #[rstest]
4408    #[case::out_of_gas(EthErrors::OutOfGas.into(), errors::TRANSACTION_REJECTED_CODE, "out of gas: gas required exceeds: 1000")]
4409    #[case::revert(EthErrors::execution_reverted(EVM_CONTRACT_REVERTED, "", "", &[]).into(), errors::EXECUTION_REVERTED_CODE, "message execution failed (exit=[33], vm error=[])")]
4410    #[case::untyped_keeps_the_cause_chain(anyhow::anyhow!("blockstore read failed").context("gas estimation failed"), INTERNAL_ERROR_CODE, "failed to estimate gas: gas estimation failed: blockstore read failed")]
4411    fn estimate_gas_error_keeps_codes_and_causes(
4412        #[case] err: anyhow::Error,
4413        #[case] code: i32,
4414        #[case] message: &str,
4415    ) {
4416        let err = estimate_gas_error(err, 1000);
4417        assert_eq!(err.code(), code);
4418        assert_eq!(err.message(), message);
4419    }
4420
4421    #[rstest]
4422    #[case::affordable(1_000_000, 0, 1, 1_000_000)]
4423    #[case::value_reduces_allowance(1_000_000, 400_000, 2, 300_000)] // (1_000_000 - 400_000) / 2
4424    #[case::capped_at_block_gas_limit(u128::from(BLOCK_GAS_LIMIT) * 2, 0, 1, BLOCK_GAS_LIMIT)]
4425    #[case::beyond_u64(u128::MAX, 0, 1, BLOCK_GAS_LIMIT)]
4426    fn gas_allowance_limits_gas_to_what_the_sender_can_pay(
4427        #[case] balance: u128,
4428        #[case] value: u128,
4429        #[case] price: u64,
4430        #[case] gas: u64,
4431    ) {
4432        let allowance = gas_allowance(
4433            &TokenAmount::from_atto(balance),
4434            &TokenAmount::from_atto(value),
4435            &TokenAmount::from_atto(price),
4436        );
4437        assert_eq!(allowance.unwrap(), gas);
4438    }
4439
4440    #[rstest]
4441    #[case::nothing_affordable(1, 0, 2, "gas required exceeds allowance (0)")] // 1 / 2 = 0 gas
4442    #[case::all_spent_on_value(100, 100, 1, "gas required exceeds allowance (0)")]
4443    #[case::price_above_balance(1_000_000, 0, u64::MAX, "gas required exceeds allowance (0)")]
4444    #[case::value_above_balance(
4445        100,
4446        101,
4447        1,
4448        "insufficient funds for gas * price + value: have 100 want 101"
4449    )]
4450    fn gas_allowance_rejects_a_sender_that_cannot_pay(
4451        #[case] balance: u128,
4452        #[case] value: u128,
4453        #[case] price: u64,
4454        #[case] message: &str,
4455    ) {
4456        let err = gas_allowance(
4457            &TokenAmount::from_atto(balance),
4458            &TokenAmount::from_atto(value),
4459            &TokenAmount::from_atto(price),
4460        )
4461        .unwrap_err();
4462        assert_eq!(err.to_string(), message);
4463    }
4464
4465    /// Searches with a fake run that succeeds exactly at the limits `succeeds` accepts.
4466    async fn search(start: u64, gas_cap: u64, succeeds: fn(u64) -> bool) -> anyhow::Result<u64> {
4467        gas_search(start, gas_cap, 1.25, |limit| {
4468            let exit_code = if succeeds(limit) {
4469                0
4470            } else {
4471                EVM_CONTRACT_REVERTED.value()
4472            };
4473            async move { Ok(apply_ret(exit_code, 1)) }
4474        })
4475        .await
4476    }
4477
4478    #[rstest]
4479    #[case::margin_added(100, BLOCK_GAS_LIMIT, |limit| limit >= 1000, 1250)] // 1000 found, ×1.25
4480    #[case::margin_clamped_to_cap(100, 1100, |limit| limit >= 1000, 1100)] // 1001 found, 1251 is above the cap
4481    #[case::margin_breaks_the_call(500, BLOCK_GAS_LIMIT, |limit| limit >= 1000 && !(1100..=1500).contains(&limit), 1000)] // 1000 found, 1250 fails
4482    #[case::below_100_gas(1, BLOCK_GAS_LIMIT, |limit| limit >= 70, 87)] // 70 found, ×1.25 = 87.5
4483    #[tokio::test]
4484    async fn gas_search_adds_the_margin_only_when_it_fits(
4485        #[case] start: u64,
4486        #[case] gas_cap: u64,
4487        #[case] succeeds: fn(u64) -> bool,
4488        #[case] gas: u64,
4489    ) {
4490        assert_eq!(search(start, gas_cap, succeeds).await.unwrap(), gas);
4491    }
4492
4493    #[tokio::test]
4494    async fn gas_search_fails_when_the_cap_is_too_low() {
4495        let err: ServerError = search(100, 10_000, |limit| limit >= 20_000)
4496            .await
4497            .unwrap_err()
4498            .into();
4499        assert_eq!(err.code(), errors::TRANSACTION_REJECTED_CODE);
4500        assert_eq!(err.message(), "out of gas: gas required exceeds: 10000");
4501    }
4502
4503    #[rstest]
4504    // Non-empty access list → JSON array.
4505    #[case::populated_array(ApiEthTx { access_list: Some(NotNullVec(vec![EthHash::default()])), ..Default::default() }, Some(1))]
4506    // `access_list: None` → field omitted.
4507    #[case::explicit_none_omitted(ApiEthTx { access_list: None, ..Default::default() }, None)]
4508    // Legacy tx → field omitted.
4509    #[case::legacy_homestead_omitted(EthLegacyHomesteadTxArgs::default().into(), None)]
4510    // Typed tx with no entries → `[]`.
4511    #[case::eip1559_empty_array(EthEip1559TxArgs::default().into(), Some(0))]
4512    fn access_list_serialization(#[case] tx: ApiEthTx, #[case] expected: Option<usize>) {
4513        let json = serde_json::to_value(tx.into_lotus_json()).unwrap();
4514        match expected {
4515            Some(len) => assert_eq!(
4516                json["accessList"]
4517                    .as_array()
4518                    .expect("accessList should serialize as an array")
4519                    .len(),
4520                len
4521            ),
4522            None => assert!(!json.as_object().unwrap().contains_key("accessList")),
4523        }
4524    }
4525
4526    #[rstest]
4527    // Contract creation → `"to": null` present, not omitted.
4528    #[case::contract_creation(None)]
4529    // Normal tx → `"to"` is the recipient address.
4530    #[case::normal(Some(EthAddress::default()))]
4531    fn to_is_always_serialized(#[case] to: Option<EthAddress>) {
4532        let json = serde_json::to_value(
4533            ApiEthTx {
4534                to,
4535                ..Default::default()
4536            }
4537            .into_lotus_json(),
4538        )
4539        .unwrap();
4540        assert!(
4541            json.as_object().unwrap().contains_key("to"),
4542            "`to` key must always be present"
4543        );
4544        assert_eq!(json["to"], serde_json::to_value(to).unwrap());
4545    }
4546
4547    #[rstest]
4548    // `"accessList": null` → `None`.
4549    #[case::null_to_none(Some(serde_json::Value::Null), None)]
4550    // Omitted/Missing field → `None`.
4551    #[case::missing_to_none(None, None)]
4552    // `"accessList": []` → `None`.
4553    #[case::empty_array_to_none(Some(serde_json::json!([])), None)]
4554    // Non-empty array → `Some(...)`.
4555    #[case::populated_array_to_some(
4556        Some(serde_json::json!([EthHash::default()])),
4557        Some(NotNullVec(vec![EthHash::default()]))
4558    )]
4559    fn access_list_deserialization(
4560        #[case] access_list_value: Option<serde_json::Value>,
4561        #[case] expected: Option<NotNullVec<EthHash>>,
4562    ) {
4563        let mut json = serde_json::to_value(ApiEthTx::default().into_lotus_json()).unwrap();
4564        let obj = json.as_object_mut().unwrap();
4565        match access_list_value {
4566            Some(value) => {
4567                obj.insert("accessList".into(), value);
4568            }
4569            None => {
4570                obj.remove("accessList");
4571            }
4572        }
4573        let tx = ApiEthTx::from_lotus_json(serde_json::from_value(json).unwrap());
4574        assert_eq!(tx.access_list, expected);
4575    }
4576
4577    #[quickcheck]
4578    fn gas_price_result_serde_roundtrip(i: u128) {
4579        let r = EthBigInt(ethereum_types::U256::from(i));
4580        let encoded = serde_json::to_string(&r).unwrap();
4581        assert_eq!(encoded, format!("\"{i:#x}\""));
4582        let decoded: EthBigInt = serde_json::from_str(&encoded).unwrap();
4583        assert_eq!(r, decoded);
4584    }
4585
4586    #[rstest]
4587    #[case::zero("0x0", ethereum_types::U256::zero())]
4588    #[case::mixed_case("0xABcd", ethereum_types::U256::from(0xabcd))]
4589    #[case::max(
4590        "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
4591        ethereum_types::U256::MAX
4592    )]
4593    fn eth_big_int_deserialize_canonical(
4594        #[case] input: &str,
4595        #[case] expected: ethereum_types::U256,
4596    ) {
4597        let decoded: EthBigInt = serde_json::from_value(serde_json::json!(input)).unwrap();
4598        assert_eq!(decoded.0, expected);
4599    }
4600
4601    #[rstest]
4602    #[case::empty("")]
4603    #[case::no_digits("0x")]
4604    #[case::unprefixed("ff")]
4605    #[case::leading_zero("0x01")]
4606    #[case::zero_padded_zero("0x00")]
4607    #[case::second_prefix("0x0x1")]
4608    #[case::sign("0x-1")]
4609    #[case::whitespace("0x12 34")]
4610    #[case::not_hex("0xzz")]
4611    #[case::oversized("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")]
4612    fn eth_big_int_deserialize_rejects(#[case] input: &str) {
4613        serde_json::from_value::<EthBigInt>(serde_json::json!(input)).unwrap_err();
4614    }
4615
4616    #[rstest]
4617    fn eth_big_int_from_wide_big_int(
4618        #[values(256, crate::shim::bigint::MAX_BIGINT_BITS - 1)] shift: u64,
4619    ) {
4620        let value = BigInt::from(1u8) << shift;
4621        assert_eq!(EthBigInt::from(&value).0, ethereum_types::U256::MAX);
4622        assert_eq!(EthBigInt::from(-value).0, ethereum_types::U256::MAX);
4623    }
4624
4625    #[quickcheck]
4626    fn eth_big_int_from_big_int_roundtrip(words: [u64; 4]) {
4627        let value = ethereum_types::U256(words);
4628        assert_eq!(EthBigInt::from(BigInt::from(EthBigInt(value))).0, value);
4629    }
4630
4631    /// `transactionPosition` must be 0-indexed and system-actor messages must
4632    /// be filtered without consuming a position.
4633    #[test]
4634    fn non_system_traces_with_positions_is_zero_indexed() {
4635        use crate::shim::address::Address as ShimAddress;
4636        use crate::shim::message::Message_v3;
4637
4638        let invoc_with_from = |from: ShimAddress| -> Arc<ApiInvocResult> {
4639            ApiInvocResult {
4640                msg: Message_v3 {
4641                    to: ShimAddress::new_id(1).into(),
4642                    from: from.into(),
4643                    ..Message_v3::default()
4644                }
4645                .into(),
4646                ..Default::default()
4647            }
4648            .into()
4649        };
4650
4651        let raw_traces = vec![
4652            invoc_with_from(system::ADDRESS.into()),
4653            invoc_with_from(ShimAddress::new_id(1000)),
4654            invoc_with_from(system::ADDRESS.into()),
4655            invoc_with_from(ShimAddress::new_id(1001)),
4656            invoc_with_from(ShimAddress::new_id(1002)),
4657        ];
4658
4659        let positions: Vec<i64> = non_system_traces_with_positions(raw_traces)
4660            .map(|(pos, _)| pos)
4661            .collect();
4662
4663        assert_eq!(positions, vec![0, 1, 2]);
4664    }
4665
4666    #[test]
4667    fn test_abi_encoding() {
4668        const EXPECTED: &str = "000000000000000000000000000000000000000000000000000000000000001600000000000000000000000000000000000000000000000000000000000000510000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000001b1111111111111111111020200301000000044444444444444444010000000000";
4669        const DATA: &str = "111111111111111111102020030100000004444444444444444401";
4670        let expected_bytes = hex::decode(EXPECTED).unwrap();
4671        let data_bytes = hex::decode(DATA).unwrap();
4672
4673        assert_eq!(expected_bytes, encode_as_abi_helper(22, 81, &data_bytes));
4674    }
4675
4676    #[test]
4677    fn test_abi_encoding_empty_bytes() {
4678        // Generated using https://abi.hashex.org/
4679        const EXPECTED: &str = "0000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000005100000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000000";
4680        let expected_bytes = hex::decode(EXPECTED).unwrap();
4681        let data_bytes = vec![];
4682
4683        assert_eq!(expected_bytes, encode_as_abi_helper(22, 81, &data_bytes));
4684    }
4685
4686    #[test]
4687    fn test_abi_encoding_one_byte() {
4688        // According to https://docs.soliditylang.org/en/latest/abi-spec.html and handcrafted
4689        // Uint64, Uint64, Bytes[]
4690        // 22, 81, [253]
4691        const EXPECTED: &str = "0000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000005100000000000000000000000000000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000000001fd00000000000000000000000000000000000000000000000000000000000000";
4692        let expected_bytes = hex::decode(EXPECTED).unwrap();
4693        let data_bytes = vec![253];
4694
4695        assert_eq!(expected_bytes, encode_as_abi_helper(22, 81, &data_bytes));
4696    }
4697
4698    #[test]
4699    fn test_id_address_roundtrip() {
4700        let test_cases = [1u64, 2, 3, 100, 101];
4701
4702        for id in test_cases {
4703            let addr = FilecoinAddress::new_id(id);
4704
4705            // roundtrip
4706            let eth_addr = EthAddress::from_filecoin_address(&addr).unwrap();
4707            let fil_addr = eth_addr.to_filecoin_address().unwrap();
4708            assert_eq!(addr, fil_addr)
4709        }
4710    }
4711
4712    #[test]
4713    fn test_addr_serde_roundtrip() {
4714        let test_cases = [
4715            r#""0xd4c5fb16488Aa48081296299d54b0c648C9333dA""#,
4716            r#""0x2C2EC67e3e1FeA8e4A39601cB3A3Cd44f5fa830d""#,
4717            r#""0x01184F793982104363F9a8a5845743f452dE0586""#,
4718        ];
4719
4720        for addr in test_cases {
4721            let eth_addr: EthAddress = serde_json::from_str(addr).unwrap();
4722
4723            let encoded = serde_json::to_string(&eth_addr).unwrap();
4724            assert_eq!(encoded, addr.to_lowercase());
4725
4726            let decoded: EthAddress = serde_json::from_str(&encoded).unwrap();
4727            assert_eq!(eth_addr, decoded);
4728        }
4729    }
4730
4731    #[quickcheck]
4732    fn test_fil_address_roundtrip(addr: FilecoinAddress) {
4733        if let Ok(eth_addr) = EthAddress::from_filecoin_address(&addr) {
4734            let fil_addr = eth_addr.to_filecoin_address().unwrap();
4735
4736            let protocol = addr.protocol();
4737            assert!(protocol == Protocol::ID || protocol == Protocol::Delegated);
4738            assert_eq!(addr, fil_addr);
4739        }
4740    }
4741
4742    #[rstest]
4743    #[case("\"0x013dbb9442ca9667baccc6230fcd5c1c4b2d4d2870f4bd20681d4d47cfd15184\"")]
4744    #[case("\"0xab8653edf9f51785664a643b47605a7ba3d917b5339a0724e7642c114d0e4738\"")]
4745    fn test_hash_serde_json(#[case] hash: &str) {
4746        let h: EthHash = serde_json::from_str(hash).unwrap();
4747        let c = h.to_cid();
4748        let h1: EthHash = c.into();
4749        assert_eq!(h, h1);
4750    }
4751
4752    #[quickcheck]
4753    fn test_eth_hash_roundtrip(eth_hash: EthHash) {
4754        let cid = eth_hash.to_cid();
4755        let hash = cid.into();
4756        assert_eq!(eth_hash, hash);
4757    }
4758
4759    #[test]
4760    fn test_block_constructor() {
4761        let block = Block::new(false, 1);
4762        assert_eq!(block.transactions_root, EthHash::empty_root());
4763
4764        let block = Block::new(true, 1);
4765        assert_eq!(block.transactions_root, EthHash::default());
4766    }
4767
4768    #[test]
4769    fn test_eth_tx_hash_from_signed_message() {
4770        let (_, signed) = construct_eth_messages(0);
4771        let tx_hash =
4772            eth_tx_hash_from_signed_message(&signed, crate::networks::calibnet::ETH_CHAIN_ID)
4773                .unwrap();
4774        assert_eq!(
4775            &format!("{tx_hash}"),
4776            "0xfc81dd8d9ffb045e7e2d494f925824098183263c7f402d69e18cc25e3422791b"
4777        );
4778
4779        let (_, signed) = construct_messages();
4780        let tx_hash =
4781            eth_tx_hash_from_signed_message(&signed, crate::networks::calibnet::ETH_CHAIN_ID)
4782                .unwrap();
4783        assert_eq!(tx_hash.to_cid(), signed.cid());
4784
4785        let (_, signed) = construct_bls_messages();
4786        let tx_hash =
4787            eth_tx_hash_from_signed_message(&signed, crate::networks::calibnet::ETH_CHAIN_ID)
4788                .unwrap();
4789        assert_eq!(tx_hash.to_cid(), signed.message().cid());
4790    }
4791
4792    /// An `RPCState` on calibnet with `sender` registered as a funded `EthAccount` actor at
4793    /// nonce `sequence`, so a raw-transaction handler can push a signed message from it.
4794    fn funded_calibnet_ctx(
4795        sender: &crate::shim::address::Address,
4796        sequence: u64,
4797    ) -> (Ctx, flume::Receiver<crate::libp2p::NetworkMessage>) {
4798        use crate::blocks::{CachingBlockHeader, RawBlockHeader};
4799        use crate::networks::{ACTOR_BUNDLES_METADATA, ChainConfig, NetworkChain};
4800        use crate::rpc::RPCState;
4801        use crate::rpc::test_utils::chain_store_with_config;
4802        use crate::shim::machine::BuiltinActor;
4803        use crate::shim::state_tree::{ActorState, StateTree, StateTreeVersion};
4804        use crate::test_utils::dummy_ticket;
4805        use crate::utils::db::CborStoreExt as _;
4806
4807        let chain_config = ChainConfig::calibnet();
4808        // Past the Hygge (NV18) upgrade, so `EthAccount` actors may send messages.
4809        let head_epoch = chain_config.epoch(Height::Hygge) + 1;
4810        let cs = chain_store_with_config(chain_config);
4811        let db = cs.db();
4812
4813        let mut init_state =
4814            fil_actor_init_state::v18::State::new(db, "calibrationnet".to_string()).unwrap();
4815        let robust_addr = VmAddress::new_actor(b"eth-send-raw-tx-test");
4816        let delegated_addr = VmAddress::from(sender);
4817        let (sender_id, _) = init_state
4818            .map_addresses_to_id(db, &robust_addr, Some(&delegated_addr))
4819            .unwrap();
4820        let init_head = db.put_cbor_default(&init_state).unwrap();
4821
4822        let manifest = &ACTOR_BUNDLES_METADATA
4823            .get(&(NetworkChain::Calibnet, "v18.0.0".to_string()))
4824            .unwrap()
4825            .manifest;
4826        let init_code = manifest.get(BuiltinActor::Init).unwrap();
4827        let ethaccount_code = manifest.get(BuiltinActor::EthAccount).unwrap();
4828
4829        let mut state_tree = StateTree::new(db, StateTreeVersion::V5).unwrap();
4830        state_tree
4831            .set_actor(
4832                &crate::shim::address::Address::new_id(1),
4833                ActorState::new(init_code, init_head, TokenAmount::from_atto(0), 0, None),
4834            )
4835            .unwrap();
4836        state_tree
4837            .set_actor(
4838                &crate::shim::address::Address::new_id(sender_id),
4839                ActorState::new(
4840                    ethaccount_code,
4841                    Cid::default(),
4842                    TokenAmount::from_whole(1000),
4843                    sequence,
4844                    Some(*sender),
4845                ),
4846            )
4847            .unwrap();
4848        let state_root = state_tree.flush().unwrap();
4849
4850        let head_header = CachingBlockHeader::new(RawBlockHeader {
4851            parents: cs.genesis_tipset().key().clone(),
4852            epoch: head_epoch,
4853            state_root,
4854            ticket: dummy_ticket(1),
4855            ..Default::default()
4856        });
4857        db.put_cbor_default(&head_header).unwrap();
4858        cs.set_heaviest_tipset(Tipset::from(head_header)).unwrap();
4859
4860        RPCState::for_tests(cs).unwrap()
4861    }
4862
4863    /// A signed calibnet EIP-1559 transaction, as `eth_sendRawTransaction` receives it.
4864    fn signed_calibnet_tx() -> EthTx {
4865        use crate::eth::EthEip1559TxArgsBuilder;
4866        use std::str::FromStr as _;
4867
4868        let mut tx_args = EthEip1559TxArgsBuilder::default()
4869            .chain_id(314159_u64)
4870            .nonce(486_u64)
4871            .to(Some(
4872                ethereum_types::H160::from_str("0xeb4a9cdb9f42d3a503d580a39b6e3736eb21fffd")
4873                    .unwrap()
4874                    .into(),
4875            ))
4876            .value(num::BigInt::from(0))
4877            .max_fee_per_gas(num::BigInt::from(1500000120))
4878            .max_priority_fee_per_gas(num::BigInt::from(1500000000))
4879            .gas_limit(37442471_u64)
4880            .input(hex::decode("383487be000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000660d4d120000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000003b6261666b726569656f6f75326d36356276376561786e7767656d7562723675787269696867366474646e6c7a663469616f37686c6e6a6d647372750000000000").unwrap())
4881            .build()
4882            .unwrap();
4883        tx_args.v = num::BigInt::from_str("1").unwrap();
4884        tx_args.r = num::BigInt::from_str(
4885            "84103132941276310528712440865285269631208564772362393569572880532520338257200",
4886        )
4887        .unwrap();
4888        tx_args.s = num::BigInt::from_str(
4889            "7820796778417228639067439047870612492553874254089570360061550763595363987236",
4890        )
4891        .unwrap();
4892        EthTx::from(tx_args)
4893    }
4894
4895    #[tokio::test]
4896    async fn test_eth_send_raw_transaction_hash_is_not_message_cid() {
4897        let tx = signed_calibnet_tx();
4898        let raw_tx = EthBytes(tx.rlp_signed_message().unwrap());
4899
4900        let expected_hash = "0x9f2e70d5737c6b798eccea14895893fb48091ab3c59d0fe95508dc7efdae2e5f";
4901        let smsg = tx
4902            .get_signed_message(crate::networks::calibnet::ETH_CHAIN_ID)
4903            .unwrap();
4904        // What it returned before the fix.
4905        let wrong_hash: EthHash = smsg.cid().into();
4906        let from = smsg.message().from();
4907        let sequence = smsg.message().sequence();
4908
4909        let (trusted_ctx, _network_rx) = funded_calibnet_ctx(&from, sequence);
4910        let sent_hash = EthSendRawTransaction::handle(
4911            trusted_ctx.clone(),
4912            (raw_tx.clone(),),
4913            &Default::default(),
4914        )
4915        .await
4916        .unwrap();
4917        assert_eq!(&format!("{sent_hash}"), expected_hash);
4918        assert_ne!(sent_hash, wrong_hash);
4919        assert_eq!(
4920            trusted_ctx.chain_store().get_mapping(&sent_hash).unwrap(),
4921            Some(smsg.cid()),
4922            "the submitted tx must be immediately indexed under its own hash"
4923        );
4924
4925        let (untrusted_ctx, _network_rx) = funded_calibnet_ctx(&from, sequence);
4926        let sent_hash_untrusted = EthSendRawTransactionUntrusted::handle(
4927            untrusted_ctx.clone(),
4928            (raw_tx,),
4929            &Default::default(),
4930        )
4931        .await
4932        .unwrap();
4933        assert_eq!(sent_hash_untrusted, sent_hash);
4934        assert_eq!(
4935            untrusted_ctx
4936                .chain_store()
4937                .get_mapping(&sent_hash_untrusted)
4938                .unwrap(),
4939            Some(smsg.cid())
4940        );
4941    }
4942
4943    /// A pending delegated message is found by its Ethereum hash with and without a tx-hash
4944    /// mapping, and comes back with its hash and sender. A transaction gossiped from another node
4945    /// has no mapping until it is mined.
4946    #[tokio::test]
4947    async fn test_eth_get_transaction_by_hash_finds_pending_tx() {
4948        let tx = signed_calibnet_tx();
4949        let tx_hash: EthHash = tx.eth_hash().unwrap().into();
4950        let smsg = tx
4951            .get_signed_message(crate::networks::calibnet::ETH_CHAIN_ID)
4952            .unwrap();
4953        // The mapping miss falls back to the hash as a CID, which is never the message's CID.
4954        assert_ne!(tx_hash.to_cid(), smsg.cid());
4955
4956        let (from, sequence) = (smsg.message().from(), smsg.message().sequence());
4957        let (ctx, _network_rx) = funded_calibnet_ctx(&from, sequence);
4958        let cid = ctx.mpool.push(smsg).await.unwrap();
4959        let cancellation_token = CancellationToken::new();
4960        let lookup = |hash: EthHash| {
4961            let ctx = ctx.clone();
4962            let cancellation_token = cancellation_token.clone();
4963            async move {
4964                get_eth_transaction_by_hash(&ctx, &hash, None, &cancellation_token)
4965                    .await
4966                    .unwrap()
4967            }
4968        };
4969
4970        // (case, mapping): the mapping is what `eth_sendRawTransaction` on this node writes.
4971        for (case, mapping) in [("mapping miss", None), ("mapping hit", Some(cid))] {
4972            if let Some(cid) = mapping {
4973                ctx.chain_store().put_mapping(tx_hash, cid, 0).unwrap();
4974            }
4975            assert_eq!(ctx.chain_store().get_mapping(&tx_hash).unwrap(), mapping);
4976            let found = lookup(tx_hash)
4977                .await
4978                .unwrap_or_else(|| panic!("{case}: the pending tx must be found by its hash"));
4979            assert_eq!(found.hash, tx_hash, "{case}");
4980            assert_eq!(
4981                found.from,
4982                EthAddress::from_filecoin_address(&from).unwrap(),
4983                "{case}"
4984            );
4985            assert_eq!(
4986                found.block_hash,
4987                EthHash::default(),
4988                "{case}: pending, not mined"
4989            );
4990        }
4991
4992        let unknown = lookup(EthHash::default()).await;
4993        assert!(unknown.is_none(), "{unknown:?}");
4994    }
4995
4996    #[test]
4997    fn test_eth_tx_hash_from_message_cid() {
4998        let blockstore = Arc::new(MemoryDB::default());
4999
5000        let (msg0, secp0) = construct_eth_messages(0);
5001        let (_msg1, secp1) = construct_eth_messages(1);
5002        let (msg2, bls0) = construct_bls_messages();
5003
5004        crate::chain::persist_objects(&blockstore, [&msg0, &msg2].into_iter()).unwrap();
5005        crate::chain::persist_objects(&blockstore, [&secp0, &bls0].into_iter()).unwrap();
5006
5007        let tx_hash = eth_tx_hash_from_message_cid(&blockstore, &secp0.cid(), 0).unwrap();
5008        assert_eq!(tx_hash, eth_tx_hash_from_signed_message(&secp0, 0).unwrap());
5009
5010        let tx_hash = eth_tx_hash_from_message_cid(&blockstore, &msg2.cid(), 0).unwrap();
5011        assert_eq!(tx_hash, EthHash::from(msg2.cid()));
5012
5013        let err = eth_tx_hash_from_message_cid(&blockstore, &secp1.cid(), 0).unwrap_err();
5014        let missing = secp1.cid();
5015        assert_eq!(
5016            err.to_string(),
5017            format!(
5018                "failed to load event message {missing}: Invalid tipset: {missing}; Invalid tipset: {missing}"
5019            )
5020        );
5021    }
5022
5023    /// One unreadable event message fails the whole conversion instead of dropping the event;
5024    /// readable ones still convert, through the unsigned fallback too.
5025    #[tokio::test]
5026    async fn test_eth_filter_logs_from_events_fails_on_unreadable_message() {
5027        let (ctx, _network_rx) =
5028            crate::rpc::RPCState::for_tests(crate::rpc::test_utils::chain_store()).unwrap();
5029        let (readable, _) = construct_bls_messages();
5030        let (_, missing) = construct_eth_messages(0);
5031        crate::chain::persist_objects(ctx.db(), std::iter::once(&readable)).unwrap();
5032        let (readable, missing) = (readable.cid(), missing.cid());
5033        let tipset_key = ctx.chain_store().genesis_tipset().key().clone();
5034        let event = |msg_cid: Cid, codec: u64| CollectedEvent {
5035            entries: vec![EventEntry {
5036                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5037                key: "d".into(),
5038                codec,
5039                value: vec![1].into(),
5040            }],
5041            emitter_addr: FilecoinAddress::new_id(1),
5042            event_idx: 0,
5043            reverted: false,
5044            height: 0,
5045            tipset_key: tipset_key.clone(),
5046            msg_idx: 0,
5047            msg_cid,
5048        };
5049
5050        // (case, events, expected log count; `None` expects the error naming the missing message)
5051        let cases = [
5052            ("BLS fallback", vec![event(readable, IPLD_RAW)], Some(1)),
5053            ("missing message", vec![event(missing, IPLD_RAW)], None),
5054            (
5055                "readable then missing",
5056                vec![event(readable, IPLD_RAW), event(missing, IPLD_RAW)],
5057                None,
5058            ),
5059            ("empty", vec![], Some(0)),
5060            ("non-Ethereum", vec![event(missing, DAG_CBOR)], Some(0)),
5061        ];
5062        for (case, events, want_logs) in cases {
5063            let result = eth_filter_logs_from_events(&ctx, &events);
5064            let Some(want_logs) = want_logs else {
5065                let err = result.expect_err(case).to_string();
5066                assert!(
5067                    err.contains(&format!("failed to load event message {missing}")),
5068                    "{case}: {err}"
5069                );
5070                continue;
5071            };
5072            let logs = result.unwrap_or_else(|e| panic!("{case}: {e:#}"));
5073            assert_eq!(logs.len(), want_logs, "{case}");
5074            assert!(
5075                logs.iter()
5076                    .all(|log| log.transaction_hash == EthHash::from(readable)),
5077                "{case}: {logs:?}"
5078            );
5079        }
5080    }
5081
5082    #[test]
5083    fn test_eth_log_from_event() {
5084        // The value member of these event entries correspond to existing topics on Calibnet,
5085        // but they could just as easily be vectors filled with random bytes.
5086
5087        let entries = vec![
5088            EventEntry {
5089                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5090                key: "t1".into(),
5091                codec: IPLD_RAW,
5092                value: vec![
5093                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5094                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5095                ]
5096                .into(),
5097            },
5098            EventEntry {
5099                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5100                key: "t2".into(),
5101                codec: IPLD_RAW,
5102                value: vec![
5103                    116, 4, 227, 209, 4, 234, 120, 65, 195, 217, 230, 253, 32, 173, 254, 153, 180,
5104                    173, 88, 107, 192, 141, 143, 59, 211, 175, 239, 137, 76, 241, 132, 222,
5105                ]
5106                .into(),
5107            },
5108        ];
5109        let (bytes, hashes) = eth_log_from_event(&entries).unwrap();
5110        assert!(bytes.0.is_empty());
5111        assert_eq!(hashes.len(), 2);
5112
5113        let entries = vec![
5114            EventEntry {
5115                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5116                key: "t1".into(),
5117                codec: IPLD_RAW,
5118                value: vec![
5119                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5120                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5121                ]
5122                .into(),
5123            },
5124            EventEntry {
5125                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5126                key: "t2".into(),
5127                codec: IPLD_RAW,
5128                value: vec![
5129                    116, 4, 227, 209, 4, 234, 120, 65, 195, 217, 230, 253, 32, 173, 254, 153, 180,
5130                    173, 88, 107, 192, 141, 143, 59, 211, 175, 239, 137, 76, 241, 132, 222,
5131                ]
5132                .into(),
5133            },
5134            EventEntry {
5135                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5136                key: "t3".into(),
5137                codec: IPLD_RAW,
5138                value: vec![
5139                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5140                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5141                ]
5142                .into(),
5143            },
5144            EventEntry {
5145                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5146                key: "t4".into(),
5147                codec: IPLD_RAW,
5148                value: vec![
5149                    116, 4, 227, 209, 4, 234, 120, 65, 195, 217, 230, 253, 32, 173, 254, 153, 180,
5150                    173, 88, 107, 192, 141, 143, 59, 211, 175, 239, 137, 76, 241, 132, 222,
5151                ]
5152                .into(),
5153            },
5154        ];
5155        let (bytes, hashes) = eth_log_from_event(&entries).unwrap();
5156        assert!(bytes.0.is_empty());
5157        assert_eq!(hashes.len(), 4);
5158
5159        let entries = vec![
5160            EventEntry {
5161                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5162                key: "t1".into(),
5163                codec: IPLD_RAW,
5164                value: vec![
5165                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5166                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5167                ]
5168                .into(),
5169            },
5170            EventEntry {
5171                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5172                key: "t1".into(),
5173                codec: IPLD_RAW,
5174                value: vec![
5175                    116, 4, 227, 209, 4, 234, 120, 65, 195, 217, 230, 253, 32, 173, 254, 153, 180,
5176                    173, 88, 107, 192, 141, 143, 59, 211, 175, 239, 137, 76, 241, 132, 222,
5177                ]
5178                .into(),
5179            },
5180        ];
5181        assert!(eth_log_from_event(&entries).is_none());
5182
5183        let entries = vec![
5184            EventEntry {
5185                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5186                key: "t3".into(),
5187                codec: IPLD_RAW,
5188                value: vec![
5189                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5190                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5191                ]
5192                .into(),
5193            },
5194            EventEntry {
5195                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5196                key: "t4".into(),
5197                codec: IPLD_RAW,
5198                value: vec![
5199                    116, 4, 227, 209, 4, 234, 120, 65, 195, 217, 230, 253, 32, 173, 254, 153, 180,
5200                    173, 88, 107, 192, 141, 143, 59, 211, 175, 239, 137, 76, 241, 132, 222,
5201                ]
5202                .into(),
5203            },
5204            EventEntry {
5205                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5206                key: "t1".into(),
5207                codec: IPLD_RAW,
5208                value: vec![
5209                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5210                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5211                ]
5212                .into(),
5213            },
5214            EventEntry {
5215                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5216                key: "t2".into(),
5217                codec: IPLD_RAW,
5218                value: vec![
5219                    116, 4, 227, 209, 4, 234, 120, 65, 195, 217, 230, 253, 32, 173, 254, 153, 180,
5220                    173, 88, 107, 192, 141, 143, 59, 211, 175, 239, 137, 76, 241, 132, 222,
5221                ]
5222                .into(),
5223            },
5224        ];
5225        let (bytes, hashes) = eth_log_from_event(&entries).unwrap();
5226        assert!(bytes.0.is_empty());
5227        assert_eq!(hashes.len(), 4);
5228
5229        let entries = vec![
5230            EventEntry {
5231                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5232                key: "t1".into(),
5233                codec: IPLD_RAW,
5234                value: vec![
5235                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5236                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5237                ]
5238                .into(),
5239            },
5240            EventEntry {
5241                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5242                key: "t3".into(),
5243                codec: IPLD_RAW,
5244                value: vec![
5245                    116, 4, 227, 209, 4, 234, 120, 65, 195, 217, 230, 253, 32, 173, 254, 153, 180,
5246                    173, 88, 107, 192, 141, 143, 59, 211, 175, 239, 137, 76, 241, 132, 222,
5247                ]
5248                .into(),
5249            },
5250        ];
5251        assert!(eth_log_from_event(&entries).is_none());
5252
5253        let entries = vec![EventEntry {
5254            flags: (Flags::FLAG_INDEXED_ALL).bits(),
5255            key: "t1".into(),
5256            codec: DAG_CBOR,
5257            value: vec![
5258                226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11, 81,
5259                29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5260            ]
5261            .into(),
5262        }];
5263        assert!(eth_log_from_event(&entries).is_none());
5264
5265        let entries = vec![EventEntry {
5266            flags: (Flags::FLAG_INDEXED_ALL).bits(),
5267            key: "t1".into(),
5268            codec: IPLD_RAW,
5269            value: vec![
5270                226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11, 81,
5271                29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149, 0,
5272            ]
5273            .into(),
5274        }];
5275        assert!(eth_log_from_event(&entries).is_none());
5276
5277        let entries = vec![
5278            EventEntry {
5279                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5280                key: "t1".into(),
5281                codec: IPLD_RAW,
5282                value: vec![
5283                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5284                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149,
5285                ]
5286                .into(),
5287            },
5288            EventEntry {
5289                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5290                key: "d".into(),
5291                codec: IPLD_RAW,
5292                value: vec![
5293                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 190,
5294                    25, 34, 116, 232, 27, 26, 248,
5295                ]
5296                .into(),
5297            },
5298        ];
5299        let (bytes, hashes) = eth_log_from_event(&entries).unwrap();
5300        assert_eq!(bytes.0.len(), 32);
5301        assert_eq!(hashes.len(), 1);
5302
5303        let entries = vec![
5304            EventEntry {
5305                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5306                key: "t1".into(),
5307                codec: IPLD_RAW,
5308                value: vec![
5309                    226, 71, 32, 244, 92, 183, 79, 45, 85, 241, 222, 235, 182, 9, 143, 80, 241, 11,
5310                    81, 29, 171, 138, 125, 71, 196, 129, 154, 8, 220, 208, 184, 149, 0,
5311                ]
5312                .into(),
5313            },
5314            EventEntry {
5315                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5316                key: "d".into(),
5317                codec: IPLD_RAW,
5318                value: vec![
5319                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 190,
5320                    25, 34, 116, 232, 27, 26, 248,
5321                ]
5322                .into(),
5323            },
5324            EventEntry {
5325                flags: (Flags::FLAG_INDEXED_ALL).bits(),
5326                key: "d".into(),
5327                codec: IPLD_RAW,
5328                value: vec![
5329                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 49, 190,
5330                    25, 34, 116, 232, 27, 26, 248,
5331                ]
5332                .into(),
5333            },
5334        ];
5335        assert!(eth_log_from_event(&entries).is_none());
5336    }
5337
5338    #[test]
5339    fn test_from_bytes_valid() {
5340        let zero_bytes = [0u8; 32];
5341        assert_eq!(
5342            EthUint64::from_bytes(&zero_bytes).unwrap().0,
5343            0,
5344            "zero bytes"
5345        );
5346
5347        let mut value_bytes = [0u8; 32];
5348        value_bytes[31] = 42;
5349        assert_eq!(
5350            EthUint64::from_bytes(&value_bytes).unwrap().0,
5351            42,
5352            "simple value"
5353        );
5354
5355        let mut max_bytes = [0u8; 32];
5356        max_bytes[24..32].copy_from_slice(&u64::MAX.to_be_bytes());
5357        assert_eq!(
5358            EthUint64::from_bytes(&max_bytes).unwrap().0,
5359            u64::MAX,
5360            "valid max value"
5361        );
5362    }
5363
5364    #[test]
5365    fn test_from_bytes_wrong_length() {
5366        let short_bytes = [0u8; 31];
5367        assert!(
5368            EthUint64::from_bytes(&short_bytes).is_err(),
5369            "bytes too short"
5370        );
5371
5372        let long_bytes = [0u8; 33];
5373        assert!(
5374            EthUint64::from_bytes(&long_bytes).is_err(),
5375            "bytes too long"
5376        );
5377
5378        let empty_bytes = [];
5379        assert!(
5380            EthUint64::from_bytes(&empty_bytes).is_err(),
5381            "bytes too short"
5382        );
5383    }
5384
5385    #[test]
5386    fn test_from_bytes_overflow() {
5387        let mut overflow_bytes = [0u8; 32];
5388        overflow_bytes[10] = 1;
5389        assert!(
5390            EthUint64::from_bytes(&overflow_bytes).is_err(),
5391            "overflow with non-zero byte at position 10"
5392        );
5393
5394        overflow_bytes = [0u8; 32];
5395        overflow_bytes[23] = 1;
5396        assert!(
5397            EthUint64::from_bytes(&overflow_bytes).is_err(),
5398            "overflow with non-zero byte at position 23"
5399        );
5400
5401        overflow_bytes = [0u8; 32];
5402        overflow_bytes
5403            .iter_mut()
5404            .take(24)
5405            .for_each(|byte| *byte = 0xFF);
5406
5407        assert!(
5408            EthUint64::from_bytes(&overflow_bytes).is_err(),
5409            "overflow bytes with non-zero bytes at positions 0-23"
5410        );
5411
5412        overflow_bytes = [0u8; 32];
5413        for i in 0..24 {
5414            overflow_bytes[i] = 0xFF;
5415            assert!(
5416                EthUint64::from_bytes(&overflow_bytes).is_err(),
5417                "overflow with non-zero byte at position {i}"
5418            );
5419        }
5420
5421        overflow_bytes = [0xFF; 32];
5422        assert!(
5423            EthUint64::from_bytes(&overflow_bytes).is_err(),
5424            "overflow with all ones"
5425        );
5426    }
5427
5428    fn create_execution_trace(from: FilecoinAddress, to: FilecoinAddress) -> ExecutionTrace {
5429        ExecutionTrace {
5430            msg: MessageTrace {
5431                from,
5432                to,
5433                value: TokenAmount::default(),
5434                method: 0,
5435                params: Default::default(),
5436                params_codec: 0,
5437                gas_limit: None,
5438                read_only: None,
5439            },
5440            msg_rct: ReturnTrace {
5441                exit_code: ExitCode::from(0u32),
5442                r#return: Default::default(),
5443                return_codec: 0,
5444            },
5445            invoked_actor: None,
5446            gas_charges: vec![],
5447            subcalls: vec![],
5448            logs: vec![],
5449            ipld_ops: vec![],
5450        }
5451    }
5452
5453    fn create_execution_trace_with_subcalls(
5454        from: FilecoinAddress,
5455        to: FilecoinAddress,
5456        subcalls: Vec<ExecutionTrace>,
5457    ) -> ExecutionTrace {
5458        let mut trace = create_execution_trace(from, to);
5459        trace.subcalls = subcalls;
5460        trace
5461    }
5462
5463    #[test]
5464    fn test_extract_touched_addresses_with_id_addresses() {
5465        // ID addresses (e.g., f0100) can be converted to EthAddress
5466        let from = FilecoinAddress::new_id(100);
5467        let to = FilecoinAddress::new_id(200);
5468        let trace = create_execution_trace(from, to);
5469
5470        let addresses = extract_touched_eth_addresses(&trace);
5471
5472        assert_eq!(addresses.len(), 2);
5473        assert!(addresses.contains(&EthAddress::from_filecoin_address(&from).unwrap()));
5474        assert!(addresses.contains(&EthAddress::from_filecoin_address(&to).unwrap()));
5475    }
5476
5477    #[test]
5478    fn test_extract_touched_addresses_same_from_and_to() {
5479        let addr = FilecoinAddress::new_id(100);
5480        let trace = create_execution_trace(addr, addr);
5481
5482        let addresses = extract_touched_eth_addresses(&trace);
5483
5484        // Should deduplicate
5485        assert_eq!(addresses.len(), 1);
5486        assert!(addresses.contains(&EthAddress::from_filecoin_address(&addr).unwrap()));
5487    }
5488
5489    #[test]
5490    fn test_extract_touched_addresses_with_subcalls() {
5491        let addr1 = FilecoinAddress::new_id(100);
5492        let addr2 = FilecoinAddress::new_id(200);
5493        let addr3 = FilecoinAddress::new_id(300);
5494        let addr4 = FilecoinAddress::new_id(400);
5495
5496        let subcall = create_execution_trace(addr3, addr4);
5497        let trace = create_execution_trace_with_subcalls(addr1, addr2, vec![subcall]);
5498
5499        let addresses = extract_touched_eth_addresses(&trace);
5500
5501        assert_eq!(addresses.len(), 4);
5502        assert!(addresses.contains(&EthAddress::from_filecoin_address(&addr1).unwrap()));
5503        assert!(addresses.contains(&EthAddress::from_filecoin_address(&addr2).unwrap()));
5504        assert!(addresses.contains(&EthAddress::from_filecoin_address(&addr3).unwrap()));
5505        assert!(addresses.contains(&EthAddress::from_filecoin_address(&addr4).unwrap()));
5506    }
5507
5508    #[test]
5509    fn test_extract_touched_addresses_with_nested_subcalls() {
5510        let addr1 = FilecoinAddress::new_id(100);
5511        let addr2 = FilecoinAddress::new_id(200);
5512        let addr3 = FilecoinAddress::new_id(300);
5513        let addr4 = FilecoinAddress::new_id(400);
5514        let addr5 = FilecoinAddress::new_id(500);
5515        let addr6 = FilecoinAddress::new_id(600);
5516
5517        // Create nested structure: trace -> subcall1 -> nested_subcall
5518        let nested_subcall = create_execution_trace(addr5, addr6);
5519        let subcall = create_execution_trace_with_subcalls(addr3, addr4, vec![nested_subcall]);
5520        let trace = create_execution_trace_with_subcalls(addr1, addr2, vec![subcall]);
5521
5522        let addresses = extract_touched_eth_addresses(&trace);
5523
5524        assert_eq!(addresses.len(), 6);
5525        for addr in [addr1, addr2, addr3, addr4, addr5, addr6] {
5526            assert!(addresses.contains(&EthAddress::from_filecoin_address(&addr).unwrap()));
5527        }
5528    }
5529
5530    #[test]
5531    fn test_extract_touched_addresses_with_multiple_subcalls() {
5532        let addr1 = FilecoinAddress::new_id(100);
5533        let addr2 = FilecoinAddress::new_id(200);
5534        let addr3 = FilecoinAddress::new_id(300);
5535        let addr4 = FilecoinAddress::new_id(400);
5536        let addr5 = FilecoinAddress::new_id(500);
5537        let addr6 = FilecoinAddress::new_id(600);
5538
5539        let subcall1 = create_execution_trace(addr3, addr4);
5540        let subcall2 = create_execution_trace(addr5, addr6);
5541        let trace = create_execution_trace_with_subcalls(addr1, addr2, vec![subcall1, subcall2]);
5542
5543        let addresses = extract_touched_eth_addresses(&trace);
5544
5545        assert_eq!(addresses.len(), 6);
5546    }
5547
5548    #[test]
5549    fn test_extract_touched_addresses_deduplicates_across_subcalls() {
5550        // Same address appears in parent and subcall
5551        let addr1 = FilecoinAddress::new_id(100);
5552        let addr2 = FilecoinAddress::new_id(200);
5553
5554        let subcall = create_execution_trace(addr1, addr2); // addr1 repeated
5555        let trace = create_execution_trace_with_subcalls(addr1, addr2, vec![subcall]);
5556
5557        let addresses = extract_touched_eth_addresses(&trace);
5558
5559        // Should deduplicate
5560        assert_eq!(addresses.len(), 2);
5561    }
5562
5563    #[test]
5564    fn test_extract_touched_addresses_with_non_convertible_addresses() {
5565        // BLS addresses cannot be converted to EthAddress
5566        let bls_addr = FilecoinAddress::new_bls(&[0u8; 48]).unwrap();
5567        let id_addr = FilecoinAddress::new_id(100);
5568
5569        let trace = create_execution_trace(bls_addr, id_addr);
5570        let addresses = extract_touched_eth_addresses(&trace);
5571
5572        // Only the ID address should be in the set
5573        assert_eq!(addresses.len(), 1);
5574        assert!(addresses.contains(&EthAddress::from_filecoin_address(&id_addr).unwrap()));
5575    }
5576}