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
use rand::Rng;
use triton_opcodes::shortcuts::{divine, read_io};
use triton_vm::BFieldElement;
use twenty_first::shared_math::other::random_elements;

use crate::{
    dyn_malloc, get_init_tvm_stack,
    snippet::{DataType, InputSource, Snippet},
    ExecutionState,
};

#[derive(Clone, Debug)]
pub struct LoadFromInput(pub InputSource);

/// Load a list of words from the input source into memory.
/// The first element of the input source is the length of the list
/// that is loaded into memory. Returns a pointer to the first element
/// in memory.
impl Snippet for LoadFromInput {
    fn entrypoint(&self) -> String {
        format!("tasm_io_load_from_input_{}", self.0)
    }

    fn inputs(&self) -> Vec<String> {
        vec![]
    }

    fn input_types(&self) -> Vec<crate::snippet::DataType> {
        vec![]
    }

    fn output_types(&self) -> Vec<crate::snippet::DataType> {
        vec![DataType::VoidPointer]
    }

    fn outputs(&self) -> Vec<String> {
        vec!["*addr".to_string()]
    }

    fn stack_diff(&self) -> isize {
        1
    }

    fn function_code(&self, library: &mut crate::snippet_state::SnippetState) -> String {
        let entrypoint = self.entrypoint();

        let dyn_alloc = library.import(Box::new(dyn_malloc::DynMalloc));

        let read_instruction = match self.0 {
            InputSource::StdIn => read_io(),
            InputSource::SecretIn => divine(),
        };

        format!(
            "
            // BEFORE: _
            // AFTER: _ *addr
            {entrypoint}:
                {read_instruction}
                // _ length

                // allocate memory for the input, including its own length indicator
                dup 0
                push 1
                add
                call {dyn_alloc}
                // _ length *addr

                // store the length indicator in the first element of dedicated memory
                dup 1
                write_mem
                // _ length *addr

                push 1
                add
                // _ length (*addr + 1)

                // set element counter i = 0
                push 0
                // _ length (*addr + 1) i
                call {entrypoint}_loop

                // _ length (*addr + 1) i
                pop
                push -1
                add
                // _ length *addr

                swap 1 pop
                // _ *addr

                return

                // TODO: You could probably calculate the end address here,
                // and use that in the loop termination condition instead of
                // keeping track of two variables, length and i.

                // START and END of loop: _ length (*addr + 1) i
                {entrypoint}_loop:
                    // check while-loop condition
                    dup 0
                    dup 3
                    eq

                    // _ length (*addr + 1) i (i == length)
                    skiz
                        return

                    // _ length (*addr + 1) i

                    dup 1
                    dup 1
                    add
                    // _ length (*addr + 1) i (*addr + 1 + i)

                    {read_instruction}
                    // _ length (*addr + 1) i (*addr + 1 + i) value_from_input

                    write_mem
                    // _ length (*addr + 1) i (*addr + 1 + i)

                    pop
                    // _ length (*addr + 1) i

                    push 1
                    add
                    // _ length (*addr + 1) (i + 1)

                    recurse
                "
        )
    }

    fn crash_conditions(&self) -> Vec<String> {
        vec![
            "size exceeds 2^32".to_owned(),
            "allocated memory exceeds 2^32".to_owned(),
            "input is shorter than indicated length".to_owned(),
            "input is empty".to_owned(),
        ]
    }

    fn gen_input_states(&self) -> Vec<crate::ExecutionState> {
        let mut ret = vec![];
        let mut thread_rng = rand::thread_rng();
        for _ in 0..10 {
            let length = thread_rng.gen_range(0..(1 << 10)) as u64;
            let input: Vec<BFieldElement> = vec![
                vec![BFieldElement::new(length)],
                random_elements(length as usize),
            ]
            .concat();
            ret.push(match self.0 {
                InputSource::StdIn => ExecutionState {
                    stack: get_init_tvm_stack(),
                    memory: std::collections::HashMap::new(),
                    std_in: input,
                    secret_in: vec![],
                    words_allocated: 0,
                },
                InputSource::SecretIn => ExecutionState {
                    stack: get_init_tvm_stack(),
                    memory: std::collections::HashMap::new(),
                    std_in: vec![],
                    secret_in: input,
                    words_allocated: 0,
                },
            });
        }

        ret
    }

