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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
// Copyright 2020 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

use crate::{trace_eth::LocalizedTrace as EthLocalizedTrace, RpcAddress};
use cfx_addr::Network;
use cfx_parameters::internal_contract_addresses::CROSS_SPACE_CONTRACT_ADDRESS;
use cfx_parity_trace_types::{
    Action as VmAction, ActionType as VmActionType, BlockExecTraces,
    Call as VmCall, CallResult as VmCallResult, Create as VmCreate,
    CreateResult as VmCreateResult, ExecTrace,
    InternalTransferAction as VmInternalTransferAction,
    LocalizedTrace as PrimitiveLocalizedTrace, Outcome, TransactionExecTraces,
};
use cfx_rpc_primitives::Bytes;
use cfx_types::{address_util::AddressUtil, Space, H160, H256, U256, U64};
use cfx_vm_types::{CallType, CreateType};
use primitives::SignedTransaction;
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};
use std::{collections::HashMap, sync::Arc};
use strum_macros::EnumDiscriminants;

#[derive(Debug, Clone, PartialEq, EnumDiscriminants)]
#[strum_discriminants(name(ActionType))]
#[strum_discriminants(derive(Hash, Serialize, Deserialize))]
#[strum_discriminants(serde(rename_all = "snake_case", deny_unknown_fields))]
pub enum Action {
    Call(Call),
    Create(Create),
    CallResult(CallResult),
    CreateResult(CreateResult),
    InternalTransferAction(InternalTransferAction),
}

impl Action {
    pub fn try_from(
        action: VmAction, network: Network,
    ) -> Result<Self, String> {
        Ok(match action {
            VmAction::Call(x) => Action::Call(Call::try_from(x, network)?),
            VmAction::Create(x) => {
                Action::Create(Create::try_from(x, network)?)
            }
            VmAction::CallResult(x) => Action::CallResult(x.into()),
            VmAction::CreateResult(x) => {
                Action::CreateResult(CreateResult::try_from(x, network)?)
            }
            VmAction::InternalTransferAction(x) => {
                Action::InternalTransferAction(
                    InternalTransferAction::try_from(x, network)?,
                )
            }
        })
    }
}

