Make a host in Rust, step 4: prove it exact

Your host shows what the reference shows. This step proves that it agrees to the last bit, with a yes-or-no test: the state hash. It adds the module state to the crate.

The state serialization

Between frames, a machine's whole state is one string of bytes; its BLAKE3-256 hash is the state hash. Two hosts given the same program and input agree exactly when their hashes agree after every frame.

use crate::frames::{Machine, Status};

impl Machine {
    pub fn state(
        &self,
        id: &[u8; 32],
        grants: &[u8],
        terminal: Option<&[u8]>,
    ) -> Vec<u8> {
        let mut state = b"terse-state-1".to_vec();
        state.extend(id);
        state.extend(self.cpu.pc.to_le_bytes());
        for x in &self.cpu.x[1..] {
            state.extend(x.to_le_bytes());
        }
        state.extend(self.frame.to_le_bytes());
        let (stopped, code, fault) = match self.status {
            Status::Running => (0, 0, None),
            Status::Exited(code) => (1, code, None),
            Status::Faulted(fault) => (2, 0, Some(fault)),
        };
        let kind = fault.map_or(0, |f| f.kind as u8);
        state.extend([stopped, code, kind]);
        for value in [
            fault.map_or(0, |f| f.encoding),
            fault.map_or(0, |_| self.cpu.pc),
            fault.map_or(0, |f| f.address),
            self.budget as u32,
            self.cpu.ram.len() as u32,
        ] {
            state.extend(value.to_le_bytes());
        }
        state.extend(&self.cpu.ram);
        state.extend(grants);
        state.extend([0; 37]);
        match terminal {
            Some(section) => {
                state.push(1);
                state.extend(section);
            }
            None => state.push(0),
        }
        state.extend([0, 0, 0]);
        state
    }
}

In order: terse-state-1 and the image ID; pc and the registers x1 to x31; the frame counter, how the machine stopped (0 running, 1 exited, 2 faulted), the exit code, and a fault's kind, encoding, pc and address; the budget carried into the next frame; the RAM; one byte per optional device, 1 if granted. Then the System device: 37 zero bytes here (the time, 0 in a test; an empty event queue; four controllers, none connected). Then each device's section in a fixed order, from its driver's STATE: the terminal's with a byte 1 before it, or a 0 for a machine without one; then a 0 each for the vector display, content and the page, which this host never has.

The program

use host::bus::Bus;
use host::frames::{Machine, Status};
use host::image::load;
use std::error::Error;
use std::process::exit;

fn main() -> Result<(), Box<dyn Error>> {
    let args: Vec<String> = std::env::args().collect();
    let file = std::fs::read(&args[1])?;
    let frames: u32 = args[2].parse()?;
    let (cpu, devices) = load(&file)?;
    let mut bus = (!devices.is_empty())
        .then(|| Bus::start(&args[3], &cpu, &file, &devices));
    let mut m = Machine::new(cpu);
    while m.running() && m.frame < frames {
        if let Some(bus) = &mut bus {
            m.budget -= bus.begin(m.frame);
        }
        m.run_frame(|cpu, budget, slot, function| {
            let Some(bus) = &mut bus else {
                return (u32::MAX, 4);
            };
            bus.call(cpu, budget, slot, function)
        });
        if let Some(bus) = &mut bus {
            bus.end(m.frame, !m.running());
        }
    }
    let (grants, terminal) = match bus {
        Some(mut bus) => {
            let terminal = bus.state(2);
            let grants = std::mem::take(&mut bus.grants);
            bus.close();
            (grants, Some(terminal))
        }
        None => (Vec::new(), None),
    };
    let id = blake3::hash(&file);
    let terminal = terminal.as_deref();
    let state = m.state(id.as_bytes(), &grants, terminal);
    println!("{}", blake3::hash(&state));
    match m.status {
        Status::Faulted(fault) => {
            eprintln!("{fault}");
            exit(1)
        }
        Status::Exited(code) => exit(code as i32),
        Status::Running => Ok(()),
    }
}

It starts the driver only for a program that lists devices, and prints the hash after the last frame.

Check it

From examples/host/rust, after cargo build --release, with step 1's exit.terse:

target/release/step4 exit.terse 0
target/release/step4 exit.terse 1

prints the hash at reset, then after the frame in which it exits:

9cbfa0da982561dd1c5dbaf1d5fde2121dee78c097d754aa0c2a350584bbeb5a
3272a879392d8179997dc398726430bf92bbd413b89653be8c9af4472656fe9b

the two STATE.md section 3 gives. And hello after 30 frames:

target/release/step4 ../../../programs/hello/hello.terse 30 \
    ../../../target/release/terse-dev-terminal
819432152b38626f8fc54b43f50d5d4c501dc99e6904315b61dc78b796c611e2

which is what terse run programs/hello/hello.terse --frames 30 --hash prints. A program that faults must agree too: native/core-c/tests has one for each kind of fault, and the sources' tests compare their hashes with the reference's.

Random programs find what the tests do not. native/core-c/tests/fuzz.py writes them: random 16-bit and 32-bit encodings, many of them faulting. This prints the name of any whose hash after 3 frames is not the reference's, and with this host prints nothing:

python3 ../../../native/core-c/tests/fuzz.py fuzz 200
for f in fuzz/*.terse; do
    a=$(target/release/step4 $f 3 2>/dev/null)
    b=$(terse run $f --frames 3 --hash 2>/dev/null)
    [ "$a" = "$b" ] || echo $f
done

What is left out

This host runs hello and proves it, nothing more. The rest of a complete host, in the order to add it:

tcore (native/core-c) has all of it but snapshots in about 1,580 lines of C; crates/terse-core is the reference.

What you have now

A host that runs Terse32 programs exactly as the reference does, and proves it: state.rs, 46 lines, bin/step4.rs, 50; 940 lines in all. Next, write a device as a separate program: Make a device.