code wiki / _hdl_build / nx_pub_receipt_keys.nx
nx_pub_receipt_keys.nx source
↩ module page · 43 lines · 2835 B
1// nx_pub_receipt_keys.nx -- the publisher's STABLE receipt-signing IDENTITY (makes the receipt non-repudiation REAL,
2// not a per-run demo). For an Ed25519-signed receipt to MEAN anything, the publisher must have ONE durable signing
3// keypair whose PUBLIC key is published + discoverable, so ANY submitter can verify a receipt across runs without
4// trusting the issuer. Generate-once (idempotent, #10): if the private seed exists, load it; else CSPRNG-generate it,
5// persist it 0600 (crown jewel, never logged/leaked), derive the public key, and PUBLISH the public key as hex.
6// priv = 32 raw bytes (the Ed25519 seed) at privpath, mode 0600 ; pub = 64 hex at pubpath, world-readable.
7import "nx_csprng.nx" // nx_csprng_fill
8import "nx_ed25519_signature.nx" // ed25519_pub_from_priv
9import "nx_syscalls.nx"
10
11func prk_hexenc(inp: *u8, n: i64, out: *u8) -> i64 { let hx: *u8="0123456789abcdef" as *u8; var i: i64=0; while i<n { out[i*2]=hx[((inp[i] as i64)>>4)&15]; out[i*2+1]=hx[(inp[i] as i64)&15]; i=i+1 } out[n*2]=0 as u8; return n*2 }
12func prk_unhex1(c: i64) -> i64 { if c>=48 { if c<=57 {return c-48} } if c>=97 { if c<=102 {return c-87} } if c>=65 { if c<=70 {return c-55} } return 0 }
13func prk_unhex(inp: *u8, n: i64, out: *u8) -> i64 { var i: i64=0; while i<n { out[i]=((prk_unhex1(inp[i*2] as i64)<<4)|prk_unhex1(inp[i*2+1] as i64)) as u8; i=i+1 } return n }
14
15// load-or-init the publisher's receipt keypair. writes the 32-byte priv to out_priv32 + the 32-byte pub to out_pub32.
16// returns 1 (loaded existing) or 2 (generated fresh).
17func prk_load_or_init(privpath: *u8, pubpath: *u8, out_priv32: *u8, out_pub32: *u8) -> i64 {
18 let lp: *i64=sys_mmap(8) as *i64; lp[0]=0
19 let d: *u8=sys_read_file(privpath, lp)
20 var generated: i64 = 0
21 if (d as i64)!=0 { if lp[0]>=32 { var i: i64=0; while i<32 { out_priv32[i]=d[i]; i=i+1 } } else { generated=1 } } else { generated=1 }
22 if generated==1 {
23 nx_csprng_fill(out_priv32, 32)
24 let fd: i64=sys_openat_wr(privpath, 0x180) // 0600 -- private seed, owner-only
25 if fd>=0 { sys_write(fd, out_priv32, 32); sys_close(fd) }
26 }
27 ed25519_pub_from_priv(out_priv32, out_pub32)
28 let hexb: *u8=sys_mmap(72); prk_hexenc(out_pub32, 32, hexb)
29 let pfd: i64=sys_openat_wr(pubpath, 0x1a4) // 0644 -- the published, world-readable pubkey
30 if pfd>=0 { sys_write(pfd, hexb, 64); sys_close(pfd) }
31 if generated==1 { return 2 }
32 return 1
33}
34
35// load the PUBLISHED public key (64 hex) into out_pub32 -- what a submitter uses to verify a receipt. 1 ok, 0 missing.
36func prk_pub_load(pubpath: *u8, out_pub32: *u8) -> i64 {
37 let lp: *i64=sys_mmap(8) as *i64; lp[0]=0
38 let d: *u8=sys_read_file(pubpath, lp)
39 if (d as i64)==0 { return 0 }
40 if lp[0] < 64 { return 0 }
41 prk_unhex(d, 32, out_pub32)
42 return 1
43}