    fn common_case_input_state(&self) -> crate::ExecutionState {
        let length = 1u64 << 9;
        let input: Vec<BFieldElement> = vec![
            vec![BFieldElement::new(length)],
            random_elements(length as usize),
        ]
        .concat();
        match self.0 {
            InputSource::StdIn => ExecutionState {
                stack: get_init_tvm_stack(),
                memory: std::collections::HashMap::new(),
                std_in: input,
                secret_in: vec![],
                words_allocated: 0,
            },
            InputSource::SecretIn => ExecutionState {
                stack: get_init_tvm_stack(),
                memory: std::collections::HashMap::new(),
                std_in: vec![],
                secret_in: input,
                words_allocated: 0,
            },
        }
    }

    fn worst_case_input_state(&self) -> crate::ExecutionState {
        let length = 1u64 << 13;
        let input: Vec<BFieldElement> = vec![
            vec![BFieldElement::new(length)],
            random_elements(length as usize),
        ]
        .concat();
        match self.0 {
            InputSource::StdIn => ExecutionState {
                stack: get_init_tvm_stack(),
                memory: std::collections::HashMap::new(),
                std_in: input,
                secret_in: vec![],
                words_allocated: 0,
            },
            InputSource::SecretIn => ExecutionState {
                stack: get_init_tvm_stack(),
                memory: std::collections::HashMap::new(),
                std_in: vec![],
                secret_in: input,
                words_allocated: 0,
            },
        }
    }

    fn rust_shadowing(
        &self,
        stack: &mut Vec<triton_vm::BFieldElement>,
        std_in: Vec<triton_vm::BFieldElement>,
        secret_in: Vec<triton_vm::BFieldElement>,
        memory: &mut std::collections::HashMap<triton_vm::BFieldElement, triton_vm::BFieldElement>,
    ) {
        // BEFORE: _
        // AFTER: _ *addr
        let input = match self.0 {
            InputSource::StdIn => std_in,
            InputSource::SecretIn => secret_in,
        };

        let indicated_length: usize = input[0].value() as usize;
        let pointer = crate::rust_shadowing_helper_functions::dyn_malloc::dynamic_allocator(
            indicated_length + 1,
            memory,
        );

        for (i, value_from_input) in input.into_iter().enumerate() {
            let addr = pointer + BFieldElement::new(i as u64);
            memory.insert(addr, value_from_input);
        }

        stack.push(pointer);
    }
}

#[cfg(test)]
mod tests {
    use crate::{execute_with_execution_state, test_helpers::test_rust_equivalence_multiple};

    use super::*;

    #[test]
    fn new_snippet_test() {
        test_rust_equivalence_multiple(&LoadFromInput(InputSource::SecretIn), true);
        test_rust_equivalence_multiple(&LoadFromInput(InputSource::StdIn), true);
    }

    #[test]
    fn verify_dyn_malloc_shows_correct_next_value() {
        for length in 0..10 {
            let state = ExecutionState {
                stack: get_init_tvm_stack(),
                memory: std::collections::HashMap::new(),
                std_in: vec![
                    vec![BFieldElement::new(length)],
                    random_elements(length as usize),
                ]
                .concat(),
                secret_in: vec![],
                words_allocated: 0,
            };
            let snippet = LoadFromInput(InputSource::StdIn);
            let stack_diff = snippet.stack_diff();
            let res = execute_with_execution_state(state, Box::new(snippet), stack_diff).unwrap();

            // Verify final state of dyn malloc. dyn malloc should be set to the next available
            // memory address.
            // Expected memory layout after running above program:
            // 0: dynamic allocator value
            // 1: indicated length
            // 2..N: elements of input, after indicated length
            // N+1: next available memory address
            let indicated_next_free_address =
                res.final_ram[&BFieldElement::new(dyn_malloc::DYN_MALLOC_ADDRESS as u64)].value();
            assert_eq!(length + 2, indicated_next_free_address);
            assert!(res
                .final_ram
                .get(&BFieldElement::new(indicated_next_free_address))
                .is_none());
        }
    }
}

#[cfg(test)]
mod benches {
    use super::*;
    use crate::snippet_bencher::bench_and_write;

    #[test]
    fn load_from_input_benchmark() {
        bench_and_write(LoadFromInput(InputSource::SecretIn));
        bench_and_write(LoadFromInput(InputSource::StdIn));
    }
}