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
use crate::{
    circuit_input_builder::{CircuitInputStateRef, ExecStep},
    error::ExecError,
    evm::{Opcode, OpcodeId},
    operation::CallContextField,
    Error,
};

use eth_types::GethExecStep;

#[derive(Debug, Copy, Clone)]
pub(crate) struct ErrorWriteProtection;

impl Opcode for ErrorWriteProtection {
    fn gen_associated_ops(
        state: &mut CircuitInputStateRef,
        geth_steps: &[GethExecStep],
    ) -> Result<Vec<ExecStep>, Error> {
        let geth_step = &geth_steps[0];
        let mut exec_step = state.new_step(geth_step)?;
        let next_step = if geth_steps.len() > 1 {
            Some(&geth_steps[1])
        } else {
            None
        };
        exec_step.error = state.get_step_err(geth_step, next_step).unwrap();
        // assert error is targeting ExecError::WriteProtection.
        assert_eq!(exec_step.clone().error.unwrap(), ExecError::WriteProtection);

        let current_call = state.call()?.clone();
        // assert op code can only be following codes
        assert!([
            OpcodeId::SSTORE,
            OpcodeId::TSTORE,
            OpcodeId::CREATE,
            OpcodeId::CREATE2,
            OpcodeId::CALL,
            OpcodeId::SELFDESTRUCT,
            OpcodeId::LOG0,
            OpcodeId::LOG1,
            OpcodeId::LOG2,
            OpcodeId::LOG3,
            OpcodeId::LOG4
        ]
        .contains(&geth_step.op));

        if geth_step.op == OpcodeId::CALL {
            // get only the first three stack elements since the third one is the value we
            // want to check.
            for i in 0..3 {
                state.stack_read(
                    &mut exec_step,
                    geth_step.stack.nth_last_filled(i),
                    geth_step.stack.nth_last(i)?,
                )?;
            }
        }

        state.call_context_read(
            &mut exec_step,
            current_call.call_id,
            CallContextField::IsStatic,
            (current_call.is_static as u64).into(),
        )?;

        // `IsSuccess` call context operation is added in handle_return
        state.handle_return(&mut [&mut exec_step], geth_steps, true)?;
        Ok(vec![exec_step])
    }
}