revm_inspector/
handler_register.rs

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
402
403
404
405
406
407
408
use crate::Inspector;
use core::cell::RefCell;
use revm::{
    bytecode::opcode,
    handler::register::EvmHandler,
    interpreter::{table::DynInstruction, InstructionResult, Interpreter},
    wiring::result::EVMResultGeneric,
    Context, EvmWiring, FrameOrResult, FrameResult, JournalEntry,
};
use std::{rc::Rc, sync::Arc, vec::Vec};

/// Provides access to an `Inspector` instance.
pub trait GetInspector<EvmWiringT: EvmWiring> {
    /// Returns the associated `Inspector`.
    fn get_inspector(&mut self) -> &mut impl Inspector<EvmWiringT>;
}

impl<EvmWiringT: EvmWiring, INSP: Inspector<EvmWiringT>> GetInspector<EvmWiringT> for INSP {
    #[inline]
    fn get_inspector(&mut self) -> &mut impl Inspector<EvmWiringT> {
        self
    }
}

/// Register Inspector handles that interact with Inspector instance.
///
///
/// # Note
///
/// Inspector handle register does not override any existing handlers, and it
/// calls them before (or after) calling Inspector. This means that it is safe
/// to use this register with any other register.
///
/// A few instructions handlers are wrapped twice once for `step` and `step_end`
/// and in case of Logs and Selfdestruct wrapper is wrapped again for the
/// `log` and `selfdestruct` calls.
pub fn inspector_handle_register<
    EvmWiringT: EvmWiring<ExternalContext: GetInspector<EvmWiringT>>,
