Skip to main content

forest/message/
mod.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4pub mod chain_message;
5pub mod signed_message;
6
7use crate::shim::{address::Address, econ::TokenAmount, message::Message};
8use crate::shim::{gas::Gas, version::NetworkVersion};
9use ambassador::delegatable_trait;
10pub use chain_message::ChainMessage;
11use num::Zero;
12pub use signed_message::SignedMessage;
13
14/// Message interface to make read-only interactions with Signed and unsigned messages in a generic
15/// context.
16#[auto_impl::auto_impl(&, Arc)]
17#[delegatable_trait]
18pub trait MessageRead {
19    /// Returns the message the VM executes. For a signed message this is the inner unsigned
20    /// message.
21    ///
22    /// Mirrors Lotus [`ChainMsg.VMMessage`](https://github.com/filecoin-project/lotus/blob/a56f7b7399c2804cdab1a230b0efbd92b1694617/chain/types/message.go#L134-L136).
23    fn vm_message(&self) -> &Message;
24    /// Returns the number of bytes this message contributes to the chain, which is what on-chain
25    /// gas is charged for. A `Secp256k1` or delegated signature counts towards it; a BLS signature
26    /// does not, because it is aggregated into the block header.
27    ///
28    /// Mirrors Lotus [`ChainMsg.ChainLength`](https://github.com/filecoin-project/lotus/blob/a56f7b7399c2804cdab1a230b0efbd92b1694617/chain/types/signedmessage.go#L86-L98).
29    fn chain_length(&self) -> anyhow::Result<usize>;
30    /// Returns the from address of the message.
31    fn from(&self) -> Address;
32    /// Returns the destination address of the message.
33    fn to(&self) -> Address;
34    /// Returns the message sequence or nonce.
35    fn sequence(&self) -> u64;
36    /// Returns the amount sent in message.
37    fn value(&self) -> &TokenAmount;
38    /// Returns the gas limit for the message.
39    fn gas_limit(&self) -> u64;
40    /// Returns the required funds for the message.
41    fn required_funds(&self) -> TokenAmount;
42    /// gets gas fee cap for the message.
43    fn gas_fee_cap(&self) -> &TokenAmount;
44    /// gets gas premium for the message.
45    fn gas_premium(&self) -> &TokenAmount;
46    /// This method returns the effective gas premium claimable by the miner
47    /// given the supplied base fee. This method is not used anywhere except the `Eth` API.
48    ///
49    /// Filecoin clamps the gas premium at `gas_fee_cap` - `base_fee`, if lower than the
50    /// specified premium. Returns 0 if `gas_fee_cap` is less than `base_fee`.
51    fn effective_gas_premium(&self, base_fee: &TokenAmount) -> TokenAmount {
52        let available = self.gas_fee_cap() - base_fee;
53        // It's possible that storage providers may include messages with gasFeeCap less than the baseFee
54        // In such cases, their reward should be viewed as zero
55        available.clamp(TokenAmount::zero(), self.gas_premium().clone())
56    }
57}
58
59/// Semantic validation and validates the message has enough gas.
60pub fn valid_for_block_inclusion(
61    msg: &Message,
62    min_gas: Gas,
63    version: NetworkVersion,
64) -> anyhow::Result<()> {
65    use crate::shim::address::ZERO_ADDRESS;
66    use crate::shim::econ::{BLOCK_GAS_LIMIT, TOTAL_FILECOIN};
67    if msg.version() != 0 {
68        anyhow::bail!("Message version: {} not supported", msg.version());
69    }
70    if msg.to() == *ZERO_ADDRESS && version >= NetworkVersion::V7 {
71        anyhow::bail!("invalid 'to' address");
72    }
73    if msg.value().is_negative() {
74        anyhow::bail!("message value cannot be negative");
75    }
76    if *msg.value() > *TOTAL_FILECOIN {
77        anyhow::bail!("message value cannot be greater than total FIL supply");
78    }
79    if msg.gas_fee_cap().is_negative() {
80        anyhow::bail!("gas_fee_cap cannot be negative");
81    }
82    if msg.gas_premium().is_negative() {
83        anyhow::bail!("gas_premium cannot be negative");
84    }
85    if msg.gas_premium() > msg.gas_fee_cap() {
86        anyhow::bail!("gas_fee_cap less than gas_premium");
87    }
88    if msg.gas_limit() > BLOCK_GAS_LIMIT {
89        anyhow::bail!(
90            "gas_limit {} cannot be greater than block gas limit",
91            msg.gas_limit()
92        );
93    }
94
95    if Gas::new(msg.gas_limit()) < min_gas {
96        anyhow::bail!(
97            "gas_limit {} cannot be less than cost {} of storing a message on chain",
98            msg.gas_limit(),
99            min_gas
100        );
101    }
102
103    Ok(())
104}
105
106#[cfg(test)]
107mod tests {
108    mod builder_test;
109
110    use rstest::rstest;
111
112    use super::*;
113    use crate::shim::crypto::{SECP_SIG_LEN, Signature};
114    use crate::shim::gas::price_list_by_network_version;
115
116    #[test]
117    fn gas_limit_below_min_gas_rejected_for_block_inclusion() {
118        let msg = Message::builder().gas_limit(0).build();
119        let err = valid_for_block_inclusion(&msg, Gas::new(1), NetworkVersion::V0)
120            .expect_err("gas_limit below min_gas must be rejected");
121        assert!(
122            err.to_string().contains("less than cost"),
123            "expected the gas-limit floor to reject, got: {err}"
124        );
125    }
126
127    /// The floor is charged over the signed encoding for `Secp256k1` and delegated messages, so a
128    /// gas limit that only covers the unsigned encoding must be rejected.
129    ///
130    /// See Lotus [`checkMsg`](https://github.com/filecoin-project/lotus/blob/a56f7b7399c2804cdab1a230b0efbd92b1694617/chain/consensus/common.go#L217-L223).
131    #[rstest]
132    #[case(Signature::new_secp256k1(vec![0; SECP_SIG_LEN]))]
133    #[case(Signature::new_delegated(vec![0; SECP_SIG_LEN]))]
134    fn block_inclusion_floor_counts_signature_bytes(#[case] signature: Signature) {
135        let network_version = NetworkVersion::V29;
136        let price_list = price_list_by_network_version(network_version);
137        let signed = SignedMessage::new_unchecked(
138            Message::builder()
139                .to(Address::new_id(1))
140                .from(Address::new_id(2))
141                .build(),
142            signature,
143        );
144
145        let floor = |len| price_list.on_chain_message(len).total();
146        let signed_floor = floor(signed.chain_length().unwrap());
147        let unsigned_floor = floor(signed.vm_message().chain_length().unwrap());
148        assert!(
149            signed_floor > unsigned_floor,
150            "signature bytes must raise the floor, got {signed_floor} and {unsigned_floor}"
151        );
152
153        let underpaying = signed
154            .message()
155            .clone()
156            .into_builder()
157            .gas_limit(unsigned_floor.round_up())
158            .build();
159        assert!(
160            valid_for_block_inclusion(&underpaying, unsigned_floor, network_version).is_ok(),
161            "this is the message the unsigned floor used to accept"
162        );
163        assert!(
164            valid_for_block_inclusion(&underpaying, signed_floor, network_version).is_err(),
165            "a gas limit covering only the unsigned encoding must be rejected"
166        );
167
168        let paying = signed
169            .message()
170            .clone()
171            .into_builder()
172            .gas_limit(signed_floor.round_up())
173            .build();
174        valid_for_block_inclusion(&paying, signed_floor, network_version)
175            .expect("a gas limit covering the signed encoding must be accepted");
176    }
177
178    #[test]
179    fn vm_message_is_the_unsigned_message() {
180        let message = Message::builder()
181            .to(Address::new_id(1))
182            .from(Address::new_id(2))
183            .build();
184        let signed = SignedMessage::new_unchecked(
185            message.clone(),
186            Signature::new_secp256k1(vec![0; SECP_SIG_LEN]),
187        );
188
189        assert_eq!(message.vm_message(), &message);
190        assert_eq!(signed.vm_message(), &message);
191    }
192
193    // Test cases from the FIP-0115
194    // <https://github.com/filecoin-project/FIPs/blob/b84b89a34ccb3d239493392a7867d6b082193b38/FIPS/fip-0115.md#premium>>
195    #[rstest]
196    #[case::fee_cap_equals_base_fee(8, 8, 8, 0)]
197    #[case::premium_below_headroom(8, 16, 7, 7)]
198    #[case::premium_well_below_headroom(8, 19, 10, 10)]
199    #[case::fee_cap_below_base_fee(123456, 123455, 123455, 0)]
200    #[case::premium_capped_by_headroom(123456, 1234567, 1111112, 1111111)]
201    fn test_effective_gas_premium(
202        #[case] base_fee: u64,
203        #[case] gas_fee_cap: u64,
204        #[case] gas_premium: u64,
205        #[case] expected: u64,
206    ) {
207        let msg = Message::builder()
208            .gas_fee_cap(TokenAmount::from_atto(gas_fee_cap))
209            .gas_premium(TokenAmount::from_atto(gas_premium))
210            .build();
211
212        let result = msg.effective_gas_premium(&TokenAmount::from_atto(base_fee));
213        assert_eq!(result, TokenAmount::from_atto(expected));
214    }
215}