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
// Copyright 2019-2022 PureStake Inc.
// This file is part Utils package, originally developed by PureStake

// Utils is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Utils is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Utils.  If not, see <http://www.gnu.org/licenses/>.
use alloc::{format, string::String};

use core::assert_matches::assert_matches;
use pallet_3vm_evm_primitives::{
    Context, ExitError, ExitReason, ExitSucceed, Log, PrecompileFailure, PrecompileHandle,
    PrecompileOutput, PrecompileResult, PrecompileSet, Transfer,
};
use sp_core::{H160, H256, U256};
use sp_std::{boxed::Box, vec, vec::Vec};

pub struct Subcall {
    pub address: H160,
    pub transfer: Option<Transfer>,
    pub input: Vec<u8>,
    pub target_gas: Option<u64>,
    pub is_static: bool,
    pub context: Context,
}

pub struct SubcallOutput {
    pub reason: ExitReason,
    pub output: Vec<u8>,
    pub cost: u64,
    pub logs: Vec<Log>,
}

pub trait SubcallTrait: FnMut(Subcall) -> SubcallOutput + 'static {}

impl<T: FnMut(Subcall) -> SubcallOutput + 'static> SubcallTrait for T {}

pub type SubcallHandle = Box<dyn SubcallTrait>;

/// Mock handle to write tests for precompiles.
pub struct MockHandle {
    pub gas_limit: u64,
    pub gas_used: u64,
    pub logs: Vec<PrettyLog>,
    pub subcall_handle: Option<SubcallHandle>,
    pub code_address: H160,
    pub input: Vec<u8>,
    pub context: Context,
    pub is_static: bool,
}

impl MockHandle {
    pub fn new(code_address: H160, context: Context) -> Self {
        Self {
            gas_limit: u64::MAX,
            gas_used: 0,
            logs: vec![],
            subcall_handle: None,
            code_address,
            input: Vec::new(),
            context,
            is_static: false,
        }
    }
}

impl PrecompileHandle for MockHandle {
    /// Perform subcall in provided context.
    /// Precompile specifies in which context the subcall is executed.
    fn call(
        &mut self,
        address: H160,
        transfer: Option<Transfer>,
        input: Vec<u8>,
        target_gas: Option<u64>,
        is_static: bool,
        context: &Context,
    ) -> (ExitReason, Vec<u8>) {
        if self
            .record_cost(crate::costs::call_cost(
                context.apparent_value,
                &evm::Config::london(),
            ))
            .is_err()
        {
            return (ExitReason::Error(ExitError::OutOfGas), vec![])
        }

        match &mut self.subcall_handle {
            Some(handle) => {
                let SubcallOutput {
                    reason,
                    output,
                    cost,
                    logs,
                } = handle(Subcall {
                    address,
                    transfer,
                    input,
                    target_gas,
                    is_static,
                    context: context.clone(),
                });

                if self.record_cost(cost).is_err() {
                    return (ExitReason::Error(ExitError::OutOfGas), vec![])
                }

                for log in logs {
                    self.log(log.address, log.topics, log.data)
                        .expect("cannot fail");
                }

                (reason, output)
            },
            None => panic!("no subcall handle registered"),
        }
    }

    fn record_cost(&mut self, cost: u64) -> Result<(), ExitError> {
        self.gas_used += cost;

        if self.gas_used > self.gas_limit {
            Err(ExitError::OutOfGas)
        } else {
            Ok(())
        }
    }

    fn record_external_cost(
        &mut self,
        _ref_time: Option<u64>,
        _proof_size: Option<u64>,
    ) -> Result<(), ExitError> {
        Ok(())
    }

    fn refund_external_cost(&mut self, _ref_time: Option<u64>, _proof_size: Option<u64>) {}

    fn remaining_gas(&self) -> u64 {
        self.gas_limit - self.gas_used
    }

    fn log(&mut self, address: H160, topics: Vec<H256>, data: Vec<u8>) -> Result<(), ExitError> {
        self.logs.push(PrettyLog(Log {
            address,
            topics,
            data,
        }));
        Ok(())
    }

    /// Retreive the code address (what is the address of the precompile being called).
    fn code_address(&self) -> H160 {
        self.code_address
    }

    /// Retreive the input data the precompile is called with.
    fn input(&self) -> &[u8] {
        &self.input
    }

    /// Retreive the context in which the precompile is executed.
    fn context(&self) -> &Context {
        &self.context
    }

    /// Is the precompile call is done statically.
    fn is_static(&self) -> bool {
        self.is_static
    }

    /// Retreive the gas limit of this call.
    fn gas_limit(&self) -> Option<u64> {
        Some(self.gas_limit)
    }
}

pub struct PrecompilesTester<'p, P> {
    precompiles: &'p P,
    handle: MockHandle,

    target_gas: Option<u64>,
    subcall_handle: Option<SubcallHandle>,

    expected_cost: Option<u64>,
    expected_logs: Option<Vec<PrettyLog>>,
}