>(
    handler: &mut EvmHandler<'_, EvmWiringT>,
) {
    let table = &mut handler.instruction_table;

    // Update all instructions to call inspector step and step_end.
    table.update_all(inspector_instruction);

    // Register inspector LOG* instructions.
    for opcode in opcode::LOG0..=opcode::LOG4 {
        table.update_boxed(opcode, move |prev, interpreter, host| {
            let prev_log_len = host.evm.journaled_state.logs.len();
            prev(interpreter, host);
            // check if log was added. It is possible that revert happened
            // cause of gas or stack underflow.
            if host.evm.journaled_state.logs.len() == prev_log_len + 1 {
                // clone log.
                // TODO decide if we should remove this and leave the comment
                // that log can be found as journaled_state.
                let last_log = host.evm.journaled_state.logs.last().unwrap().clone();
                // call Inspector
                host.external
                    .get_inspector()
                    .log(interpreter, &mut host.evm, &last_log);
            }
        });
    }

    // Register selfdestruct function.
    table.update_boxed(opcode::SELFDESTRUCT, |prev, interpreter, host| {
        // execute selfdestruct
        prev(interpreter, host);
        // check if selfdestruct was successful and if journal entry is made.
        match host.evm.journaled_state.journal.last().unwrap().last() {
            Some(JournalEntry::AccountDestroyed {
                address,
                target,
                had_balance,
                ..
            }) => {
                host.external
                    .get_inspector()
                    .selfdestruct(*address, *target, *had_balance);
            }
            Some(JournalEntry::BalanceTransfer {
                from, to, balance, ..
            }) => {
                host.external
                    .get_inspector()
                    .selfdestruct(*from, *to, *balance);
            }
            _ => {}
        }
    });

    // call and create input stack shared between handlers. They are used to share
    // inputs in *_end Inspector calls.
    let call_input_stack = Rc::<RefCell<Vec<_>>>::default();
    let create_input_stack = Rc::<RefCell<Vec<_>>>::default();
    let eofcreate_input_stack = Rc::<RefCell<Vec<_>>>::default();

    // Create handler
    let create_input_stack_inner = create_input_stack.clone();
    let prev_handle = handler.execution.create.clone();
    handler.execution.create = Arc::new(
        move |ctx, mut inputs| -> EVMResultGeneric<FrameOrResult, EvmWiringT> {
            let inspector = ctx.external.get_inspector();
            // call inspector create to change input or return outcome.
            if let Some(outcome) = inspector.create(&mut ctx.evm, &mut inputs) {
                create_input_stack_inner.borrow_mut().push(inputs.clone());
                return Ok(FrameOrResult::Result(FrameResult::Create(outcome)));
            }
            create_input_stack_inner.borrow_mut().push(inputs.clone());

            let mut frame_or_result = prev_handle(ctx, inputs);
            if let Ok(FrameOrResult::Frame(frame)) = &mut frame_or_result {
                ctx.external
                    .get_inspector()
                    .initialize_interp(frame.interpreter_mut(), &mut ctx.evm)
            }
            frame_or_result
        },
    );

    // Call handler
    let call_input_stack_inner = call_input_stack.clone();
    let prev_handle = handler.execution.call.clone();
    handler.execution.call = Arc::new(move |ctx, mut inputs| {
        // Call inspector to change input or return outcome.
        let outcome = ctx.external.get_inspector().call(&mut ctx.evm, &mut inputs);
        call_input_stack_inner.borrow_mut().push(inputs.clone());
        if let Some(outcome) = outcome {
            return Ok(FrameOrResult::Result(FrameResult::Call(outcome)));
        }

        let mut frame_or_result = prev_handle(ctx, inputs);
        if let Ok(FrameOrResult::Frame(frame)) = &mut frame_or_result {
            ctx.external
                .get_inspector()
                .initialize_interp(frame.interpreter_mut(), &mut ctx.evm)
        }
        frame_or_result
    });

    // Calls inspector `eofcreate` and `initialize_interp` functions. Queues the inputs for the `eofcreate_end`` function.
    // Calls the old handler, and in case of inspector returning outcome,
    // returns the outcome without executing eofcreate.
    let eofcreate_input_stack_inner = eofcreate_input_stack.clone();
    let prev_handle = handler.execution.eofcreate.clone();
    handler.execution.eofcreate = Arc::new(move |ctx, mut inputs| {
        // Call inspector to change input or return outcome.
        let outcome = ctx
            .external
            .get_inspector()
            .eofcreate(&mut ctx.evm, &mut inputs);
        eofcreate_input_stack_inner
            .borrow_mut()
            .push(inputs.clone());
        if let Some(outcome) = outcome {
            return Ok(FrameOrResult::Result(FrameResult::EOFCreate(outcome)));
        }

        let mut frame_or_result = prev_handle(ctx, inputs);
        if let Ok(FrameOrResult::Frame(frame)) = &mut frame_or_result {
            ctx.external
                .get_inspector()
                .initialize_interp(frame.interpreter_mut(), &mut ctx.evm)
        }
        frame_or_result
    });

    // Pops eofcreate input from the stack and calls inspector `eofcreate_end` function.
    // preserve the old handler and calls it with the outcome.
    let eofcreate_input_stack_inner = eofcreate_input_stack.clone();
    let prev_handle = handler.execution.insert_eofcreate_outcome.clone();
    handler.execution.insert_eofcreate_outcome = Arc::new(move |ctx, frame, mut outcome| {
        let create_inputs = eofcreate_input_stack_inner.borrow_mut().pop().unwrap();
        outcome = ctx
            .external
            .get_inspector()
            .eofcreate_end(&mut ctx.evm, &create_inputs, outcome);
        prev_handle(ctx, frame, outcome)
    });

    // call outcome
    let call_input_stack_inner = call_input_stack.clone();
    let prev_handle = handler.execution.insert_call_outcome.clone();
    handler.execution.insert_call_outcome =
        Arc::new(move |ctx, frame, shared_memory, mut outcome| {
            let call_inputs = call_input_stack_inner.borrow_mut().pop().unwrap();
            outcome = ctx
                .external
                .get_inspector()
                .call_end(&mut ctx.evm, &call_inputs, outcome);
            prev_handle(ctx, frame, shared_memory, outcome)
        });

    // create outcome
    let create_input_stack_inner = create_input_stack.clone();
    let prev_handle = handler.execution.insert_create_outcome.clone();
    handler.execution.insert_create_outcome = Arc::new(move |ctx, frame, mut outcome| {
        let create_inputs = create_input_stack_inner.borrow_mut().pop().unwrap();
        outcome = ctx
            .external
            .get_inspector()
            .create_end(&mut ctx.evm, &create_inputs, outcome);
        prev_handle(ctx, frame, outcome)
    });

    // last frame outcome
    let prev_handle = handler.execution.last_frame_return.clone();
    handler.execution.last_frame_return = Arc::new(move |ctx, frame_result| {
        let inspector = ctx.external.get_inspector();
        match frame_result {
            FrameResult::Call(outcome) => {
                let call_inputs = call_input_stack.borrow_mut().pop().unwrap();
                *outcome = inspector.call_end(&mut ctx.evm, &call_inputs, outcome.clone());
            }
            FrameResult::Create(outcome) => {
                let create_inputs = create_input_stack.borrow_mut().pop().unwrap();
                *outcome = inspector.create_end(&mut ctx.evm, &create_inputs, outcome.clone());
            }
            FrameResult::EOFCreate(outcome) => {
                let eofcreate_inputs = eofcreate_input_stack.borrow_mut().pop().unwrap();
                *outcome =
                    inspector.eofcreate_end(&mut ctx.evm, &eofcreate_inputs, outcome.clone());
            }
        }
        prev_handle(ctx, frame_result)
    });
}

