forest/dev/subcommands/devnet_cmd/
state_call.rs1use 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
22const SIMPLE_COIN_HEX: &str = include_str!("contracts/simple_coin/simple_coin.hex");
24const GET_BALANCE_SIGNATURE: &str = "getBalance(address)";
25
26#[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
51async 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
59async 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
78async 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
94struct Devnet {
96 forest: Client,
97 lotus: Client,
98 tipset: ApiTipsetKey,
99}
100
101impl Devnet {
102 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 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 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
197async fn state_call_runs_at_the_message_gas_limit() -> anyhow::Result<()> {
200 let devnet = Devnet::pinned().await?;
201 let ok = ExitCode::OK;
202
203 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 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 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
253async 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}