Skip to main content

forest/message/
signed_message.rs

1// Copyright 2019-2026 ChainSafe Systems
2// SPDX-License-Identifier: Apache-2.0, MIT
3
4use super::MessageRead;
5use crate::eth::EthChainId;
6use crate::shim::{
7    address::Address,
8    crypto::{Signature, SignatureType},
9    econ::TokenAmount,
10    message::Message,
11};
12use crate::utils::cid::{EncodedCbor, Memo};
13use get_size2::GetSize;
14
15/// Represents a wrapped message with signature bytes.
16#[cfg_attr(test, derive(derive_quickcheck_arbitrary::Arbitrary))]
17#[derive(Clone, Debug, PartialEq, Eq, Hash, GetSize)]
18pub struct SignedMessage {
19    message: Message,
20    signature: Signature,
21    /// The memoized CID and length of the signed encoding. A `SignedMessage` is immutable, so
22    /// this cannot outlive what it was derived from. Excluded from the derived
23    /// `PartialEq`/`Eq`/`Hash`/`Debug` by [`Memo`].
24    #[cfg_attr(test, arbitrary(gen(|_| Memo::default())))]
25    encoded: Memo,
26}
27
28impl serde::Serialize for SignedMessage {
29    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
30        (&self.message, &self.signature).serialize(s)
31    }
32}
33
34impl<'de> serde::Deserialize<'de> for SignedMessage {
35    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
36        let (message, signature) = serde::Deserialize::deserialize(deserializer)?;
37        Ok(Self {
38            message,
39            signature,
40            encoded: Memo::default(),
41        })
42    }
43}
44
45impl SignedMessage {
46    /// Generate a new signed message from fields.
47    /// The signature will be verified.
48    pub fn new_from_parts(message: Message, signature: Signature) -> anyhow::Result<SignedMessage> {
49        signature.verify(&message.cid().to_bytes(), &message.from())?;
50        Ok(SignedMessage::new_unchecked(message, signature))
51    }
52
53    /// Generate a new signed message from fields.
54    /// The signature will not be verified.
55    pub fn new_unchecked(message: Message, signature: Signature) -> SignedMessage {
56        SignedMessage {
57            message,
58            signature,
59            encoded: Memo::default(),
60        }
61    }
62
63    /// Returns reference to the unsigned message.
64    pub fn message(&self) -> &Message {
65        &self.message
66    }
67
68    /// Returns signature of the signed message.
69    pub fn signature(&self) -> &Signature {
70        &self.signature
71    }
72
73    /// Consumes self and returns it's unsigned message.
74    pub fn into_message(self) -> Message {
75        self.message
76    }
77
78    pub fn into_parts(self) -> (Message, Signature) {
79        (self.message, self.signature)
80    }
81
82    /// Checks if the signed message is a BLS message.
83    pub fn is_bls(&self) -> bool {
84        self.signature.signature_type() == SignatureType::Bls
85    }
86
87    /// Checks if the signed message is a SECP message.
88    pub fn is_secp256k1(&self) -> bool {
89        self.signature.signature_type() == SignatureType::Secp256k1
90    }
91
92    /// Checks if the signed message is a delegated message.
93    pub fn is_delegated(&self) -> bool {
94        self.signature.signature_type() == SignatureType::Delegated
95    }
96
97    /// Verifies that the from address of the message generated the signature.
98    pub fn verify(&self, eth_chain_id: EthChainId) -> anyhow::Result<()> {
99        self.signature
100            .authenticate_msg(eth_chain_id, self, &self.from())
101    }
102
103    // Important note: `msg.cid()` is different from
104    // `Cid::from_cbor_blake2b256(msg)`. The behavior comes from Lotus, and
105    // Lotus, by, definition, is correct.
106    pub fn cid(&self) -> cid::Cid {
107        if self.is_bls() {
108            self.message.cid()
109        } else {
110            self.encoded().cid()
111        }
112    }
113
114    /// The CID of the signed encoding, which is what a block's `SECP` message root is built from.
115    /// Differs from [`SignedMessage::cid`] only for a BLS signature, which a `SECP` message list
116    /// may not carry.
117    pub fn signed_cid(&self) -> cid::Cid {
118        self.encoded().cid()
119    }
120
121    /// The length of the signed encoding, which is what a message's size on the wire is measured
122    /// against. Differs from [`MessageRead::chain_length`] for a BLS signature, which is excluded
123    /// from the chain length but not from the message itself.
124    pub fn signed_encoded_len(&self) -> usize {
125        self.encoded().byte_len()
126    }
127
128    fn encoded(&self) -> &EncodedCbor {
129        self.encoded.get_or_init(|| {
130            EncodedCbor::compute(self).expect("message serialization is infallible")
131        })
132    }
133
134    /// Creates a mock signed message for testing purposes. The signature check will fail if
135    /// invoked.
136    #[cfg(test)]
137    pub fn mock_bls_signed_message(message: Message) -> SignedMessage {
138        let signature = Signature::new_bls(vec![0; crate::shim::crypto::BLS_SIG_LEN]);
139        SignedMessage::new_unchecked(message, signature)
140    }
141}
142
143impl MessageRead for SignedMessage {
144    fn vm_message(&self) -> &Message {
145        &self.message
146    }
147    fn chain_length(&self) -> anyhow::Result<usize> {
148        Ok(match self.signature.signature_type() {
149            // BLS chain message length doesn't include the signature
150            SignatureType::Bls => self.message.encoded_len(),
151            // SECP and Delegated chain message length includes the signature
152            SignatureType::Secp256k1 | SignatureType::Delegated => self.encoded().byte_len(),
153        })
154    }
155    fn from(&self) -> Address {
156        self.message.from()
157    }
158    fn to(&self) -> Address {
159        self.message.to()
160    }
161    fn sequence(&self) -> u64 {
162        self.message.sequence()
163    }
164    fn value(&self) -> &TokenAmount {
165        self.message.value()
166    }
167    fn gas_limit(&self) -> u64 {
168        self.message.gas_limit()
169    }
170    fn required_funds(&self) -> TokenAmount {
171        self.message.required_funds()
172    }
173    fn gas_fee_cap(&self) -> &TokenAmount {
174        self.message.gas_fee_cap()
175    }
176    fn gas_premium(&self) -> &TokenAmount {
177        self.message.gas_premium()
178    }
179}
180
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use crate::shim::{
185        address::Address,
186        crypto::{BLS_SIG_LEN, SECP_SIG_LEN, Signature},
187        message::Message,
188    };
189    use crate::utils::cid::CidCborExt as _;
190    use cid::Cid;
191    use fvm_ipld_encoding::to_vec;
192    use quickcheck_macros::quickcheck;
193
194    fn hash_of<T: std::hash::Hash>(value: &T) -> u64 {
195        use std::hash::Hasher as _;
196        let mut hasher = std::collections::hash_map::DefaultHasher::new();
197        value.hash(&mut hasher);
198        hasher.finish()
199    }
200
201    /// `Arbitrary` always yields cold memos, so both must be warmed here to reach the case the
202    /// derived `PartialEq`/`Hash`/`Debug` must stay blind to.
203    #[quickcheck]
204    fn computing_the_memos_is_invisible(msg: SignedMessage) -> bool {
205        let warm = msg.clone();
206        let (_, _) = (warm.cid(), warm.signed_cid());
207        warm == msg && hash_of(&warm) == hash_of(&msg) && format!("{warm:?}") == format!("{msg:?}")
208    }
209
210    #[quickcheck]
211    fn signed_cid_and_len_match_the_unmemoized_path(msg: SignedMessage) -> bool {
212        msg.signed_cid() == Cid::from_cbor_blake2b256(&msg).unwrap()
213            && msg.signed_encoded_len() == to_vec(&msg).unwrap().len()
214    }
215
216    #[track_caller]
217    fn assert_measures_and_hashes(signed: &SignedMessage, encoded: &[u8]) {
218        assert_eq!(signed.chain_length().unwrap(), encoded.len());
219        assert_eq!(
220            signed.cid(),
221            Cid::from_cbor_encoded_raw_bytes_blake2b256(encoded)
222        );
223    }
224
225    /// Anchors both values to the Lotus rule, which a test derived from the same `match` as the
226    /// implementation cannot do.
227    #[test]
228    fn chain_length_and_cid_follow_signature_type() {
229        let message = Message::builder()
230            .to(Address::new_id(1))
231            .from(Address::new_id(2))
232            .build();
233
234        // BLS signatures are aggregated into the block header, so they count for neither value.
235        let bls =
236            SignedMessage::new_unchecked(message.clone(), Signature::new_bls(vec![0; BLS_SIG_LEN]));
237        assert_measures_and_hashes(&bls, &to_vec(&message).unwrap());
238
239        for signature in [
240            Signature::new_secp256k1(vec![0; SECP_SIG_LEN]),
241            Signature::new_delegated(vec![0; SECP_SIG_LEN]),
242        ] {
243            let signed = SignedMessage::new_unchecked(message.clone(), signature);
244            assert_measures_and_hashes(&signed, &to_vec(&signed).unwrap());
245        }
246    }
247
248    /// Pins the hand-written [`serde`] code to the `Serialize_tuple` derive it replaced, which
249    /// no round-trip test can do on its own.
250    #[quickcheck]
251    fn signed_encoding_matches_the_tuple_derive(msg: SignedMessage) -> bool {
252        use fvm_ipld_encoding::tuple::*;
253
254        #[derive(Serialize_tuple)]
255        struct Reference<'a> {
256            message: &'a Message,
257            signature: &'a Signature,
258        }
259
260        to_vec(&msg).unwrap()
261            == to_vec(&Reference {
262                message: msg.message(),
263                signature: msg.signature(),
264            })
265            .unwrap()
266    }
267
268    /// The signature type selects one encoding for both the CID and the chain length, so the two
269    /// cannot be allowed to disagree about which bytes they mean.
270    #[quickcheck]
271    fn chain_length_measures_the_bytes_the_cid_hashes(msg: SignedMessage) -> bool {
272        [to_vec(msg.message()).unwrap(), to_vec(&msg).unwrap()]
273            .into_iter()
274            .find(|bytes| Cid::from_cbor_encoded_raw_bytes_blake2b256(bytes) == msg.cid())
275            .is_some_and(|bytes| msg.chain_length().unwrap() == bytes.len())
276    }
277}