fn inspector_instruction<EvmWiringT>(
    prev: &DynInstruction<'_, Context<EvmWiringT>>,
    interpreter: &mut Interpreter,
    host: &mut Context<EvmWiringT>,
) where
    EvmWiringT: EvmWiring,
    EvmWiringT::ExternalContext: GetInspector<EvmWiringT>,
{
    // SAFETY: as the PC was already incremented we need to subtract 1 to preserve the
    // old Inspector behavior.
    interpreter.instruction_pointer = unsafe { interpreter.instruction_pointer.sub(1) };

    // Call step.
    host.external
        .get_inspector()
        .step(interpreter, &mut host.evm);
    if interpreter.instruction_result != InstructionResult::Continue {
        return;
    }

    // Reset PC to previous value.
    interpreter.instruction_pointer = unsafe { interpreter.instruction_pointer.add(1) };

    // Execute instruction.
    prev(interpreter, host);

    // Call step_end.
    host.external
        .get_inspector()
        .step_end(interpreter, &mut host.evm);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{inspector_handle_register, inspectors::NoOpInspector};
    use database::BenchmarkDB;
    use revm::{
        bytecode::{opcode, Bytecode},
        database_interface::EmptyDB,
        interpreter::{CallInputs, CallOutcome, CreateInputs, CreateOutcome},
        primitives::{address, Bytes, TxKind},
        wiring::{DefaultEthereumWiring, EthereumWiring, EvmWiring as PrimitiveEvmWiring},
        Evm, EvmContext, EvmWiring,
    };

    type TestEvmWiring = DefaultEthereumWiring;

    #[derive(Default, Debug)]
    struct StackInspector {
        initialize_interp_called: bool,
        step: u32,
        step_end: u32,
        call: bool,
        call_end: bool,
    }

    impl<EvmWiringT: EvmWiring> Inspector<EvmWiringT> for StackInspector {
        fn initialize_interp(
            &mut self,
            _interp: &mut Interpreter,
            _context: &mut EvmContext<EvmWiringT>,
        ) {
            if self.initialize_interp_called {
                unreachable!("initialize_interp should not be called twice")
            }
            self.initialize_interp_called = true;
        }

        fn step(&mut self, _interp: &mut Interpreter, _context: &mut EvmContext<EvmWiringT>) {
            self.step += 1;
        }

        fn step_end(&mut self, _interp: &mut Interpreter, _context: &mut EvmContext<EvmWiringT>) {
            self.step_end += 1;
        }

        fn call(
            &mut self,
            context: &mut EvmContext<EvmWiringT>,
            _call: &mut CallInputs,
        ) -> Option<CallOutcome> {
            if self.call {
                unreachable!("call should not be called twice")
            }
            self.call = true;
            assert_eq!(context.journaled_state.depth(), 0);
            None
        }

        fn call_end(
            &mut self,
            context: &mut EvmContext<EvmWiringT>,
            _inputs: &CallInputs,
            outcome: CallOutcome,
        ) -> CallOutcome {
            if self.call_end {
                unreachable!("call_end should not be called twice")
            }
            assert_eq!(context.journaled_state.depth(), 0);
            self.call_end = true;
            outcome
        }

        fn create(
            &mut self,
            context: &mut EvmContext<EvmWiringT>,
            _call: &mut CreateInputs,
        ) -> Option<CreateOutcome> {
            assert_eq!(context.journaled_state.depth(), 0);
            None
        }

        fn create_end(
            &mut self,
            context: &mut EvmContext<EvmWiringT>,
            _inputs: &CreateInputs,
            outcome: CreateOutcome,
        ) -> CreateOutcome {
            assert_eq!(context.journaled_state.depth(), 0);
            outcome
        }
    }

    #[test]
    fn test_inspector_handlers() {
        let contract_data: Bytes = Bytes::from(vec![
            opcode::PUSH1,
            0x1,
            opcode::PUSH1,
            0xb,
            opcode::PUSH1,
            0x1,
            opcode::PUSH1,
            0x1,
            opcode::PUSH1,
            0x1,
            opcode::CREATE,
            opcode::STOP,
        ]);
        let bytecode = Bytecode::new_raw(contract_data);

        let mut evm = Evm::<EthereumWiring<BenchmarkDB, StackInspector>>::builder()
            .with_default_ext_ctx()
            .with_db(BenchmarkDB::new_bytecode(bytecode.clone()))
            .with_external_context(StackInspector::default())
            .modify_tx_env(|tx| {
                *tx = <TestEvmWiring as PrimitiveEvmWiring>::Transaction::default();

                tx.caller = address!("1000000000000000000000000000000000000000");
                tx.transact_to = TxKind::Call(address!("0000000000000000000000000000000000000000"));
                tx.gas_limit = 21100;
            })
            .append_handler_register(inspector_handle_register)
            .build();

        // run evm.
        evm.transact().unwrap();

        let inspector = evm.into_context().external;

        assert_eq!(inspector.step, 6);
        assert_eq!(inspector.step_end, 6);
        assert!(inspector.initialize_interp_called);
        assert!(inspector.call);
        assert!(inspector.call_end);
    }

    #[test]
    fn test_inspector_reg() {
        let mut noop = NoOpInspector;
        let _evm: Evm<'_, EthereumWiring<EmptyDB, &mut NoOpInspector>> = Evm::builder()
            .with_default_db()
            .with_external_context(&mut noop)
            .append_handler_register(inspector_handle_register)
            .build();
    }
}