code wiki / _hdl_build / nx_tamper_lit.nx
nx_tamper_lit.nx source
↩ module page · 70 lines · 2552 B
1// nx_tamper_lit.nx -- TAMPER_PROOF organ (mainless module): deterministically
2// corrupt the Nth long decimal literal in a source file, in place. Used by the
3// math rung-runner to make the honesty proof MECHANICAL: tamper -> gate must go
4// RED -> regenerate from the emitter -> gate must return GREEN.
5//
6// "Long literal" = a run of >= 17 decimal digits (f64 raw constants are 18-19
7// digits; nothing else in kernel sources is that long; hex literals are 0x..
8// and never qualify). The flip targets the MIDDLE digit of the run: that is a
9// ~2^-32 RELATIVE change to the constant -- a guaranteed multi-thousand-ulp
10// defect on a load-bearing constant (the weak-tamper lesson: a LAST-digit flip
11// is sub-ulp and the gate honestly stays GREEN). Which literal is load-bearing
12// is per-kernel knowledge: the caller passes skip (0 = first long run) from the
13// rung table (e.g. sincos/sinhcosh skip their quantization-only 2/pi / 1/ln2
14// rows, whose corruption only matters within 2^-23 of rounding boundaries).
15// license_tier: ORIGINAL
16
17import "nx_syscalls.nx"
18const K_MAGIC_524288: i64 = 524288
19const K_MAGIC_524287: i64 = 524287
20
21// flip middle digit of the (skip+1)-th >=17-digit run in path; 1 = done, 0 = fail
22func tl_flip(path: *u8, skip: i64) -> i64 {
23 let buf: *u8 = sys_mmap(K_MAGIC_524288)
24 let fd: i64 = sys_openat_rd(path)
25 if fd < 0 { return 0 }
26 var n: i64 = 0
27 var r: i64 = sys_read(fd, buf, K_MAGIC_524287)
28 while r > 0 {
29 n = n + r
30 r = sys_read(fd, buf + n, K_MAGIC_524287 - n)
31 }
32 sys_close(fd)
33 if n <= 0 { return 0 }
34 var i: i64 = 0
35 var run: i64 = 0
36 var left: i64 = skip
37 var target: i64 = 0 - 1
38 while i <= n {
39 var isd: i64 = 0
40 if i < n {
41 if buf[i] >= (48 as u8) { if buf[i] <= (57 as u8) { isd = 1 } }
42 }
43 if isd == 1 {
44 run = run + 1
45 } else {
46 if run >= 17 {
47 if left == 0 {
48 if target < 0 { target = i - run + (run / 2) }
49 }
50 left = left - 1
51 }
52 run = 0
53 }
54 i = i + 1
55 }
56 if target < 0 { return 0 }
57 var d: i64 = buf[target] as i64
58 if d >= 57 { d = 48 } else { d = d + 1 }
59 buf[target] = d as u8
60 let wf: i64 = sys_openat_wr(path, 0x1a4)
61 if wf < 0 { return 0 }
62 var off: i64 = 0
63 while off < n {
64 let w: i64 = sys_write(wf, buf + off, n - off)
65 if w <= 0 { sys_close(wf); return 0 }
66 off = off + w
67 }
68 sys_close(wf)
69 return 1
70}