Skip to main content

forest/message/
chain_message.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use super::*;
5use crate::message::signed_message::SignedMessage;
6use crate::shim::address::Protocol;
7use crate::shim::crypto::{SECP_SIG_LEN, Signature, SignatureType};
8use crate::shim::{address::Address, econ::TokenAmount, message::Message};
9use ambassador::Delegate;
10use get_size2::GetSize;
11use serde::{Deserialize, Serialize};
12use spire_enum::prelude::delegated_enum;
13use std::sync::Arc;
14
15/// `Enum` to encapsulate signed and unsigned messages. Useful when working with
16/// both types
17#[delegated_enum]
18#[derive(
19    Clone, Debug, Serialize, Deserialize, Hash, Eq, PartialEq, GetSize, derive_more::From, Delegate,
20)]
21#[delegate(MessageRead)]
22#[serde(untagged)]
23pub enum ChainMessage {
24    Unsigned(Arc<Message>),
25    Signed(Arc<SignedMessage>),
26}
27
28impl From<Message> for ChainMessage {
29    fn from(msg: Message) -> Self {
30        Arc::new(msg).into()
31    }
32}
33
34impl From<SignedMessage> for ChainMessage {
35    fn from(msg: SignedMessage) -> Self {
36        Arc::new(msg).into()
37    }
38}
39
40impl ChainMessage {
41    pub fn message(&self) -> &Message {
42        match self {
43            Self::Unsigned(m) => m,
44            Self::Signed(sm) => sm.message(),
45        }
46    }
47
48    pub fn cid(&self) -> cid::Cid {
49        delegate_chain_message!(self.cid())
50    }
51
52    /// The length of this message's own encoding, signature included. Not
53    /// [`MessageRead::chain_length`], which drops a BLS signature.
54    pub fn encoded_len(&self) -> usize {
55        match self {
56            Self::Unsigned(msg) => msg.encoded_len(),
57            Self::Signed(msg) => msg.signed_encoded_len(),
58        }
59    }
60
61    /// Tests if a message is equivalent to another replacing message.
62    /// A replacing message is a message with a different CID,
63    /// any of Gas values, and different signature, but with all
64    /// other parameters matching (source/destination, nonce, parameters, etc.)
65    /// See <https://github.com/filecoin-project/lotus/blob/813d133c24295629ef442fc3aa60e6e6b2101226/chain/types/message.go#L138>
66    pub fn equal_call(&self, other: &Self) -> bool {
67        self.message().equal_call(other.message())
68    }
69
70    /// Wrap `msg` for gas estimation so its on-chain size approximates a
71    /// real submission — the FVM charges per-byte gas based on the wire
72    /// encoding including the signature. Mirrors Lotus's
73    /// [`CallWithGas`](https://github.com/filecoin-project/lotus/blob/4a72a61c704d64228b4d91c497948442a9bfd235/chain/stmgr/call.go#L247-L267):
74    /// SECP256k1 / Delegated get a 65-byte zero-filled signature; BLS and
75    /// all other protocols (ID, Actor) get the unsigned message.
76    pub fn for_gas_estimation(msg: Message, from_protocol: Protocol) -> Self {
77        match from_protocol {
78            Protocol::Secp256k1 => {
79                SignedMessage::new_unchecked(msg, Signature::new_secp256k1(vec![0; SECP_SIG_LEN]))
80                    .into()
81            }
82            // Lotus uses the same signature length as Secp256k1 for Delegated.
83            Protocol::Delegated => SignedMessage::new_unchecked(
84                msg,
85                Signature::new(SignatureType::Delegated, vec![0; SECP_SIG_LEN]),
86            )
87            .into(),
88            _ => msg.into(),
89        }
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    use crate::shim::crypto::BLS_SIG_LEN;
97    use crate::utils::encoding::calc_encoded_len;
98    use quickcheck_macros::quickcheck;
99
100    /// The memo travels with the `Arc`, so the derived `PartialEq`/`Hash` must stay blind to it
101    /// here too.
102    #[quickcheck]
103    fn computing_the_memo_is_invisible(msg: SignedMessage) -> bool {
104        use std::hash::Hasher as _;
105        let hash_of = |value: &ChainMessage| {
106            let mut hasher = std::collections::hash_map::DefaultHasher::new();
107            std::hash::Hash::hash(value, &mut hasher);
108            hasher.finish()
109        };
110        // Two independent `Arc`s: cloning a `ChainMessage` would alias one memo and warm both.
111        let cold: ChainMessage = msg.clone().into();
112        let warm: ChainMessage = msg.into();
113        let _ = warm.encoded_len();
114        warm == cold && hash_of(&warm) == hash_of(&cold)
115    }
116
117    /// `encoded_len` must measure the bytes this value serializes to, for every variant: the
118    /// `#[serde(untagged)]` encoding is the inner message's, signature included.
119    #[quickcheck]
120    fn encoded_len_measures_the_serialized_bytes(msg: Message, sig_bytes: Vec<u8>) -> bool {
121        let signatures = [
122            Signature::new_secp256k1(sig_bytes.clone()),
123            Signature::new(SignatureType::Delegated, sig_bytes),
124            Signature::new_bls(vec![0; BLS_SIG_LEN]),
125        ];
126        let unsigned: ChainMessage = msg.clone().into();
127        let mut candidates = std::iter::once(unsigned).chain(
128            signatures
129                .into_iter()
130                .map(|sig| SignedMessage::new_unchecked(msg.clone(), sig).into()),
131        );
132        candidates.all(|chain_msg: ChainMessage| {
133            chain_msg.encoded_len() == calc_encoded_len(&chain_msg).unwrap()
134        })
135    }
136
137    fn dummy_msg() -> Message {
138        Message::builder()
139            .from(Address::new_id(2))
140            .to(Address::new_id(1))
141            .build()
142    }
143
144    #[track_caller]
145    fn assert_signed_with_zero_sig(
146        chain_msg: ChainMessage,
147        sig_type: SignatureType,
148        msg: &Message,
149    ) {
150        let ChainMessage::Signed(signed) = chain_msg else {
151            panic!("expected Signed variant");
152        };
153        assert_eq!(signed.signature().signature_type(), sig_type);
154        assert_eq!(signed.signature().bytes(), &vec![0; SECP_SIG_LEN]);
155        assert_eq!(signed.message(), msg);
156    }
157
158    #[track_caller]
159    fn assert_unsigned(chain_msg: ChainMessage, msg: &Message) {
160        let ChainMessage::Unsigned(m) = chain_msg else {
161            panic!("expected Unsigned variant");
162        };
163        assert_eq!(&*m, msg);
164    }
165
166    #[test]
167    fn test_for_gas_estimation_secp256k1() {
168        let msg = dummy_msg();
169        let chain_msg = ChainMessage::for_gas_estimation(msg.clone(), Protocol::Secp256k1);
170        assert_signed_with_zero_sig(chain_msg, SignatureType::Secp256k1, &msg);
171    }
172
173    #[test]
174    fn test_for_gas_estimation_delegated() {
175        let msg = dummy_msg();
176        let chain_msg = ChainMessage::for_gas_estimation(msg.clone(), Protocol::Delegated);
177        // Lotus uses the same signature length as Secp256k1 for delegated; this
178        // lock-in prevents an accidental length change from regressing parity.
179        assert_signed_with_zero_sig(chain_msg, SignatureType::Delegated, &msg);
180    }
181
182    #[test]
183    fn test_for_gas_estimation_bls() {
184        let msg = dummy_msg();
185        let chain_msg = ChainMessage::for_gas_estimation(msg.clone(), Protocol::BLS);
186        // Lotus passes BLS senders to ApplyMessage as the raw unsigned message
187        // (see chain/stmgr/call.go); matching that here.
188        assert_unsigned(chain_msg, &msg);
189    }
190
191    #[test]
192    fn test_for_gas_estimation_id() {
193        let msg = dummy_msg();
194        let chain_msg = ChainMessage::for_gas_estimation(msg.clone(), Protocol::ID);
195        assert_unsigned(chain_msg, &msg);
196    }
197
198    #[test]
199    fn test_for_gas_estimation_actor() {
200        let msg = dummy_msg();
201        let chain_msg = ChainMessage::for_gas_estimation(msg.clone(), Protocol::Actor);
202        assert_unsigned(chain_msg, &msg);
203    }
204}