impl Into<VmActionType> for ActionType {
    fn into(self) -> VmActionType {
        match self {
            Self::Call => VmActionType::Call,
            Self::Create => VmActionType::Create,
            Self::CallResult => VmActionType::CallResult,
            Self::CreateResult => VmActionType::CreateResult,
            Self::InternalTransferAction => {
                VmActionType::InternalTransferAction
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Call {
    pub space: Space,
    pub from: RpcAddress,
    pub to: RpcAddress,
    pub value: U256,
    pub gas: U256,
    pub input: Bytes,
    pub call_type: CallType,
}

impl Call {
    fn try_from(call: VmCall, network: Network) -> Result<Self, String> {
        Ok(Self {
            space: call.space,
            from: RpcAddress::try_from_h160(call.from, network)?,
            to: RpcAddress::try_from_h160(call.to, network)?,
            value: call.value,
            gas: call.gas,
            input: call.input.into(),
            call_type: call.call_type,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallResult {
    pub outcome: Outcome,
    pub gas_left: U256,
    pub return_data: Bytes,
}

impl From<VmCallResult> for CallResult {
    fn from(result: VmCallResult) -> Self {
        Self {
            outcome: result.outcome,
            gas_left: result.gas_left,
            return_data: result.return_data.into(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Create {
    pub space: Space,
    pub from: RpcAddress,
    pub value: U256,
    pub gas: U256,
    pub init: Bytes,
    pub create_type: CreateType,
}

impl Create {
    fn try_from(create: VmCreate, network: Network) -> Result<Self, String> {
        Ok(Self {
            space: create.space,
            from: RpcAddress::try_from_h160(create.from, network)?,
            value: create.value,
            gas: create.gas,
            init: create.init.into(),
            create_type: create.create_type,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateResult {
    pub outcome: Outcome,
    pub addr: RpcAddress,
    pub gas_left: U256,
    pub return_data: Bytes,
}

impl CreateResult {
    fn try_from(
        result: VmCreateResult, network: Network,
    ) -> Result<Self, String> {
        Ok(Self {
            outcome: result.outcome,
            addr: RpcAddress::try_from_h160(result.addr, network)?,
            gas_left: result.gas_left,
            return_data: result.return_data.into(),
        })
    }
}

#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InternalTransferAction {
    pub from: RpcAddress,
    pub from_pocket: String,
    pub from_space: String,
    pub to: RpcAddress,
    pub to_pocket: String,
    pub to_space: String,
    pub value: U256,
}

impl InternalTransferAction {
    fn try_from(
        action: VmInternalTransferAction, network: Network,
    ) -> Result<Self, String> {
        Ok(Self {
            from: RpcAddress::try_from_h160(
                action.from.inner_address_or_default(),
                network,
            )?,
            from_pocket: action.from.pocket().into(),
            from_space: action.from.space().into(),
            to: RpcAddress::try_from_h160(
                action.to.inner_address_or_default(),
                network,
            )?,
            to_pocket: action.to.pocket().into(),
            to_space: action.to.space().into(),
            value: action.value,
        })
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LocalizedBlockTrace {
    pub transaction_traces: Vec<LocalizedTransactionTrace>,
    /// Epoch hash.
    pub epoch_hash: H256,
    /// Epoch number.
    pub epoch_number: U256,
    /// Block hash.
    pub block_hash: H256,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LocalizedTransactionTrace {
    pub traces: Vec<LocalizedTrace>,
    /// Transaction position.
    pub transaction_position: U64,
    /// Signed transaction hash.
    pub transaction_hash: H256,
}

#[derive(Debug)]
pub struct LocalizedTrace {
    pub action: Action,
    pub valid: bool,
    /// Epoch hash.
    pub epoch_hash: Option<H256>,
    /// Epoch number.
    pub epoch_number: Option<U256>,
    /// Block hash.
    pub block_hash: Option<H256>,
    /// Transaction position.
    pub transaction_position: Option<U64>,
    /// Signed transaction hash.
    pub transaction_hash: Option<H256>,
}

impl Serialize for LocalizedTrace {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where S: Serializer {
        let mut struc = serializer.serialize_struct("LocalizedTrace", 8)?;

        match self.action {
            Action::Call(ref call) => {
                struc.serialize_field("type", "call")?;
                struc.serialize_field("action", call)?;
            }
            Action::Create(ref create) => {
                struc.serialize_field("type", "create")?;
                struc.serialize_field("action", create)?;
            }
            Action::CallResult(ref call_result) => {
                struc.serialize_field("type", "call_result")?;
                struc.serialize_field("action", call_result)?;
            }
            Action::CreateResult(ref create_result) => {
                struc.serialize_field("type", "create_result")?;
                struc.serialize_field("action", create_result)?;
            }
            Action::InternalTransferAction(ref internal_action) => {
                struc.serialize_field("type", "internal_transfer_action")?;
                struc.serialize_field("action", internal_action)?;
            }
        }

        struc.serialize_field("valid", &self.valid)?;

        if self.epoch_hash.is_some() {
            struc.serialize_field("epochHash", &self.epoch_hash.unwrap())?;
        }
        if self.epoch_number.is_some() {
            struc
                .serialize_field("epochNumber", &self.epoch_number.unwrap())?;
        }
        if self.block_hash.is_some() {
            struc.serialize_field("blockHash", &self.block_hash.unwrap())?;
        }
        if self.transaction_position.is_some() {
            struc.serialize_field(
                "transactionPosition",
                &self.transaction_position.unwrap(),
            )?;
        }
        if self.transaction_hash.is_some() {
            struc.serialize_field(
                "transactionHash",
                &self.transaction_hash.unwrap(),
            )?;
        }

        struc.end()
    }
}

impl LocalizedTrace {
    pub fn from(
        trace: PrimitiveLocalizedTrace, network: Network,
    ) -> Result<Self, String> {
        Ok(LocalizedTrace {
            action: Action::try_from(trace.action, network)?,
            epoch_number: Some(trace.epoch_number),
            epoch_hash: Some(trace.epoch_hash),
            block_hash: Some(trace.block_hash),
            transaction_position: Some(trace.transaction_position),
            transaction_hash: Some(trace.transaction_hash),
            valid: trace.valid,
        })
    }
}

impl LocalizedTransactionTrace {
    pub fn from(
        traces: TransactionExecTraces, transaction_hash: H256,
        transaction_position: usize, network: Network,
    ) -> Result<Self, String> {
        let traces: Vec<ExecTrace> = traces.into();

        Ok(LocalizedTransactionTrace {
            traces: traces
                .into_iter()
                .map(|t| {
                    let valid = t.valid;
                    Action::try_from(t.action, network).map(|action| {
                        LocalizedTrace {
                            action,
                            valid,
                            // Set to None because the information has been
                            // included in the outer
                            // structs
                            epoch_hash: None,
                            epoch_number: None,
                            block_hash: None,
                            transaction_position: None,
                            transaction_hash: None,
                        }
                    })
                })
                .collect::<Result<_, _>>()?,
            transaction_position: transaction_position.into(),
            transaction_hash,
        })
    }
}

impl LocalizedBlockTrace {
    pub fn from(
        traces: BlockExecTraces, block_hash: H256, epoch_hash: H256,
        epoch_number: u64, transactions: &Vec<Arc<SignedTransaction>>,
        network: Network,
    ) -> Result<Self, String> {
        let traces: Vec<TransactionExecTraces> = traces.into();
        if traces.len() != transactions.len() {
            cfx_util_macros::bail!("trace and tx hash list length unmatch!");
        }
        let transaction_traces = traces
            .into_iter()
            .enumerate()
            .filter_map(|(tx_pos, t)| match transactions[tx_pos].space() {
                Space::Native => Some((transactions[tx_pos].hash(), t)),
                Space::Ethereum => None,
            })
            .enumerate()
            .map(|(rpc_index, (tx_hash, t))| {
                LocalizedTransactionTrace::from(t, tx_hash, rpc_index, network)
            })
            .collect::<Result<_, _>>()?;

        Ok(LocalizedBlockTrace {
            transaction_traces,
            epoch_hash,
            epoch_number: epoch_number.into(),
            block_hash,
        })
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EpochTrace {
    cfx_traces: Vec<LocalizedTrace>,
    eth_traces: Vec<EthLocalizedTrace>,
    mirror_address_map: HashMap<H160, RpcAddress>,
}

impl EpochTrace {
    pub fn new(
        cfx_traces: Vec<LocalizedTrace>, eth_traces: Vec<EthLocalizedTrace>,
    ) -> Self {
        let mut mirror_address_map = HashMap::new();
        for t in &cfx_traces {
            if let Action::Call(action) = &t.action {
                if action.to.hex_address == CROSS_SPACE_CONTRACT_ADDRESS {
                    mirror_address_map.insert(
                        action.from.hex_address.evm_map().address,
                        action.from.clone(),
                    );
                }
            }
        }
        Self {
            cfx_traces,
            eth_traces,
            mirror_address_map,
        }
    }
}