impl<'p, P: PrecompileSet> PrecompilesTester<'p, P> {
    pub fn new(
        precompiles: &'p P,
        from: impl Into<H160>,
        to: impl Into<H160>,
        data: Vec<u8>,
    ) -> Self {
        let to = to.into();
        let mut handle = MockHandle::new(
            to.clone(),
            Context {
                address: to,
                caller: from.into(),
                apparent_value: U256::zero(),
            },
        );

        handle.input = data;

        Self {
            precompiles,
            handle,

            target_gas: None,
            subcall_handle: None,

            expected_cost: None,
            expected_logs: None,
        }
    }

    pub fn with_value(mut self, value: impl Into<U256>) -> Self {
        self.handle.context.apparent_value = value.into();
        self
    }

    pub fn with_subcall_handle(mut self, subcall_handle: impl SubcallTrait) -> Self {
        self.subcall_handle = Some(Box::new(subcall_handle));
        self
    }

    pub fn with_target_gas(mut self, target_gas: Option<u64>) -> Self {
        self.target_gas = target_gas;
        self
    }

    pub fn expect_cost(mut self, cost: u64) -> Self {
        self.expected_cost = Some(cost);
        self
    }

    pub fn expect_no_logs(mut self) -> Self {
        self.expected_logs = Some(vec![]);
        self
    }

    pub fn expect_log(mut self, log: Log) -> Self {
        self.expected_logs = Some({
            let mut logs = self.expected_logs.unwrap_or_else(Vec::new);
            logs.push(PrettyLog(log));
            logs
        });
        self
    }

    fn assert_optionals(&self) {
        if let Some(cost) = &self.expected_cost {
            assert_eq!(&self.handle.gas_used, cost);
        }

        if let Some(logs) = &self.expected_logs {
            assert_eq!(&self.handle.logs, logs);
        }
    }

    fn execute(&mut self) -> Option<PrecompileResult> {
        let handle = &mut self.handle;
        handle.subcall_handle = self.subcall_handle.take();

        if let Some(gas_limit) = self.target_gas {
            handle.gas_limit = gas_limit;
        }

        let res = self.precompiles.execute(
            handle,
            // self.to,
            // &self.data,
            // self.target_gas,
            // &self.context,
            // self.is_static,
        );

        self.subcall_handle = handle.subcall_handle.take();

        res
    }

    /// Execute the precompile set and expect some precompile to have been executed, regardless of
    /// the result.
    pub fn execute_some(mut self) {
        let res = self.execute();
        assert!(res.is_some());
        self.assert_optionals();
    }

    /// Execute the precompile set and expect no precompile to have been executed.
    pub fn execute_none(mut self) {
        let res = self.execute();
        assert!(res.is_some());
        self.assert_optionals();
    }

    /// Execute the precompile set and check it returns provided output.
    pub fn execute_returns(mut self, output: Vec<u8>) {
        let res = self.execute();
        assert_eq!(
            res,
            Some(Ok(PrecompileOutput {
                exit_status: ExitSucceed::Returned,
                output
            }))
        );
        self.assert_optionals();
    }

    /// Execute the precompile set and check if it reverts.
    /// Take a closure allowing to perform custom matching on the output.
    pub fn execute_reverts(mut self, check: impl Fn(&[u8]) -> bool) {
        let res = self.execute();
        assert_matches!(
            res,
            Some(Err(PrecompileFailure::Revert { output, ..}))
                if check(&output)
        );
        self.assert_optionals();
    }

    /// Execute the precompile set and check it returns provided output.
    pub fn execute_error(mut self, error: ExitError) {
        let res = self.execute();
        assert_eq!(
            res,
            Some(Err(PrecompileFailure::Error { exit_status: error }))
        );
        self.assert_optionals();
    }
}

pub trait PrecompileTesterExt: PrecompileSet + Sized {
    fn prepare_test(
        &self,
        from: impl Into<H160>,
        to: impl Into<H160>,
        data: Vec<u8>,
    ) -> PrecompilesTester<Self>;
}

impl<T: PrecompileSet> PrecompileTesterExt for T {
    fn prepare_test(
        &self,
        from: impl Into<H160>,
        to: impl Into<H160>,
        data: Vec<u8>,
    ) -> PrecompilesTester<Self> {
        PrecompilesTester::new(self, from, to, data)
    }
}

#[derive(Clone, PartialEq, Eq)]
pub struct PrettyLog(Log);

impl core::fmt::Debug for PrettyLog {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
        let bytes = self
            .0
            .data
            .iter()
            .map(|b| format!("{:02X}", b))
            .collect::<Vec<String>>()
            .join("");

        let message = String::from_utf8(self.0.data.clone()).ok();

        f.debug_struct("Log")
            .field("address", &self.0.address)
            .field("topics", &self.0.topics)
            .field("data", &bytes)
            .field("data_utf8", &message)
            .finish()
    }
}