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
use crate::trace::{
    Action as RpcCfxAction, LocalizedTrace as RpcCfxLocalizedTrace,
};
use cfx_parity_trace_types::Outcome;
use cfx_rpc_primitives::Bytes;
use cfx_types::{H160, H256, U256};
use cfx_util_macros::bail;
use cfx_vm_types::{CallType as CfxCallType, CreateType as CfxCreateType};
use jsonrpc_core::Error as JsonRpcError;
use serde::{ser::SerializeStruct, Serialize, Serializer};
use std::{
    convert::{TryFrom, TryInto},
    fmt,
};

/// Create response
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Create {
    /// Sender
    from: H160,
    /// Value
    value: U256,
    /// Gas
    gas: U256,
    /// Initialization code
    init: Bytes,
    /// The create type `CREATE` or `CREATE2`
    create_type: CreateType,
}

/// The type of the create-like instruction.
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum CreateType {
    /// Not a create
    None,
    /// CREATE
    CREATE,
    /// CREATE2
    CREATE2,
}

impl From<CfxCreateType> for CreateType {
    fn from(cfx_create_type: CfxCreateType) -> Self {
        match cfx_create_type {
            CfxCreateType::None => CreateType::None,
            CfxCreateType::CREATE => CreateType::CREATE,
            CfxCreateType::CREATE2 => CreateType::CREATE2,
        }
    }
}

/// Call type.
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "lowercase")]
pub enum CallType {
    /// None
    None,
    /// Call
    Call,
    /// Call code
    CallCode,
    /// Delegate call
    DelegateCall,
    /// Static call
    StaticCall,
}

impl From<CfxCallType> for CallType {
    fn from(cfx_call_type: CfxCallType) -> Self {
        match cfx_call_type {
            CfxCallType::None => CallType::None,
            CfxCallType::Call => CallType::Call,
            CfxCallType::CallCode => CallType::CallCode,
            CfxCallType::DelegateCall => CallType::DelegateCall,
            CfxCallType::StaticCall => CallType::StaticCall,
        }
    }
}

/// Call response
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct Call {
    /// Sender
    from: H160,
    /// Recipient
    to: H160,
    /// Transfered Value
    value: U256,
    /// Gas
    gas: U256,
    /// Input data
    input: Bytes,
    /// The type of the call.
    call_type: CallType,
}

/// Action
#[derive(Debug, Clone)]
pub enum Action {
    /// Call
    Call(Call),
    /// Create
    Create(Create),
    /* TODO: Support Suicide
     * TODO: Support Reward */
}

impl TryFrom<RpcCfxAction> for Action {
    type Error = String;

    fn try_from(cfx_action: RpcCfxAction) -> Result<Self, String> {
        match cfx_action {
            RpcCfxAction::Call(call) => Ok(Action::Call(Call {
                from: call.from.hex_address,
                to: call.to.hex_address,
                value: call.value,
                gas: call.gas,
                input: call.input,
                call_type: call.call_type.into(),
            })),
            RpcCfxAction::Create(create) => Ok(Action::Create(Create {
                from: create.from.hex_address,
                value: create.value,
                gas: create.gas,
                init: create.init,
                create_type: create.create_type.into(),
            })),
            action => {
                bail!("unsupported action in eth space: {:?}", action);
            }
        }
    }
}

/// Call Result
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CallResult {
    /// Gas used
    gas_used: U256,
    /// Output bytes
    output: Bytes,
}

/// Craete Result
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct CreateResult {
    /// Gas used
    gas_used: U256,
    /// Code
    code: Bytes,
    /// Assigned address
    address: H160,
}

/// Response
#[derive(Debug, Clone)]
pub enum Res {
    /// Call
    Call(CallResult),
    /// Create
    Create(CreateResult),
    /// Call failure
    FailedCall(TraceError),
    /// Creation failure
    FailedCreate(TraceError),
    /// None
    None,
}

/// Trace
#[derive(Debug, Clone)]
pub struct LocalizedTrace {
    /// Action
    pub action: Action,
    /// Result
    pub result: Res,
    /// Trace address
    pub trace_address: Vec<usize>,
    /// Subtraces
    pub subtraces: usize,
    /// Transaction position
    pub transaction_position: Option<usize>,
    /// Transaction hash
    pub transaction_hash: Option<H256>,
    /// Block Number
    pub block_number: u64,
    /// Block Hash
    pub block_hash: H256,
    /// Valid
    pub valid: bool,
}

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", 9)?;
        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)?;
            }
        }

        match self.result {
            Res::Call(ref call) => struc.serialize_field("result", call)?,
            Res::Create(ref create) => {
                struc.serialize_field("result", create)?
            }
            Res::FailedCall(ref error) => {
                struc.serialize_field("error", &error.to_string())?
            }
            Res::FailedCreate(ref error) => {
                struc.serialize_field("error", &error.to_string())?
            }
            Res::None => {
                struc.serialize_field("result", &None as &Option<u8>)?
            }
        }

        struc.serialize_field("traceAddress", &self.trace_address)?;
        struc.serialize_field("subtraces", &self.subtraces)?;
        struc.serialize_field(
            "transactionPosition",
            &self.transaction_position,
        )?;
        struc.serialize_field("transactionHash", &self.transaction_hash)?;
        struc.serialize_field("blockNumber", &self.block_number)?;
        struc.serialize_field("blockHash", &self.block_hash)?;
        struc.serialize_field("valid", &self.valid)?;

        struc.end()
    }
}

