1use anyhow::anyhow;
5use fvm_ipld_encoding::{RawBytes, de::Deserializer, ser::Serializer};
6use fvm_shared2::message::Message as Message_v2;
7pub use fvm_shared3::METHOD_SEND;
8pub use fvm_shared3::message::Message as Message_v3;
9pub use fvm_shared4::message::Message as Message_v4;
10use get_size2::GetSize;
11use serde::{Deserialize, Serialize};
12
13use crate::shim::{address::Address, econ::TokenAmount};
14use crate::utils::cid::{EncodedCbor, Memo};
15use crate::utils::get_size::raw_bytes_heap_size_helper;
16
17pub type MethodNum = u64;
19
20#[derive(Clone, Default, PartialEq, Eq, Debug, Hash, GetSize, derive_builder::Builder)]
21#[cfg_attr(test, derive(derive_quickcheck_arbitrary::Arbitrary))]
22#[builder(
23 default,
24 pattern = "owned",
25 build_fn(private, name = "build_infallible", error = "std::convert::Infallible")
26)]
27pub struct Message {
28 version: u64,
29 from: Address,
30 to: Address,
31 sequence: u64,
32 value: TokenAmount,
33 method_num: MethodNum,
34 #[cfg_attr(test, arbitrary(gen(
35 |g| RawBytes::new(Vec::arbitrary(g))
36 )))]
37 #[get_size(size_fn = raw_bytes_heap_size_helper)]
38 params: RawBytes,
39 gas_limit: u64,
40 gas_fee_cap: TokenAmount,
41 gas_premium: TokenAmount,
42 #[builder(setter(skip))]
46 #[cfg_attr(test, arbitrary(gen(|_| Memo::default())))]
47 encoded: Memo,
48}
49
50impl crate::message::MessageRead for Message {
51 fn vm_message(&self) -> &Message {
52 self
53 }
54 fn chain_length(&self) -> anyhow::Result<usize> {
55 Ok(self.encoded_len())
56 }
57 fn from(&self) -> Address {
58 self.from
59 }
60 fn to(&self) -> Address {
61 self.to
62 }
63 fn sequence(&self) -> u64 {
64 self.sequence
65 }
66 fn value(&self) -> &TokenAmount {
67 &self.value
68 }
69 fn gas_limit(&self) -> u64 {
70 self.gas_limit
71 }
72 fn required_funds(&self) -> TokenAmount {
73 &self.gas_fee_cap * self.gas_limit
74 }
75 fn gas_fee_cap(&self) -> &TokenAmount {
76 &self.gas_fee_cap
77 }
78 fn gas_premium(&self) -> &TokenAmount {
79 &self.gas_premium
80 }
81}
82
83impl MessageBuilder {
84 pub fn build(self) -> Message {
86 let Ok(message) = self.build_infallible();
87 message
88 }
89}
90
91impl Message {
92 pub fn builder() -> MessageBuilder {
94 MessageBuilder::default()
95 }
96
97 pub fn into_builder(self) -> MessageBuilder {
100 let Self {
101 version,
102 from,
103 to,
104 sequence,
105 value,
106 method_num,
107 params,
108 gas_limit,
109 gas_fee_cap,
110 gas_premium,
111 encoded: _,
112 } = self;
113 MessageBuilder::default()
114 .version(version)
115 .from(from)
116 .to(to)
117 .sequence(sequence)
118 .value(value)
119 .method_num(method_num)
120 .params(params)
121 .gas_limit(gas_limit)
122 .gas_fee_cap(gas_fee_cap)
123 .gas_premium(gas_premium)
124 }
125
126 pub fn version(&self) -> u64 {
127 self.version
128 }
129
130 pub fn from(&self) -> Address {
131 self.from
132 }
133
134 pub fn to(&self) -> Address {
135 self.to
136 }
137
138 pub fn sequence(&self) -> u64 {
139 self.sequence
140 }
141
142 pub fn method_num(&self) -> MethodNum {
143 self.method_num
144 }
145
146 pub fn params(&self) -> &RawBytes {
147 &self.params
148 }
149
150 pub fn gas_limit(&self) -> u64 {
151 self.gas_limit
152 }
153
154 pub fn value(&self) -> &TokenAmount {
155 &self.value
156 }
157
158 pub fn gas_fee_cap(&self) -> &TokenAmount {
159 &self.gas_fee_cap
160 }
161
162 pub fn gas_premium(&self) -> &TokenAmount {
163 &self.gas_premium
164 }
165}
166
167macro_rules! message_conversion {
168 ($($version:ty),+ $(,)?) => {
169 $(
170 impl From<$version> for Message {
171 fn from(other: $version) -> Self {
172 Self {
173 version: other.version,
174 from: other.from.into(),
175 to: other.to.into(),
176 sequence: other.sequence,
177 value: other.value.into(),
178 method_num: other.method_num,
179 params: other.params,
180 gas_limit: other.gas_limit,
181 gas_fee_cap: other.gas_fee_cap.into(),
182 gas_premium: other.gas_premium.into(),
183 encoded: Memo::default(),
184 }
185 }
186 }
187
188 impl From<Message> for $version {
189 fn from(other: Message) -> Self {
190 Self {
191 version: other.version,
192 from: other.from.into(),
193 to: other.to.into(),
194 sequence: other.sequence,
195 value: other.value.into(),
196 method_num: other.method_num,
197 params: other.params,
198 gas_limit: other.gas_limit,
199 gas_fee_cap: other.gas_fee_cap.into(),
200 gas_premium: other.gas_premium.into(),
201 }
202 }
203 }
204
205 impl From<&Message> for $version {
206 fn from(other: &Message) -> Self {
207 other.clone().into()
208 }
209 }
210 )+
211 };
212}
213
214message_conversion!(Message_v3, Message_v4);
215
216impl From<Message_v2> for Message {
217 fn from(other: Message_v2) -> Self {
218 Self {
219 version: other.version as u64,
220 from: other.from.into(),
221 to: other.to.into(),
222 sequence: other.sequence,
223 value: other.value.into(),
224 method_num: other.method_num,
225 params: other.params,
226 gas_limit: other.gas_limit as u64,
227 gas_fee_cap: other.gas_fee_cap.into(),
228 gas_premium: other.gas_premium.into(),
229 encoded: Memo::default(),
230 }
231 }
232}
233
234impl TryFrom<Message> for Message_v2 {
236 type Error = anyhow::Error;
237
238 fn try_from(other: Message) -> Result<Self, Self::Error> {
239 Ok(Self {
240 version: other.version as i64,
241 from: other.from.try_to_v2()?,
242 to: other.to.try_to_v2()?,
243 sequence: other.sequence,
244 value: other.value.into(),
245 method_num: other.method_num,
246 params: other.params,
247 gas_limit: other.gas_limit as i64,
248 gas_fee_cap: other.gas_fee_cap.into(),
249 gas_premium: other.gas_premium.into(),
250 })
251 }
252}
253
254impl TryFrom<&Message> for Message_v2 {
255 type Error = anyhow::Error;
256
257 fn try_from(other: &Message) -> Result<Self, Self::Error> {
258 other.clone().try_into()
259 }
260}
261
262impl Message {
263 pub fn check(self: &Message) -> anyhow::Result<()> {
265 if self.gas_limit == 0 {
266 return Err(anyhow!("Message has no gas limit set"));
267 }
268 if self.gas_limit > i64::MAX as u64 {
269 return Err(anyhow!("Message gas exceeds i64 max"));
270 }
271 Ok(())
272 }
273
274 pub fn transfer(from: Address, to: Address, value: TokenAmount) -> Self {
276 Message {
277 from,
278 to,
279 value,
280 method_num: METHOD_SEND,
281 ..Default::default()
282 }
283 }
284
285 pub fn cid(&self) -> cid::Cid {
286 self.encoded().cid()
287 }
288
289 pub fn encoded_len(&self) -> usize {
291 self.encoded().byte_len()
292 }
293
294 fn encoded(&self) -> &EncodedCbor {
295 self.encoded.get_or_init(|| {
296 EncodedCbor::compute(self).expect("message serialization is infallible")
297 })
298 }
299
300 pub fn equal_call(&self, other: &Self) -> bool {
306 self.version == other.version
307 && self.from == other.from
308 && self.to == other.to
309 && self.sequence == other.sequence
310 && self.value == other.value
311 && self.method_num == other.method_num
312 && self.params == other.params
313 }
314}
315
316impl Serialize for Message {
317 fn serialize<S>(&self, s: S) -> std::result::Result<S::Ok, S::Error>
318 where
319 S: Serializer,
320 {
321 (
322 &self.version,
323 &self.to,
324 &self.from,
325 &self.sequence,
326 &self.value,
327 &self.gas_limit,
328 &self.gas_fee_cap,
329 &self.gas_premium,
330 &self.method_num,
331 &self.params,
332 )
333 .serialize(s)
334 }
335}
336
337impl<'de> Deserialize<'de> for Message {
338 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
339 where
340 D: Deserializer<'de>,
341 {
342 let (
343 version,
344 to,
345 from,
346 sequence,
347 value,
348 gas_limit,
349 gas_fee_cap,
350 gas_premium,
351 method_num,
352 params,
353 ) = Deserialize::deserialize(deserializer)?;
354 Ok(Self {
355 encoded: Memo::default(),
356 version,
357 from,
358 to,
359 sequence,
360 value,
361 method_num,
362 params,
363 gas_limit,
364 gas_fee_cap,
365 gas_premium,
366 })
367 }
368}
369
370#[cfg(test)]
371mod tests {
372 use super::*;
373 use crate::utils::cid::CidCborExt as _;
374 use fvm_ipld_encoding::to_vec;
375 use quickcheck_macros::quickcheck;
376
377 fn hash_of<T: std::hash::Hash>(value: &T) -> u64 {
378 use std::hash::Hasher as _;
379 let mut hasher = std::collections::hash_map::DefaultHasher::new();
380 value.hash(&mut hasher);
381 hasher.finish()
382 }
383
384 #[quickcheck]
387 fn computing_the_memo_is_invisible(msg: Message) -> bool {
388 let warm = msg.clone();
389 let _ = warm.cid();
390 warm == msg && hash_of(&warm) == hash_of(&msg) && format!("{warm:?}") == format!("{msg:?}")
391 }
392
393 #[quickcheck]
394 fn cid_and_len_match_the_unmemoized_path(msg: Message) -> bool {
395 msg.cid() == cid::Cid::from_cbor_blake2b256(&msg).unwrap()
396 && msg.encoded_len() == to_vec(&msg).unwrap().len()
397 }
398
399 #[quickcheck]
400 fn message_v4_roundtrip(msg: Message) {
401 let round_tripped: Message = Message_v4::from(msg.clone()).into();
402 assert_eq!(round_tripped, msg);
403 }
404
405 #[quickcheck]
406 fn message_v3_roundtrip(msg: Message) {
407 let round_tripped: Message = Message_v3::from(msg.clone()).into();
408 assert_eq!(round_tripped, msg);
409 }
410
411 #[quickcheck]
412 fn message_v2_roundtrip(msg: Message) {
413 use crate::shim::address::Protocol;
414
415 let representable = msg.from().protocol() != Protocol::Delegated
416 && msg.to().protocol() != Protocol::Delegated;
417 match Message_v2::try_from(msg.clone()) {
418 Ok(v2) => {
419 assert!(representable);
420 let round_tripped: Message = v2.into();
421 assert_eq!(round_tripped, msg);
422 }
423 Err(_) => assert!(!representable),
424 }
425 }
426}