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
use super::{
    AccountOp, CallContextOp, MemoryOp, Op, OpEnum, Operation, PaddingOp, RWCounter, StackOp,
    StartOp, StepStateOp, StorageOp, Target, TransientStorageOp, TxAccessListAccountOp,
    TxAccessListAccountStorageOp, TxLogOp, TxReceiptOp, TxRefundOp, RW,
};
use crate::exec_trace::OperationRef;
use itertools::Itertools;

/// The `OperationContainer` is meant to store all of the [`Operation`]s that an
/// [`ExecStep`](crate::circuit_input_builder::ExecStep) performs during its
/// execution.
///
/// Once an operation is inserted into the container, it returns an
/// [`OperationRef`] which holds an index to the operation just inserted.
/// These references are stored inside of the bus-mapping instances of each
/// [`ExecStep`](crate::circuit_input_builder::ExecStep).
///
/// Finally, the container also provides the capability of retrieving all of the
/// `Stack`, `Memory` or `Storage` operations ordered according to the criteria
/// they have specified.
/// That serves as a way to get an input with which is easy to work with in
/// order to construct the State proof.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OperationContainer {
    /// Operations of MemoryOp
    pub memory: Vec<Operation<MemoryOp>>,
    /// Operations of StackOp
    pub stack: Vec<Operation<StackOp>>,
    /// Operations of StorageOp
    pub storage: Vec<Operation<StorageOp>>,
    /// Operations of TransientStorageOp
    pub transient_storage: Vec<Operation<TransientStorageOp>>,
    /// Operations of TxAccessListAccountOp
    pub tx_access_list_account: Vec<Operation<TxAccessListAccountOp>>,
    /// Operations of TxAccessListAccountStorageOp
    pub tx_access_list_account_storage: Vec<Operation<TxAccessListAccountStorageOp>>,
    /// Operations of TxRefundOp
    pub tx_refund: Vec<Operation<TxRefundOp>>,
    /// Operations of AccountOp
    pub account: Vec<Operation<AccountOp>>,
    /// Operations of CallContextOp
    pub call_context: Vec<Operation<CallContextOp>>,
    /// Operations of TxReceiptOp
    pub tx_receipt: Vec<Operation<TxReceiptOp>>,
    /// Operations of TxLogOp
    pub tx_log: Vec<Operation<TxLogOp>>,
    /// Operations of Start
    pub start: Vec<Operation<StartOp>>,
    /// Operations of Padding
    pub padding: Vec<Operation<PaddingOp>>,
    /// Operations of StepState
    pub step_state: Vec<Operation<StepStateOp>>,
}

impl Default for OperationContainer {
    fn default() -> Self {
        Self::new()
    }
}

// TODO: impl Index for OperationContainer
impl OperationContainer {
    /// Generates a new instance of an `OperationContainer`.
    pub fn new() -> Self {
        Self {
            memory: Vec::new(),
            stack: Vec::new(),
            storage: Vec::new(),
            transient_storage: Vec::new(),
            tx_access_list_account: Vec::new(),
            tx_access_list_account_storage: Vec::new(),
            tx_refund: Vec::new(),
            account: Vec::new(),
            call_context: Vec::new(),
            tx_receipt: Vec::new(),
            tx_log: Vec::new(),
            start: Vec::new(),
            padding: Vec::new(),
            step_state: Vec::new(),
        }
    }

    /// Inserts an [`Operation`] into the  container returning a lightweight
    /// reference to it in the form of an [`OperationRef`] which points to the
    /// location of the inserted operation inside the corresponding container
    /// vector.
    pub fn insert<T: Op>(&mut self, op: Operation<T>) -> OperationRef {
        let rwc = op.rwc();
        let rwc_inner_chunk = op.rwc_inner_chunk();
        let rw = op.rw();
        let reversible = op.reversible();
        self.insert_op_enum(rwc, rwc_inner_chunk, rw, reversible, op.op.into_enum())
    }

