Skip to main content

forest/dev/subcommands/devnet_cmd/
state_call.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4//! `Filecoin.StateCall` gas limit parity tests against the Lotus node on the docker devnet. Every
5//! call runs on both nodes, which must agree.
6
7use crate::dev::subcommands::tests_cmd::helpers::*;
8use crate::rpc::eth::types::{EthAddress, EthBytes, EthCallMessage};
9use crate::rpc::prelude::*;
10use crate::rpc::state::ApiInvocResult;
11use crate::rpc::types::ApiTipsetKey;
12use crate::rpc::{Client, Request};
13use crate::shim::econ::{BLOCK_GAS_LIMIT, TokenAmount};
14use crate::shim::executor::Receipt;
15use crate::shim::fvm_shared_latest::error::ExitCode;
16use crate::shim::message::Message;
17use anyhow::{Context as _, bail, ensure};
18use jsonrpsee::types::ErrorObjectOwned;
19use libtest_mimic::{Arguments, Trial};
20use tokio::sync::OnceCell;
21
22/// `SimpleCoin`, whose `getBalance(address)` reads one storage slot.
23const SIMPLE_COIN_HEX: &str = include_str!("contracts/simple_coin/simple_coin.hex");
24const GET_BALANCE_SIGNATURE: &str = "getBalance(address)";
25
26/// `Filecoin.StateCall` gas limit parity tests
27#[derive(Debug, clap::Args)]
28pub struct StateCallTestCommand {}
29
30impl StateCallTestCommand {
31    pub async fn run(self) -> anyhow::Result<()> {
32        let args = Arguments {
33            test_threads: Some(1),
34            ..Default::default()
35        };
36        libtest_mimic::run(&args, tests()).exit();
37    }
38}
39
40fn tests() -> Vec<Trial> {
41    vec![
42        trial("state_call_runs_at_the_message_gas_limit", || {
43            block_on(state_call_runs_at_the_message_gas_limit())
44        }),
45        trial("state_call_charges_no_fees", || {
46            block_on(state_call_charges_no_fees())
47        }),
48    ]
49}
50
51/// `SimpleCoin`, deployed once per process.
52async fn contract() -> anyhow::Result<&'static EthAddress> {
53    static CONTRACT: OnceCell<EthAddress> = OnceCell::const_new();
54    CONTRACT
55        .get_or_try_init(|| deploy_contract("SimpleCoin", SIMPLE_COIN_HEX))
56        .await
57}
58
59/// `getBalance(sender)` on `SimpleCoin` from the sender, with the given gas limit.
60async fn get_balance_message(gas_limit: u64) -> anyhow::Result<Message> {
61    let (from, to) = tokio::try_join!(sender(), contract())?;
62    let msg = Message::try_from(EthCallMessage {
63        from: Some(from.eth),
64        to: Some(*to),
65        data: Some(EthBytes(calldata(
66            GET_BALANCE_SIGNATURE,
67            &abi_address_word(from.eth),
68        ))),
69        ..Default::default()
70    })?;
71    Ok(msg.into_builder().gas_limit(gas_limit).build())
72}
73
74fn receipt_of(result: &ApiInvocResult) -> anyhow::Result<&Receipt> {
75    result.msg_rct.as_ref().context("no receipt in the result")
76}
77
78/// A tipset both nodes have executed, so the two simulations start from the same state.
79async fn common_tipset(forest: &Client, lotus: &Client) -> anyhow::Result<ApiTipsetKey> {
80    let (forest_head, lotus_head) = tokio::try_join!(
81        async { anyhow::Ok(forest.call(ChainHead::request(())?).await?) },
82        async { anyhow::Ok(lotus.call(ChainHead::request(())?).await?) },
83    )?;
84    let epoch = forest_head.epoch().min(lotus_head.epoch());
85    let tipset = forest
86        .call(ChainGetTipSetByHeight::request((
87            epoch,
88            ApiTipsetKey(None),
89        ))?)
90        .await?;
91    Ok(tipset.key().into())
92}
93
94/// Both nodes and a tipset both have executed, so every call starts from the same state.
95struct Devnet {
96    forest: Client,
97    lotus: Client,
98    tipset: ApiTipsetKey,
99}
100
101impl Devnet {
102    /// Deploys the contract first, so the pinned tipset already has it on both nodes.
103    async fn pinned() -> anyhow::Result<Self> {
104        contract().await?;
105        let (forest, lotus) = (forest_client()?, lotus_client()?);
106        let tipset = common_tipset(&forest, &lotus).await?;
107        Ok(Self {
108            forest,
109            lotus,
110            tipset,
111        })
112    }
113
114    fn request(&self, msg: Message) -> anyhow::Result<Request<ApiInvocResult>> {
115        Ok(StateCall::request((msg, self.tipset.clone()))?)
116    }
117
118    /// Runs `msg` on both nodes, which must return the same result with `exit_code`.
119    async fn expect(&self, msg: Message, exit_code: ExitCode) -> anyhow::Result<ApiInvocResult> {
120        let request = self.request(msg)?;
121        let (forest, lotus) = tokio::try_join!(
122            async { anyhow::Ok(self.forest.call(request.clone()).await?) },
123            async { anyhow::Ok(self.lotus.call(request.clone()).await?) },
124        )?;
125        for (node, result) in [("forest", &forest), ("lotus", &lotus)] {
126            let exit = receipt_of(result).with_context(|| node)?.exit_code();
127            ensure!(
128                exit == exit_code,
129                "{node}: expected exit code {exit_code}, got {exit} ({})",
130                result.error
131            );
132        }
133        ensure!(
134            forest.msg == lotus.msg,
135            "echoed messages differ: forest {:?}, lotus {:?}",
136            forest.msg,
137            lotus.msg
138        );
139        ensure!(
140            forest.msg_cid == lotus.msg_cid,
141            "message CIDs differ: forest {}, lotus {}",
142            forest.msg_cid,
143            lotus.msg_cid
144        );
145        ensure!(
146            forest.msg_rct == lotus.msg_rct,
147            "receipts differ: forest {:?}, lotus {:?}",
148            forest.msg_rct,
149            lotus.msg_rct
150        );
151        ensure!(
152            forest.error == lotus.error,
153            "errors differ: forest `{}`, lotus `{}`",
154            forest.error,
155            lotus.error
156        );
157        ensure!(
158            forest.gas_cost == lotus.gas_cost,
159            "gas costs differ: forest {:?}, lotus {:?}",
160            forest.gas_cost,
161            lotus.gas_cost
162        );
163        ensure!(
164            forest.execution_trace == lotus.execution_trace,
165            "execution traces differ"
166        );
167        Ok(forest)
168    }
169
170    /// Sends `msg` to both nodes, which must both answer with a JSON-RPC error.
171    async fn expect_rejected(
172        &self,
173        msg: Message,
174    ) -> anyhow::Result<(ErrorObjectOwned, ErrorObjectOwned)> {
175        let request = self.request(msg)?;
176        tokio::try_join!(
177            rejection("forest", &self.forest, request.clone()),
178            rejection("lotus", &self.lotus, request)
179        )
180    }
181}
182
183async fn rejection(
184    node: &str,
185    client: &Client,
186    request: Request<ApiInvocResult>,
187) -> anyhow::Result<ErrorObjectOwned> {
188    let err = match client.call(request).await {
189        Ok(result) => bail!("{node} ran a message it must reject: {result:?}"),
190        Err(e) => anyhow::Error::from(e),
191    };
192    rpc_call_err(&err)
193        .cloned()
194        .with_context(|| format!("{node}: expected a JSON-RPC error, got {err:?}"))
195}
196
197/// Both nodes run the message at its own gas limit, treat `0` as the block gas limit, and reject a
198/// limit above it before running anything.
199async fn state_call_runs_at_the_message_gas_limit() -> anyhow::Result<()> {
200    let devnet = Devnet::pinned().await?;
201    let ok = ExitCode::OK;
202
203    // Gas 0 means the cap, the block gas limit by default.
204    let result = devnet.expect(get_balance_message(0).await?, ok).await?;
205    ensure!(
206        result.msg.gas_limit() == BLOCK_GAS_LIMIT,
207        "expected gas 0 to run at the block gas limit, got {}",
208        result.msg.gas_limit()
209    );
210    let gas_used = receipt_of(&result)?.gas_used();
211    ensure!(
212        gas_used > 1,
213        "expected getBalance to use gas, got {gas_used}"
214    );
215    eprintln!("getBalance used {gas_used} gas");
216
217    // Any other limit is the one the message runs at: enough gas succeeds, one unit short runs out.
218    let limits = [
219        ("exactly the gas used", gas_used, ok),
220        ("one unit short", gas_used - 1, ExitCode::SYS_OUT_OF_GAS),
221        ("the block gas limit", BLOCK_GAS_LIMIT, ok),
222    ];
223    for (label, limit, exit_code) in limits {
224        let result = devnet
225            .expect(get_balance_message(limit).await?, exit_code)
226            .await
227            .with_context(|| format!("at {label} ({limit})"))?;
228        ensure!(
229            result.msg.gas_limit() == limit,
230            "{label}: expected the message to run at {limit}, got {}",
231            result.msg.gas_limit()
232        );
233    }
234
235    // Above the cap is rejected before anything runs, with Lotus's text.
236    let expected = format!(
237        "StateCall gas limit {} exceeds configured cap {BLOCK_GAS_LIMIT}",
238        BLOCK_GAS_LIMIT + 1
239    );
240    let (forest, lotus) = devnet
241        .expect_rejected(get_balance_message(BLOCK_GAS_LIMIT + 1).await?)
242        .await?;
243    for (node, err) in [("forest", &forest), ("lotus", &lotus)] {
244        ensure!(
245            err.message().contains(&expected),
246            "{node}: expected `{expected}`, got `{}`",
247            err.message()
248        );
249    }
250    Ok(())
251}
252
253/// A realistic limit changes nothing about fees: the call is applied without checking or charging
254/// them, so fees the sender could never pay still run and come back echoed as given.
255async fn state_call_charges_no_fees() -> anyhow::Result<()> {
256    let devnet = Devnet::pinned().await?;
257    let unpayable = TokenAmount::from_whole(1_000_000u64);
258    let priced = get_balance_message(0)
259        .await?
260        .into_builder()
261        .gas_fee_cap(unpayable.clone())
262        .gas_premium(unpayable.clone())
263        .build();
264    let result = devnet.expect(priced, ExitCode::OK).await?;
265    ensure!(
266        result.msg.gas_fee_cap() == &unpayable && result.msg.gas_premium() == &unpayable,
267        "expected the fees echoed as given, got {:?}",
268        result.msg
269    );
270    Ok(())
271}