File size: 1,265 Bytes
7693357
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bf4530
 
 
 
01cf25d
 
2a4c759
 
01cf25d
2a4c759
7693357
 
 
 
 
4bf4530
 
 
7693357
 
 
 
4bf4530
7693357
 
 
 
 
 
 
 
 
4bf4530
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
use crate::{opcode::Opcode, registers::Registers, state::VMState};

pub struct BCNVM {
    pub regs: Registers,
    pub state: VMState,
    pub pc: usize,
    pub program: Vec<u8>,
}

impl BCNVM {
    pub fn new(program: Vec<u8>) -> Self {
        Self {
            regs: Registers::new(),
            state: VMState::new(),
            pc: 0,
            program,
        }
    }

    pub fn run(&mut self) -> Result<(), String> {
        while self.pc < self.program.len() {
            if self.pc + 8 > self.program.len() {
                return Err("Instruction out of bounds".into());
            }

            let instr: [u8; 8] = self.program[self.pc..self.pc + 8]
                .try_into()
                .map_err(|_| "Invalid instruction")?;

            let opcode = Opcode::from_byte(instr[0])
                .ok_or("Invalid opcode")?;

            match opcode {
                Opcode::INVCHK => self.invchk()?,
                Opcode::HALT => break,
                Opcode::NOOP => {}
                _ => {}
            }

            self.pc += 8;
        }

        Ok(())
    }

    fn invchk(&self) -> Result<(), String> {
        if self.state.trust < 0 {
            return Err("Trust underflow".into());
        }
        Ok(())
    }
}