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
use bus_mapping::evm::OpcodeId;
use eth_types::Field;
use halo2_proofs::{
    circuit::Value,
    plonk::{Error, Expression},
};

use crate::{
    evm_circuit::{
        param::{N_BYTES_MEMORY_ADDRESS, N_BYTES_U64, N_BYTES_WORD},
        step::ExecutionState,
        util::{
            and,
            common_gadget::{SameContextGadget, WordByteCapGadget},
            constraint_builder::{
                ConstrainBuilderCommon, EVMConstraintBuilder, StepStateTransition,
                Transition::Delta,
            },
            memory_gadget::BufferReaderGadget,
            not, select, CachedRegion, Cell,
        },
        witness::{Block, Call, Chunk, ExecStep, Transaction},
    },
    table::{CallContextFieldTag, TxContextFieldTag},
    util::{
        word::{Word32, WordExpr, WordLoHi},
        Expr,
    },
};

use super::ExecutionGadget;

// The offset in the RW indices that mark the start of memory lookups.
const OFFSET_RW_MEMORY_INDICES: usize = 4usize;

#[derive(Clone, Debug)]
pub(crate) struct CallDataLoadGadget<F> {
    /// Gadget to constrain the same context.
    same_context: SameContextGadget<F>,
    /// Source of data, this is transaction ID for a root call and caller ID for
    /// an internal call.
    src_id: Cell<F>,
    /// The size of the call's data (tx input for a root call or calldata length
    /// of an internal call).
    call_data_length: Cell<F>,
    /// The offset from where call data begins. This is 0 for a root call since
    /// tx data starts at the first byte, but can be non-zero offset for an
    /// internal call.
    call_data_offset: Cell<F>,
    /// The bytes offset in calldata, from which we load a 32-bytes word. It
    /// is valid if within range of Uint64 and less than call_data_length.
    data_offset: WordByteCapGadget<F, N_BYTES_U64>,
    /// Gadget to read from tx calldata, which we validate against the word
    /// pushed to stack.
    buffer_reader: BufferReaderGadget<F, N_BYTES_WORD, N_BYTES_MEMORY_ADDRESS>,
}

impl<F: Field> ExecutionGadget<F> for CallDataLoadGadget<F> {
    const EXECUTION_STATE: ExecutionState = ExecutionState::CALLDATALOAD;

    const NAME: &'static str = "CALLDATALOAD";