impl TryFrom<RpcCfxLocalizedTrace> for LocalizedTrace {
    type Error = String;

    fn try_from(cfx_trace: RpcCfxLocalizedTrace) -> Result<Self, String> {
        Ok(Self {
            action: cfx_trace.action.try_into()?,
            result: Res::None,
            trace_address: vec![],
            subtraces: 0,
            // note: `as_usize` will panic on overflow,
            // however, this should not happen for tx position
            transaction_position: cfx_trace
                .transaction_position
                .map(|x| x.as_usize()),
            transaction_hash: cfx_trace.transaction_hash,
            block_number: cfx_trace
                .epoch_number
                .map(|en| en.as_u64())
                .unwrap_or(0),
            block_hash: cfx_trace.epoch_hash.unwrap_or_default(),
            valid: cfx_trace.valid,
        })
    }
}

impl LocalizedTrace {
    pub fn set_result(
        &mut self, result: RpcCfxAction,
    ) -> Result<(), JsonRpcError> {
        if !matches!(self.result, Res::None) {
            // One action matches exactly one result.
            bail!(JsonRpcError::internal_error());
        }
        match result {
            RpcCfxAction::CallResult(call_result) => {
                if !matches!(self.action, Action::Call(_)) {
                    bail!(JsonRpcError::internal_error());
                }
                match call_result.outcome {
                    Outcome::Success => {
                        // FIXME(lpl): Convert gas_left to gas_used.
                        self.result = Res::Call(CallResult {
                            gas_used: call_result.gas_left,
                            output: call_result.return_data,
                        })
                    }
                    Outcome::Reverted => {
                        self.result = Res::FailedCall(TraceError::Reverted);
                    }
                    Outcome::Fail => {
                        self.result = Res::FailedCall(TraceError::Error(
                            call_result.return_data,
                        ));
                    }
                }
            }
            RpcCfxAction::CreateResult(create_result) => {
                if !matches!(self.action, Action::Create(_)) {
                    bail!(JsonRpcError::internal_error());
                }
                match create_result.outcome {
                    Outcome::Success => {
                        // FIXME(lpl): Convert gas_left to gas_used.
                        // FIXME(lpl): Check if `return_data` is `code`.
                        self.result = Res::Create(CreateResult {
                            gas_used: create_result.gas_left,
                            code: create_result.return_data,
                            address: create_result.addr.hex_address,
                        })
                    }
                    Outcome::Reverted => {
                        self.result = Res::FailedCreate(TraceError::Reverted);
                    }
                    Outcome::Fail => {
                        self.result = Res::FailedCreate(TraceError::Error(
                            create_result.return_data,
                        ));
                    }
                }
            }
            _ => bail!(JsonRpcError::internal_error()),
        }
        Ok(())
    }
}

/// Trace
#[derive(Debug)]
pub struct Trace {
    /// Trace address
    trace_address: Vec<usize>,
    /// Subtraces
    subtraces: usize,
    /// Action
    action: Action,
    /// Result
    result: Res,
}

impl Serialize for Trace {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where S: Serializer {
        let mut struc = serializer.serialize_struct("Trace", 4)?;
        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)?;
            }
        }

        match self.result {
            Res::Call(ref call) => struc.serialize_field("result", call)?,
            Res::Create(ref create) => {
                struc.serialize_field("result", create)?
            }
            Res::FailedCall(ref error) => {
                struc.serialize_field("error", &error.to_string())?
            }
            Res::FailedCreate(ref error) => {
                struc.serialize_field("error", &error.to_string())?
            }
            Res::None => {
                struc.serialize_field("result", &None as &Option<u8>)?
            }
        }

        struc.serialize_field("traceAddress", &self.trace_address)?;
        struc.serialize_field("subtraces", &self.subtraces)?;

        struc.end()
    }
}

#[derive(Debug, Clone)]
pub enum TraceError {
    /// Execution has been reverted with REVERT instruction.
    Reverted,
    /// Other errors with error message encoded.
    Error(Bytes),
}

impl fmt::Display for TraceError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let message = match &self {
            TraceError::Reverted => "Reverted",
            // error bytes are constructed from `format`, so this should
            // succeed.
            TraceError::Error(b) => {
                std::str::from_utf8(&b.0).map_err(|_| fmt::Error)?
            }
        };
        message.fmt(f)
    }
}