1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright 2019-2024 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT

use super::trace::ExecutionEvent;
use crate::shim::{econ::TokenAmount, fvm_shared_latest::error::ExitCode};
use cid::Cid;
use fil_actors_shared::fvm_ipld_amt::Amtv0;
use fvm2::executor::ApplyRet as ApplyRet_v2;
use fvm3::executor::ApplyRet as ApplyRet_v3;
use fvm4::executor::ApplyRet as ApplyRet_v4;
use fvm_ipld_blockstore::Blockstore;
use fvm_ipld_encoding::RawBytes;
use fvm_shared2::receipt::Receipt as Receipt_v2;
pub use fvm_shared3::receipt::Receipt as Receipt_v3;
use fvm_shared4::receipt::Receipt as Receipt_v4;
use serde::Serialize;

#[derive(Clone, Debug)]
pub enum ApplyRet {
    V2(Box<ApplyRet_v2>),
    V3(Box<ApplyRet_v3>),
    V4(Box<ApplyRet_v4>),
}

impl From<ApplyRet_v2> for ApplyRet {
    fn from(other: ApplyRet_v2) -> Self {
        ApplyRet::V2(Box::new(other))
    }
}

impl From<ApplyRet_v3> for ApplyRet {
    fn from(other: ApplyRet_v3) -> Self {
        ApplyRet::V3(Box::new(other))
    }
}

impl From<ApplyRet_v4> for ApplyRet {
    fn from(other: ApplyRet_v4) -> Self {
        ApplyRet::V4(Box::new(other))
    }
}

impl ApplyRet {
    pub fn failure_info(&self) -> Option<String> {
        match self {
            ApplyRet::V2(v2) => v2.failure_info.as_ref().map(|failure| failure.to_string()),
            ApplyRet::V3(v3) => v3.failure_info.as_ref().map(|failure| failure.to_string()),
            ApplyRet::V4(v4) => v4.failure_info.as_ref().map(|failure| failure.to_string()),
        }
        .map(|e| format!("{} (RetCode={})", e, self.msg_receipt().exit_code()))
    }

    pub fn miner_tip(&self) -> TokenAmount {
        match self {
            ApplyRet::V2(v2) => (&v2.miner_tip).into(),
            ApplyRet::V3(v3) => (&v3.miner_tip).into(),
            ApplyRet::V4(v4) => (&v4.miner_tip).into(),
        }
    }

    pub fn penalty(&self) -> TokenAmount {
        match self {
            ApplyRet::V2(v2) => (&v2.penalty).into(),
            ApplyRet::V3(v3) => (&v3.penalty).into(),
            ApplyRet::V4(v4) => (&v4.penalty).into(),
        }
    }

    pub fn msg_receipt(&self) -> Receipt {
        match self {
            ApplyRet::V2(v2) => Receipt::V2(v2.msg_receipt.clone()),
            ApplyRet::V3(v3) => Receipt::V3(v3.msg_receipt.clone()),
            ApplyRet::V4(v4) => Receipt::V4(v4.msg_receipt.clone()),
        }
    }

    pub fn refund(&self) -> TokenAmount {
        match self {
            ApplyRet::V2(v2) => (&v2.refund).into(),
            ApplyRet::V3(v3) => (&v3.refund).into(),
            ApplyRet::V4(v4) => (&v4.refund).into(),
        }
    }

    pub fn base_fee_burn(&self) -> TokenAmount {
        match self {
            ApplyRet::V2(v2) => (&v2.base_fee_burn).into(),
            ApplyRet::V3(v3) => (&v3.base_fee_burn).into(),
            ApplyRet::V4(v4) => (&v4.base_fee_burn).into(),
        }
    }

    pub fn over_estimation_burn(&self) -> TokenAmount {
        match self {
            ApplyRet::V2(v2) => (&v2.over_estimation_burn).into(),
            ApplyRet::V3(v3) => (&v3.over_estimation_burn).into(),
            ApplyRet::V4(v4) => (&v4.over_estimation_burn).into(),
        }
    }

    pub fn exec_trace(&self) -> Vec<ExecutionEvent> {
        match self {
            ApplyRet::V2(v2) => v2.exec_trace.iter().cloned().map(Into::into).collect(),
            ApplyRet::V3(v3) => v3.exec_trace.iter().cloned().map(Into::into).collect(),
            ApplyRet::V4(v4) => v4.exec_trace.iter().cloned().map(Into::into).collect(),
        }
    }
}

// Note: it's impossible to properly derive Deserialize.
// To deserialize into `Receipt`, refer to `fn get_parent_receipt`
#[derive(PartialEq, Clone, Debug, Serialize)]
#[serde(untagged)]
pub enum Receipt {
    V2(Receipt_v2),
    V3(Receipt_v3),
    V4(Receipt_v4),
}