    fn configure(cb: &mut EVMConstraintBuilder<F>) -> Self {
        let opcode = cb.query_cell();

        let src_id = cb.query_cell();
        let call_data_length = cb.query_cell();
        let call_data_offset = cb.query_cell();

        let data_offset = WordByteCapGadget::construct(cb, call_data_length.expr());
        cb.stack_pop(data_offset.original_word().to_word());

        cb.condition(
            and::expr([data_offset.not_overflow(), cb.curr.state.is_root.expr()]),
            |cb| {
                cb.call_context_lookup_read(
                    None,
                    CallContextFieldTag::TxId,
                    WordLoHi::from_lo_unchecked(src_id.expr()),
                );
                cb.call_context_lookup_read(
                    None,
                    CallContextFieldTag::CallDataLength,
                    WordLoHi::from_lo_unchecked(call_data_length.expr()),
                );
                cb.require_equal(
                    "if is_root then call_data_offset == 0",
                    call_data_offset.expr(),
                    0.expr(),
                );
            },
        );

        cb.condition(
            and::expr([
                data_offset.not_overflow(),
                not::expr(cb.curr.state.is_root.expr()),
            ]),
            |cb| {
                cb.call_context_lookup_read(
                    None,
                    CallContextFieldTag::CallerId,
                    WordLoHi::from_lo_unchecked(src_id.expr()),
                );
                cb.call_context_lookup_read(
                    None,
                    CallContextFieldTag::CallDataLength,
                    WordLoHi::from_lo_unchecked(call_data_length.expr()),
                );
                cb.call_context_lookup_read(
                    None,
                    CallContextFieldTag::CallDataOffset,
                    WordLoHi::from_lo_unchecked(call_data_offset.expr()),
                );
            },
        );

        // Set source start to the minimum value of data offset and call data length.
        let src_addr = call_data_offset.expr()
            + select::expr(
                data_offset.lt_cap(),
                data_offset.valid_value(),
                call_data_length.expr(),
            );

        let src_addr_end = call_data_offset.expr() + call_data_length.expr();

        let buffer_reader = BufferReaderGadget::construct(cb, src_addr.expr(), src_addr_end);

        let mut calldata_word: Vec<_> = (0..N_BYTES_WORD)
            .map(|idx| {
                // For a root call, the call data comes from tx's data field.
                cb.condition(
                    and::expr([
                        data_offset.not_overflow(),
                        buffer_reader.read_flag(idx),
                        cb.curr.state.is_root.expr(),
                    ]),
                    |cb| {
                        cb.tx_context_lookup(
                            src_id.expr(),
                            TxContextFieldTag::CallData,
                            Some(src_addr.expr() + idx.expr()),
                            WordLoHi::from_lo_unchecked(buffer_reader.byte(idx)),
                        );
                    },
                );
                // For an internal call, the call data comes from memory.
                cb.condition(
                    and::expr([
                        data_offset.not_overflow(),
                        buffer_reader.read_flag(idx),
                        not::expr(cb.curr.state.is_root.expr()),
                    ]),
                    |cb| {
                        cb.memory_lookup(
                            0.expr(),
                            src_addr.expr() + idx.expr(),
                            buffer_reader.byte(idx),
                            Some(src_id.expr()),
                        );
                    },
                );
                buffer_reader.byte(idx)
            })
            .collect();

        // Since the stack items are in little endian form, we reverse the bytes
        // here.
        calldata_word.reverse();

        // Add a lookup constraint for the 32-bytes that should have been pushed
        // to the stack.
        let calldata_word: [Expression<F>; N_BYTES_WORD] = calldata_word.try_into().unwrap();
        let calldata_word = Word32::new(calldata_word);
        cb.require_zero_word(
            "Stack push result must be 0 if stack pop offset is Uint64 overflow",
            calldata_word.to_word().mul_selector(data_offset.overflow()),
        );

        cb.stack_push(calldata_word.to_word());

        let step_state_transition = StepStateTransition {
            rw_counter: Delta(cb.rw_counter_offset()),
            program_counter: Delta(1.expr()),
            stack_pointer: Delta(0.expr()),
            gas_left: Delta(-OpcodeId::CALLDATALOAD.constant_gas_cost().expr()),
            ..Default::default()
        };

        let same_context = SameContextGadget::construct(cb, opcode, step_state_transition);

        Self {
            same_context,
            src_id,
            call_data_length,
            call_data_offset,
            data_offset,
            buffer_reader,
        }
    }

