tasm_lib/traits/
accessor.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
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use rand::prelude::*;
use triton_vm::prelude::*;

use super::basic_snippet::BasicSnippet;
use super::rust_shadow::RustShadow;
use crate::linker::execute_bench;
use crate::linker::link_for_isolated_run;
use crate::snippet_bencher::write_benchmarks;
use crate::snippet_bencher::BenchmarkCase;
use crate::snippet_bencher::NamedBenchmarkResult;
use crate::test_helpers::test_rust_equivalence_given_complete_state;
use crate::InitVmState;
use crate::VmHasher;

/// An Accessor can modify that stack but only read from memory
///
/// An Accessor is a piece of tasm code that can read from and write to the
/// stack but can only read from memory. Note that it cannot write to static
/// memory. It cannot read from any inputs or write to standard out. It cannot
/// modify the sponge state.
/// See also: [closure], [function], [procedure], [algorithm],
///           [read_only_algorithm], [mem_preserver]
///
/// [closure]: crate::traits::closure::Closure
/// [function]: crate::traits::function::Function
/// [procedure]: crate::traits::procedure::Procedure
/// [algorithm]: crate::traits::algorithm::Algorithm
/// [read_only_algorithm]: crate::traits::read_only_algorithm::ReadOnlyAlgorithm
/// [mem_preserver]: crate::traits::mem_preserver::MemPreserver
pub trait Accessor: BasicSnippet {
    fn rust_shadow(
        &self,
        stack: &mut Vec<BFieldElement>,
        memory: &HashMap<BFieldElement, BFieldElement>,
    );

    fn pseudorandom_initial_state(
        &self,
        seed: [u8; 32],
        bench_case: Option<BenchmarkCase>,
    ) -> AccessorInitialState;

    fn corner_case_initial_states(&self) -> Vec<AccessorInitialState> {
        vec![]
    }
}

#[derive(Debug, Clone, Default)]
pub struct AccessorInitialState {
    pub stack: Vec<BFieldElement>,
    pub memory: HashMap<BFieldElement, BFieldElement>,
}

impl From<AccessorInitialState> for InitVmState {
    fn from(value: AccessorInitialState) -> Self {
        let nd = NonDeterminism::default().with_ram(value.memory);
        Self {
            stack: value.stack,
            nondeterminism: nd,
            ..Default::default()
        }
    }
}

pub struct ShadowedAccessor<T: Accessor + 'static> {
    accessor: Rc<RefCell<T>>,
}

impl<T: Accessor + 'static> ShadowedAccessor<T> {
    pub fn new(accessor: T) -> Self {
        Self {
            accessor: Rc::new(RefCell::new(accessor)),
        }
    }
}

impl<T> RustShadow for ShadowedAccessor<T>
where
    T: Accessor + 'static,
{
    fn inner(&self) -> Rc<RefCell<dyn BasicSnippet>> {
        self.accessor.clone()
    }

    fn rust_shadow_wrapper(
        &self,
        _stdin: &[BFieldElement],
        _nondeterminism: &NonDeterminism,
        stack: &mut Vec<BFieldElement>,
        memory: &mut HashMap<BFieldElement, BFieldElement>,
        _sponge: &mut Option<VmHasher>,
    ) -> Vec<BFieldElement> {
        self.accessor.borrow().rust_shadow(stack, memory);
        vec![]
    }

    fn test(&self) {
        for corner_case in self
            .accessor
            .borrow()
            .corner_case_initial_states()
            .into_iter()
        {
            let stdin = vec![];
            let nd = NonDeterminism::default().with_ram(corner_case.memory);
            test_rust_equivalence_given_complete_state(
                self,
                &corner_case.stack,
                &stdin,
                &nd,
                &None,
                None,
            );
        }

        let num_states = 10;
        let seed: [u8; 32] = thread_rng().gen();
        let mut rng: StdRng = SeedableRng::from_seed(seed);
        for _ in 0..num_states {
            let seed: [u8; 32] = rng.gen();
            let AccessorInitialState { stack, memory } = self
                .accessor
                .borrow()
                .pseudorandom_initial_state(seed, None);

            let stdin = vec![];
            let nd = NonDeterminism::default().with_ram(memory);
            test_rust_equivalence_given_complete_state(self, &stack, &stdin, &nd, &None, None);
        }
    }

    fn bench(&self) {
        let mut rng: StdRng = SeedableRng::from_seed(
            hex::decode("73a24b6b8b32e4d7d563a4d9a85f476573a24b6b8b32e4d7d563a4d9a85f4765")
                .unwrap()
                .try_into()
                .unwrap(),
        );
        let mut benchmarks = Vec::with_capacity(2);

        for bench_case in [BenchmarkCase::CommonCase, BenchmarkCase::WorstCase] {
            let AccessorInitialState { stack, memory } = self
                .accessor
                .borrow()
                .pseudorandom_initial_state(rng.gen(), Some(bench_case));
            let program = link_for_isolated_run(self.accessor.clone());
            let nd = NonDeterminism::default().with_ram(memory);
            let benchmark = execute_bench(&program, &stack, vec![], nd, None);
            let benchmark = NamedBenchmarkResult {
                name: self.accessor.borrow().entrypoint(),
                benchmark_result: benchmark,
                case: bench_case,
            };
            benchmarks.push(benchmark);
        }

        write_benchmarks(benchmarks);
    }
}