impl Receipt {
    pub fn exit_code(&self) -> ExitCode {
        match self {
            Receipt::V2(v2) => ExitCode::new(v2.exit_code.value()),
            Receipt::V3(v3) => ExitCode::new(v3.exit_code.value()),
            Receipt::V4(v4) => v4.exit_code,
        }
    }

    pub fn return_data(&self) -> RawBytes {
        match self {
            Receipt::V2(v2) => v2.return_data.clone(),
            Receipt::V3(v3) => v3.return_data.clone(),
            Receipt::V4(v4) => v4.return_data.clone(),
        }
    }

    pub fn gas_used(&self) -> u64 {
        match self {
            Receipt::V2(v2) => v2.gas_used as u64,
            Receipt::V3(v3) => v3.gas_used,
            Receipt::V4(v4) => v4.gas_used,
        }
    }
    pub fn events_root(&self) -> Option<Cid> {
        match self {
            Receipt::V2(_) => None,
            Receipt::V3(v3) => v3.events_root,
            Receipt::V4(v4) => v4.events_root,
        }
    }

    pub fn get_receipt(
        db: &impl Blockstore,
        receipts: &Cid,
        i: u64,
    ) -> anyhow::Result<Option<Self>> {
        // Try Receipt_v4 first. (Receipt_v4 and Receipt_v3 are identical, use v4 here)
        if let Ok(amt) = Amtv0::load(receipts, db) {
            if let Ok(receipts) = amt.get(i) {
                return Ok(receipts.cloned().map(Receipt::V4));
            }
        }

        // Fallback to Receipt_v2.
        let amt = Amtv0::load(receipts, db)?;
        let receipts = amt.get(i)?;
        Ok(receipts.cloned().map(Receipt::V2))
    }

    pub fn get_receipts(db: &impl Blockstore, receipts_cid: Cid) -> anyhow::Result<Vec<Receipt>> {
        let mut receipts = Vec::new();

        // Try Receipt_v4 first. (Receipt_v4 and Receipt_v3 are identical, use v4 here)
        if let Ok(amt) = Amtv0::<fvm_shared4::receipt::Receipt, _>::load(&receipts_cid, db) {
            amt.for_each(|_, receipt| {
                receipts.push(Receipt::V4(receipt.clone()));
                Ok(())
            })?;
        } else {
            // Fallback to Receipt_v2.
            let amt = Amtv0::<fvm_shared2::receipt::Receipt, _>::load(&receipts_cid, db)?;
            amt.for_each(|_, receipt| {
                receipts.push(Receipt::V2(receipt.clone()));
                Ok(())
            })?;
        }

        Ok(receipts)
    }
}

impl From<Receipt_v3> for Receipt {
    fn from(other: Receipt_v3) -> Self {
        Receipt::V3(other)
    }
}

#[cfg(test)]
impl quickcheck::Arbitrary for Receipt {
    fn arbitrary(g: &mut quickcheck::Gen) -> Self {
        #[derive(derive_quickcheck_arbitrary::Arbitrary, Clone)]
        enum Helper {
            V2 {
                exit_code: u32,
                return_data: Vec<u8>,
                gas_used: i64,
            },
            V3 {
                exit_code: u32,
                return_data: Vec<u8>,
                gas_used: u64,
                events_root: Option<::cid::Cid>,
            },
            V4 {
                exit_code: u32,
                return_data: Vec<u8>,
                gas_used: u64,
                events_root: Option<::cid::Cid>,
            },
        }
        match Helper::arbitrary(g) {
            Helper::V2 {
                exit_code,
                return_data,
                gas_used,
            } => Self::V2(Receipt_v2 {
                exit_code: exit_code.into(),
                return_data: return_data.into(),
                gas_used,
            }),
            Helper::V3 {
                exit_code,
                return_data,
                gas_used,
                events_root,
            } => Self::V3(Receipt_v3 {
                exit_code: exit_code.into(),
                return_data: return_data.into(),
                gas_used,
                events_root,
            }),
            Helper::V4 {
                exit_code,
                return_data,
                gas_used,
                events_root,
            } => Self::V4(Receipt_v4 {
                exit_code: exit_code.into(),
                return_data: return_data.into(),
                gas_used,
                events_root,
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use quickcheck_macros::quickcheck;

    #[quickcheck]
    fn receipt_cbor_serde_serialize(receipt: Receipt) {
        let encoded = fvm_ipld_encoding::to_vec(&receipt).unwrap();
        let encoded2 = match &receipt {
            Receipt::V2(v) => fvm_ipld_encoding::to_vec(v),
            Receipt::V3(v) => fvm_ipld_encoding::to_vec(v),
            Receipt::V4(v) => fvm_ipld_encoding::to_vec(v),
        }
        .unwrap();
        assert_eq!(encoded, encoded2);
    }
}