    fn assign_exec_step(
        &self,
        region: &mut CachedRegion<'_, '_, F>,
        offset: usize,
        block: &Block<F>,
        _chunk: &Chunk<F>,
        tx: &Transaction,
        call: &Call,
        step: &ExecStep,
    ) -> Result<(), Error> {
        self.same_context.assign_exec_step(region, offset, step)?;

        // Assign to the buffer reader gadget.
        let (src_id, call_data_offset, call_data_length) = if call.is_root {
            (
                tx.id,
                0,
                if tx.is_create() {
                    0
                } else {
                    tx.call_data.len() as u64
                },
            )
        } else {
            (
                call.caller_id as u64,
                call.call_data_offset,
                call.call_data_length,
            )
        };
        self.src_id
            .assign(region, offset, Value::known(F::from(src_id)))?;
        self.call_data_length
            .assign(region, offset, Value::known(F::from(call_data_length)))?;
        self.call_data_offset
            .assign(region, offset, Value::known(F::from(call_data_offset)))?;

        let data_offset = block.get_rws(step, 0).stack_value();
        let offset_not_overflow =
            self.data_offset
                .assign(region, offset, data_offset, F::from(call_data_length))?;

        let data_offset = if offset_not_overflow {
            data_offset.as_u64()
        } else {
            call_data_length
        };
        let src_addr_end = call_data_offset + call_data_length;
        let src_addr = call_data_offset
            .checked_add(data_offset)
            .unwrap_or(src_addr_end)
            .min(src_addr_end);

        let mut calldata_bytes = vec![0u8; N_BYTES_WORD];
        if offset_not_overflow {
            for (i, byte) in calldata_bytes.iter_mut().enumerate() {
                if call.is_root {
                    // Fetch from tx call data.
                    if src_addr + (i as u64) < call_data_length {
                        *byte = tx.call_data[src_addr as usize + i];
                    }
                } else {
                    // Fetch from memory.
                    if src_addr + (i as u64) < call.call_data_offset + call.call_data_length {
                        *byte = block
                            .get_rws(step, OFFSET_RW_MEMORY_INDICES + i)
                            .memory_value();
                    }
                }
            }
        }

        self.buffer_reader
            .assign(region, offset, src_addr, src_addr_end, &calldata_bytes)?;

        Ok(())
    }
}

#[cfg(test)]
mod test {
    use crate::{evm_circuit::test::rand_bytes, test_util::CircuitTestBuilder};
    use eth_types::{bytecode, Word};
    use mock::{generate_mock_call_bytecode, MockCallBytecodeParams, TestContext};

    fn test_bytecode(offset: Word) -> eth_types::Bytecode {
        bytecode! {
            PUSH32(offset)
            CALLDATALOAD
            STOP
        }
    }

    fn test_root_ok(offset: Word) {
        let bytecode = test_bytecode(offset);

        CircuitTestBuilder::new_from_test_ctx(
            TestContext::<2, 1>::simple_ctx_with_bytecode(bytecode).unwrap(),
        )
        .run();
    }

    fn test_internal_ok(call_data_length: usize, call_data_offset: usize, offset: Word) {
        let (addr_a, addr_b) = (mock::MOCK_ACCOUNTS[0], mock::MOCK_ACCOUNTS[1]);

        // code B gets called by code A, so the call is an internal call.
        let code_b = test_bytecode(offset);
        let code_a = generate_mock_call_bytecode(MockCallBytecodeParams {
            address: addr_b,
            pushdata: rand_bytes(32),
            call_data_length,
            call_data_offset,
            ..MockCallBytecodeParams::default()
        });

        let ctx = TestContext::<3, 1>::new(
            None,
            |accs| {
                accs[0].address(addr_b).code(code_b);
                accs[1].address(addr_a).code(code_a);
                accs[2]
                    .address(mock::MOCK_ACCOUNTS[2])
                    .balance(Word::from(1u64 << 30));
            },
            |mut txs, accs| {
                txs[0].to(accs[1].address).from(accs[2].address);
            },
            |block, _tx| block,
        )
        .unwrap();

        CircuitTestBuilder::new_from_test_ctx(ctx).run();
    }

    #[test]
    fn calldataload_gadget_root() {
        test_root_ok(0x00.into());
        test_root_ok(0x08.into());
        test_root_ok(0x10.into());
        test_root_ok(0x2010.into());
    }

    #[test]
    fn calldataload_gadget_internal() {
        test_internal_ok(0x20, 0x00, 0x00.into());
        test_internal_ok(0x20, 0x10, 0x10.into());
        test_internal_ok(0x40, 0x20, 0x08.into());
        test_internal_ok(0x1010, 0xff, 0x10.into());
    }

    #[test]
    fn calldataload_gadget_offset_overflow() {
        test_root_ok(Word::MAX);
        test_internal_ok(0x1010, 0xff, Word::MAX);
    }
}