nx_module_cas_test.nx source
↩ module page · 75 lines · 2270 B
1// nx_module_cas_test.nx -- smoke: hash a tiny module, verify Merkle root.
2
3import "nx_syscalls.nx"
4import "nx_tier.nx"
5import "nx_sha256.nx"
6import "nx_module_cas.nx"
7
8func main() -> nx_int {
9 // Build a manifest for module name "hello", source "func main(){}",
10 // zero imports. Allocate name/source/merkle hash buffers.
11
12 let name_buf: *u8 = (sys_mmap(8)) as *u8
13 name_buf[0] = 104 // h
14 name_buf[1] = 101 // e
15 name_buf[2] = 108 // l
16 name_buf[3] = 108 // l
17 name_buf[4] = 111 // o
18 let src_buf: *u8 = (sys_mmap(16)) as *u8
19 src_buf[0] = 102 // f
20 src_buf[1] = 117 // u
21 src_buf[2] = 110 // n
22 src_buf[3] = 99 // c
23 src_buf[4] = 32 // space
24 src_buf[5] = 109 // m
25 src_buf[6] = 97 // a
26 src_buf[7] = 105 // i
27 src_buf[8] = 110 // n
28 src_buf[9] = 40 // (
29 src_buf[10] = 41 // )
30 src_buf[11] = 123 // {
31 src_buf[12] = 125 // }
32
33 let nh: *u8 = (sys_mmap(32)) as *u8
34 let sh: *u8 = (sys_mmap(32)) as *u8
35 let rh: *u8 = (sys_mmap(32)) as *u8
36
37 let m: *ModuleManifest = (sys_mmap(NX_SIZEOF_NX_INT * 10)) as *ModuleManifest
38 m.name_bytes = name_buf
39 m.name_len = 5
40 m.source_bytes = src_buf
41 m.source_len = 13
42 m.import_root_hashes = (sys_mmap(1)) as *u8
43 m.n_imports = 0
44 m.name_hash = nh
45 m.source_hash = sh
46 m.merkle_root = rh
47
48 nx_module_cas_compute_root(m)
49
50 // Recompute root twice; bytes must match (determinism axis).
51 let rh2: *u8 = (sys_mmap(32)) as *u8
52 m.merkle_root = rh2
53 nx_module_cas_compute_root(m)
54
55 var i: nx_int = 0
56 while i < 32 {
57 if rh[i] != rh2[i] { return 1 } // determinism violation
58 i = i + 1
59 }
60
61 // First byte should not be zero (statistically; sha256 of any non-
62 // empty input has ~1/256 chance of leading zero, but our specific
63 // input "hello" / 5 / "func main(){}" / 13 should not collide).
64 if rh[0] == 0 {
65 if rh[1] == 0 { return 2 }
66 }
67
68 // Sealed-enum validity gate.
69 if nx_module_integrity_verdict_is_valid(NX_MODULE_INTEGRITY_VERIFIED) != 1 {
70 return 3
71 }
72 if nx_module_integrity_verdict_is_valid(99) != 0 { return 4 }
73
74 return 0
75}