    /// Inserts an [`OpEnum`] into the  container returning a lightweight
    /// reference to it in the form of an [`OperationRef`] which points to the
    /// location of the inserted operation inside the corresponding container
    /// vector.
    pub fn insert_op_enum(
        &mut self,
        rwc: RWCounter,
        rwc_inner_chunk: RWCounter,
        rw: RW,
        reversible: bool,
        op_enum: OpEnum,
    ) -> OperationRef {
        match op_enum {
            OpEnum::Memory(op) => {
                self.memory
                    .push(Operation::new(rwc, rwc_inner_chunk, rw, op));
                OperationRef::from((Target::Memory, self.memory.len() - 1))
            }
            OpEnum::Stack(op) => {
                self.stack
                    .push(Operation::new(rwc, rwc_inner_chunk, rw, op));
                OperationRef::from((Target::Stack, self.stack.len() - 1))
            }
            OpEnum::Storage(op) => {
                self.storage.push(if reversible {
                    Operation::new_reversible(rwc, rwc_inner_chunk, rw, op)
                } else {
                    Operation::new(rwc, rwc_inner_chunk, rw, op)
                });
                OperationRef::from((Target::Storage, self.storage.len() - 1))
            }
            OpEnum::TransientStorage(op) => {
                self.transient_storage.push(if reversible {
                    Operation::new_reversible(rwc, rwc_inner_chunk, rw, op)
                } else {
                    Operation::new(rwc, rwc_inner_chunk, rw, op)
                });
                OperationRef::from((Target::TransientStorage, self.transient_storage.len() - 1))
            }
            OpEnum::TxAccessListAccount(op) => {
                self.tx_access_list_account.push(if reversible {
                    Operation::new_reversible(rwc, rwc_inner_chunk, rw, op)
                } else {
                    Operation::new(rwc, rwc_inner_chunk, rw, op)
                });
                OperationRef::from((
                    Target::TxAccessListAccount,
                    self.tx_access_list_account.len() - 1,
                ))
            }
            OpEnum::TxAccessListAccountStorage(op) => {
                self.tx_access_list_account_storage.push(if reversible {
                    Operation::new_reversible(rwc, rwc_inner_chunk, rw, op)
                } else {
                    Operation::new(rwc, rwc_inner_chunk, rw, op)
                });
                OperationRef::from((
                    Target::TxAccessListAccountStorage,
                    self.tx_access_list_account_storage.len() - 1,
                ))
            }
            OpEnum::TxRefund(op) => {
                self.tx_refund.push(if reversible {
                    Operation::new_reversible(rwc, rwc_inner_chunk, rw, op)
                } else {
                    Operation::new(rwc, rwc_inner_chunk, rw, op)
                });
                OperationRef::from((Target::TxRefund, self.tx_refund.len() - 1))
            }
            OpEnum::Account(op) => {
                self.account.push(if reversible {
                    Operation::new_reversible(rwc, rwc_inner_chunk, rw, op)
                } else {
                    Operation::new(rwc, rwc_inner_chunk, rw, op)
                });
                OperationRef::from((Target::Account, self.account.len() - 1))
            }
            OpEnum::CallContext(op) => {
                self.call_context
                    .push(Operation::new(rwc, rwc_inner_chunk, rw, op));
                OperationRef::from((Target::CallContext, self.call_context.len() - 1))
            }
            OpEnum::TxReceipt(op) => {
                self.tx_receipt
                    .push(Operation::new(rwc, rwc_inner_chunk, rw, op));
                OperationRef::from((Target::TxReceipt, self.tx_receipt.len() - 1))
            }
            OpEnum::TxLog(op) => {
                self.tx_log
                    .push(Operation::new(rwc, rwc_inner_chunk, rw, op));
                OperationRef::from((Target::TxLog, self.tx_log.len() - 1))
            }
            OpEnum::Start(op) => {
                self.start
                    .push(Operation::new(rwc, rwc_inner_chunk, rw, op));
                OperationRef::from((Target::Start, self.start.len() - 1))
            }
            OpEnum::Padding(op) => {
                self.padding
                    .push(Operation::new(rwc, rwc_inner_chunk, rw, op));
                OperationRef::from((Target::Padding, self.padding.len() - 1))
            }
            OpEnum::StepState(op) => {
                self.step_state
                    .push(Operation::new(rwc, rwc_inner_chunk, rw, op));
                OperationRef::from((Target::StepState, self.step_state.len() - 1))
            }
        }
    }

    /// Returns a sorted vector of all of the [`MemoryOp`]s contained inside of
    /// the container.
    pub fn sorted_memory(&self) -> Vec<Operation<MemoryOp>> {
        self.memory.iter().sorted().cloned().collect()
    }

    /// Returns a sorted vector of all of the [`StackOp`]s contained inside of
    /// the container.
    pub fn sorted_stack(&self) -> Vec<Operation<StackOp>> {
        self.stack.iter().sorted().cloned().collect()
    }

    /// Returns a sorted vector of all of the [`StorageOp`]s contained inside of
    /// the container.
    pub fn sorted_storage(&self) -> Vec<Operation<StorageOp>> {
        self.storage.iter().sorted().cloned().collect()
    }
}

#[cfg(test)]
mod container_test {
    use super::*;

    use crate::operation::{RWCounter, RW};
    use eth_types::{
        evm_types::{MemoryAddress, StackAddress},
        Address, Word,
    };

    #[test]
    fn operation_container_test() {
        // global counter same as intra_chunk_counter in single chunk
        let mut global_counter = RWCounter::default();
        let mut intra_chunk_counter = RWCounter::default();
        let mut operation_container = OperationContainer::default();
        let stack_operation = Operation::new(
            global_counter.inc_pre(),
            intra_chunk_counter.inc_pre(),
            RW::WRITE,
            StackOp::new(1, StackAddress(1023), Word::from(0x100)),
        );
        let memory_operation = Operation::new(
            global_counter.inc_pre(),
            intra_chunk_counter.inc_pre(),
            RW::WRITE,
            MemoryOp::new(1, MemoryAddress::from(1), 1),
        );
        let storage_operation = Operation::new(
            global_counter.inc_pre(),
            intra_chunk_counter.inc_pre(),
            RW::WRITE,
            StorageOp::new(
                Address::zero(),
                Word::default(),
                Word::from(0x1),
                Word::default(),
                1usize,
                Word::default(),
            ),
        );
        let stack_ref = operation_container.insert(stack_operation.clone());
        let memory_ref = operation_container.insert(memory_operation.clone());
        let storage_ref = operation_container.insert(storage_operation.clone());

        assert_eq!(operation_container.sorted_stack()[0], stack_operation);
        assert_eq!(operation_container.sorted_memory()[0], memory_operation);
        assert_eq!(operation_container.sorted_storage()[0], storage_operation);
        assert_eq!(stack_ref, OperationRef::from((Target::Stack, 0)));
        assert_eq!(memory_ref, OperationRef::from((Target::Memory, 0)));
        assert_eq!(storage_ref, OperationRef::from((Target::Storage, 0)));
    }
}