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
use std::collections::HashMap;

use crate::runtime::{ForkState, Syscall, SyscallContext};

pub struct SyscallEnterUnconstrained;

impl SyscallEnterUnconstrained {
    pub const fn new() -> Self {
        Self
    }
}

impl Syscall for SyscallEnterUnconstrained {
    fn execute(&self, ctx: &mut SyscallContext, _: u32, _: u32) -> Option<u32> {
        if ctx.rt.unconstrained {
            panic!("Unconstrained block is already active.");
        }
        ctx.rt.unconstrained = true;
        ctx.rt.unconstrained_state = ForkState {
            global_clk: ctx.rt.state.global_clk,
            clk: ctx.rt.state.clk,
            pc: ctx.rt.state.pc,
            memory_diff: HashMap::default(),
            record: std::mem::take(&mut ctx.rt.record),
            op_record: std::mem::take(&mut ctx.rt.memory_accesses),
            emit_events: ctx.rt.emit_events,
        };
        ctx.rt.emit_events = false;
        Some(1)
    }
}

pub struct SyscallExitUnconstrained;

impl SyscallExitUnconstrained {
    pub const fn new() -> Self {
        Self
    }
}

impl Syscall for SyscallExitUnconstrained {
    fn execute(&self, ctx: &mut SyscallContext, _: u32, _: u32) -> Option<u32> {
        // Reset the state of the runtime.
        if ctx.rt.unconstrained {
            ctx.rt.state.global_clk = ctx.rt.unconstrained_state.global_clk;
            ctx.rt.state.clk = ctx.rt.unconstrained_state.clk;
            ctx.rt.state.pc = ctx.rt.unconstrained_state.pc;
            ctx.next_pc = ctx.rt.state.pc.wrapping_add(4);
            for (addr, value) in ctx.rt.unconstrained_state.memory_diff.drain() {
                match value {
                    Some(value) => {
                        ctx.rt.state.memory.insert(addr, value);
                    }
                    None => {
                        ctx.rt.state.memory.remove(&addr);
                    }
                }
            }
            ctx.rt.record = std::mem::take(&mut ctx.rt.unconstrained_state.record);
            ctx.rt.memory_accesses = std::mem::take(&mut ctx.rt.unconstrained_state.op_record);
            ctx.rt.emit_events = ctx.rt.unconstrained_state.emit_events;
            ctx.rt.unconstrained = false;
        }
        ctx.rt.unconstrained_state = ForkState::default();
        Some(0)
    }
}

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

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