Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omega-mv/blob/main/tools/trit/proof/TritSignal.lean # omega-mv Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance. Brought by drakestapleton Sign in to star 1 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `omega-mv / tools / trit / proof / TritSignal.lean` 730 lines · 31522 bytes Raw Blame History 1 /- 2 T-002 trit signal: the classifier of tools/trit/trit.om, proved in Lean 4 core. 3 Part 1 (TritSignal) is the abstract lane/cursor model; part 2 (TritBin, at the end) mirrors trit.om 4 function by function and is run against trit.bin by difftest.sh. 5 (no Mathlib; every theorem closed, axioms printed below). 6 Check: lean TritSignal.lean (exit 0, no output besides the `#print axioms` lines) 7 8 Model. A lane's unread complete content lines are a list; each line has an `isStop` flag. 9 `classify` is the normal-lane trit. `St` holds the pending admitted emergency lines and the 10 unread normal lines; `stepE` applies one arrival or one ack, as `trit DIR --ack BOT` does. 11 -/ 12 namespace TritSignal 13 14 inductive Trit where 15 | zero | one | two 16 deriving DecidableEq, Repr 17 18 def Trit.rank : Trit → Nat 19 | .zero => 0 20 | .one => 1 21 | .two => 2 22 23 /-- The program's `tmax`: keep `a` when it ranks at least as high as `b`. -/ 24 def Trit.max (a b : Trit) : Trit := if b.rank ≤ a.rank then a else b 25 26 theorem rank_lt_three (t : Trit) : t.rank < 3 := by cases t <;> decide 27 theorem rank_inj (a b : Trit) : a.rank = b.rank → a = b := by cases a <;> cases b <;> decide 28 theorem max_zero (t : Trit) : t.max .zero = t := by cases t <;> rfl 29 theorem zero_max (t : Trit) : Trit.zero.max t = t := by cases t <;> rfl 30 theorem max_two (t : Trit) : t.max .two = .two := by cases t <;> rfl 31 theorem two_max (t : Trit) : Trit.two.max t = .two := by cases t <;> rfl 32 theorem max_assoc (a b c : Trit) : (a.max b).max c = a.max (b.max c) := by 33 cases a <;> cases b <;> cases c <;> rfl 34 theorem max_comm (a b : Trit) : a.max b = b.max a := by cases a <;> cases b <;> rfl 35 theorem rank_max (a b : Trit) : (a.max b).rank = Nat.max a.rank b.rank := by 36 cases a <;> cases b <;> rfl 37 38 structure Line where 39 isStop : Bool 40 deriving DecidableEq 41 42 theorem max_eq_two (a b : Trit) : a.max b = .two ↔ a = .two ∨ b = .two := by 43 cases a <;> cases b <;> decide 44 theorem max_eq_zero (a b : Trit) : a.max b = .zero ↔ a = .zero ∧ b = .zero := by 45 cases a <;> cases b <;> decide 46 47 /-- The trit one line contributes on its own. -/ 48 def lineTrit (l : Line) : Trit := if l.isStop then .two else .one 49 50 /-- The normal-lane classifier: the maximum of the line trits, 0 for no lines. -/ 51 def classify : List Line → Trit 52 | [] => .zero 53 | l :: ls => (lineTrit l).max (classify ls) 54 55 /-- Totality: `classify` is a structurally recursive (so total) function into exactly three 56 values. -/ 57 theorem classify_total (ls : List Line) : 58 classify ls = .zero ∨ classify ls = .one ∨ classify ls = .two := by 59 cases classify ls <;> simp 60 61 theorem classify_two_iff (ls : List Line) : 62 classify ls = .two ↔ ∃ l ∈ ls, l.isStop = true := by 63 induction ls with 64 | nil => simp [classify] 65 | cons l ls ih => 66 cases h : l.isStop <;> simp [classify, lineTrit, h, max_eq_two, ih] 67 68 theorem classify_zero_iff (ls : List Line) : classify ls = .zero ↔ ls = [] := by 69 cases ls with 70 | nil => simp [classify] 71 | cons l t => cases h : l.isStop <;> simp [classify, lineTrit, h, max_eq_zero] 72 73 /-- 2 dominates 1 dominates 0: the trit of two batches of lines is the maximum of their trits. -/ 74 theorem classify_append (a b : List Line) : 75 classify (a ++ b) = (classify a).max (classify b) := by 76 induction a with 77 | nil => simp [classify, zero_max] 78 | cons l a ih => simp only [List.cons_append, classify, ih, max_assoc] 79 80 theorem classify_one_iff (ls : List Line) : 81 classify ls = .one ↔ ls ≠ [] ∧ ∀ l ∈ ls, l.isStop = false := by 82 have h2 := classify_two_iff ls 83 have h0 := classify_zero_iff ls 84 constructor 85 · intro h 86 refine ⟨(fun e => by rw [h0.2 e] at h; cases h), fun l hl => ?_⟩ 87 cases hs : l.isStop 88 · rfl 89 · have := h2.2 ⟨l, hl, hs⟩; rw [h] at this; cases this 90 · intro hh 91 obtain ⟨hne, hall⟩ := hh 92 rcases classify_total ls with h | h | h 93 · exact absurd (h0.1 h) hne 94 · exact h 95 · obtain ⟨l, hl, hs⟩ := h2.1 h; rw [hall l hl] at hs; cases hs 96 97 theorem stop_dominates (ls : List Line) (h : ∃ l ∈ ls, l.isStop = true) : 98 classify ls = .two := (classify_two_iff ls).2 h 99 100 theorem unread_beats_zero (ls : List Line) (h : ls ≠ []) : classify ls ≠ .zero := 101 fun e => h ((classify_zero_iff ls).1 e) 102 103 theorem more_lines_never_lower (a b : List Line) : 104 (classify a).rank ≤ (classify (a ++ b)).rank := by 105 rw [classify_append, rank_max]; exact Nat.le_max_left _ _ 106 107 /-- The program's loop (`scann`): a stop line gives 2 at once, any other line raises to 1. -/ 108 def stepN (t : Trit) (l : Line) : Trit := if l.isStop then .two else t.max .one 109 110 theorem stepN_eq (t : Trit) (l : Line) : stepN t l = t.max (classify [l]) := by 111 cases l with | mk s => cases s <;> cases t <;> rfl 112 113 theorem fold_eq_gen (ls : List Line) (t : Trit) : 114 ls.foldl stepN t = t.max (classify ls) := by 115 induction ls generalizing t with 116 | nil => simp [classify, max_zero] 117 | cons l ls ih => 118 rw [List.foldl_cons, ih, stepN_eq, max_assoc, ← classify_append]; rfl 119 120 theorem scan_correct (ls : List Line) : ls.foldl stepN .zero = classify ls := by 121 rw [fold_eq_gen, zero_max] 122 123 /-! Lanes, cursors and token acks. 124 125 Each lane is an append-only list of complete content lines with a cursor `c` (lines read). The 126 emergency lane holds admitted lines only. A reader is told a token: the lane's length when it read. 127 `ack k` moves the cursor to `k` only when `c ≤ k ≤ length` (the program also checks that the line 128 before `k` hashes to the token, which in this append-only model always holds); otherwise it is 129 refused and nothing changes. -/ 130 131 structure St where 132 e : List Line 133 ec : Nat 134 n : List Line 135 nc : Nat 136 137 /-- The program's `state`: a pending emergency gives 2 and the normal lane is not read. -/ 138 def St.trit (s : St) : Trit := if s.ec < s.e.length then .two else classify (s.n.drop s.nc) 139 140 inductive Ev where 141 | normal (l : Line) 142 | emerg (l : Line) 143 | ackN (k : Nat) 144 | ackE (k : Nat) 145 146 def Ev.isAckE : Ev → Bool 147 | .ackE _ => true 148 | _ => false 149 150 def ackTo (c k len : Nat) : Nat := if c ≤ k ∧ k ≤ len then k else c 151 152 def stepE (s : St) : Ev → St 153 | .normal l => { s with n := s.n ++ [l] } 154 | .emerg l => { s with e := s.e ++ [l] } 155 | .ackN k => { s with nc := ackTo s.nc k s.n.length } 156 | .ackE k => { s with ec := ackTo s.ec k s.e.length } 157 158 def run (s : St) (es : List Ev) : St := es.foldl stepE s 159 160 theorem ackTo_ge (c k len : Nat) : c ≤ ackTo c k len := by 161 unfold ackTo; split <;> omega 162 163 theorem ackTo_le (c k len : Nat) (h : c ≤ len) : ackTo c k len ≤ len := by 164 unfold ackTo; split <;> omega 165 166 /-- Cursors never move backward: a stale token cannot un-read anything. -/ 167 theorem cursors_monotone (s : St) (ev : Ev) : 168 s.nc ≤ (stepE s ev).nc ∧ s.ec ≤ (stepE s ev).ec := by 169 cases ev with 170 | normal l => exact ⟨Nat.le_refl _, Nat.le_refl _⟩ 171 | emerg l => exact ⟨Nat.le_refl _, Nat.le_refl _⟩ 172 | ackN k => exact ⟨ackTo_ge _ _ _, Nat.le_refl _⟩ 173 | ackE k => exact ⟨Nat.le_refl _, ackTo_ge _ _ _⟩ 174 175 /-- A refused ack (stale, behind the cursor, or past the end) changes nothing. -/ 176 theorem refused_ack_unchanged (s : St) (k : Nat) (hk : k < s.nc ∨ s.n.length < k) : 177 stepE s (.ackN k) = s := by 178 have h : ¬ (s.nc ≤ k ∧ k ≤ s.n.length) := by omega 179 simp [stepE, ackTo, h] 180 181 /-- The ack race: lines that arrive after the read stay unread after acking the read's token. -/ 182 theorem ack_race (s : St) (ls : List Line) (hv : s.nc ≤ s.n.length) : 183 ((stepE { s with n := s.n ++ ls } (.ackN s.n.length)).n).drop 184 (stepE { s with n := s.n ++ ls } (.ackN s.n.length)).nc = ls := by 185 have h : s.nc ≤ s.n.length ∧ s.n.length ≤ (s.n ++ ls).length := by 186 simp only [List.length_append]; omega 187 simp only [stepE, ackTo, h] 188 exact List.drop_left .. 189 190 theorem pending_is_two (s : St) (h : s.ec < s.e.length) : s.trit = .two := by 191 simp [St.trit, h] 192 193 theorem run_noE (s : St) (es : List Ev) (h : ∀ ev ∈ es, ev.isAckE = false) : 194 (run s es).ec = s.ec ∧ s.e.length ≤ (run s es).e.length := by 195 induction es generalizing s with 196 | nil => exact ⟨rfl, Nat.le_refl _⟩ 197 | cons ev es ih => 198 have hr : ∀ x ∈ es, x.isAckE = false := fun x hx => h x (List.mem_cons_of_mem ev hx) 199 have he := h ev (List.mem_cons_self ..) 200 obtain ⟨h1, h2⟩ := ih (stepE s ev) hr 201 show (run (stepE s ev) es).ec = s.ec ∧ s.e.length ≤ (run (stepE s ev) es).e.length 202 cases ev with 203 | normal l => exact ⟨h1, h2⟩ 204 | emerg l => 205 refine ⟨h1, Nat.le_trans ?_ h2⟩ 206 show s.e.length ≤ (s.e ++ [l]).length 207 simp 208 | ackN k => exact ⟨h1, h2⟩ 209 | ackE k => simp [Ev.isAckE] at he 210 211 theorem emerg_arrival (s : St) (es : List Ev) (hv : s.ec ≤ s.e.length) 212 (h : ∀ ev ∈ es, ev.isAckE = false) (hm : ∃ l, Ev.emerg l ∈ es) : 213 (run s es).ec < (run s es).e.length := by 214 induction es generalizing s with 215 | nil => obtain ⟨l, hl⟩ := hm; simp at hl 216 | cons ev es ih => 217 have hr : ∀ x ∈ es, x.isAckE = false := fun x hx => h x (List.mem_cons_of_mem ev hx) 218 have he := h ev (List.mem_cons_self ..) 219 show (run (stepE s ev) es).ec < (run (stepE s ev) es).e.length 220 have tail : (∃ l, Ev.emerg l ∈ es) → (stepE s ev).ec ≤ (stepE s ev).e.length → 221 (run (stepE s ev) es).ec < (run (stepE s ev) es).e.length := 222 fun hm' hv' => ih (stepE s ev) hv' hr hm' 223 cases ev with 224 | emerg l => 225 obtain ⟨h1, h2⟩ := run_noE (stepE s (.emerg l)) es hr 226 rw [h1] 227 refine Nat.lt_of_lt_of_le ?_ h2 228 show s.ec < (s.e ++ [l]).length 229 simp; omega 230 | normal l => 231 obtain ⟨l', hl'⟩ := hm 232 have : Ev.emerg l' ∈ es := by 233 cases hl' with 234 | tail _ h2 => exact h2 235 exact tail ⟨l', this⟩ hv 236 | ackN k => 237 obtain ⟨l', hl'⟩ := hm 238 have : Ev.emerg l' ∈ es := by 239 cases hl' with 240 | tail _ h2 => exact h2 241 exact tail ⟨l', this⟩ hv 242 | ackE k => simp [Ev.isAckE] at he 243 244 /-- Never starved: under any interleaving of normal arrivals, emergency arrivals and normal-lane 245 acks, a pending emergency, or one that arrives at any point, is classified 2 until the 246 emergency lane itself is acked. -/ 247 theorem never_starved (s : St) (es : List Ev) (hv : s.ec ≤ s.e.length) 248 (h : ∀ ev ∈ es, ev.isAckE = false) 249 (hp : s.ec < s.e.length ∨ ∃ l, Ev.emerg l ∈ es) : (run s es).trit = .two := by 250 apply pending_is_two 251 cases hp with 252 | inl h0 => 253 obtain ⟨h1, h2⟩ := run_noE s es h 254 rw [h1]; exact Nat.lt_of_lt_of_le h0 h2 255 | inr hm => exact emerg_arrival s es hv h hm 256 257 /-- Acking the emergency lane at its read token clears it; normal lines are then classified. -/ 258 theorem emerg_ack_clears (s : St) (hv : s.ec ≤ s.e.length) : 259 (stepE s (.ackE s.e.length)).trit = classify (s.n.drop s.nc) := by 260 have h : s.ec ≤ s.e.length ∧ s.e.length ≤ s.e.length := ⟨hv, Nat.le_refl _⟩ 261 simp [stepE, ackTo, h, St.trit] 262 263 end TritSignal 264 265 /-! ## TritBin: the shipped classifier, line for line (tools/trit/trit.om) 266 267 Bytes are read as characters (the inbox files are ASCII). Each definition names the .om function 268 it mirrors. `proof/difftest.sh` runs this model (`#eval` in Diff.lean) and trit.bin on the same 269 generated fixture directories and requires identical stdout, stderr and exit status. The SHA-256 270 tables below are the seeded ones (seed/trace/sha256.om kinit/hinit), copied by difftest.sh. -/ 271 272 namespace TritBin 273 open TritSignal 274 275 def isDig (c : Char) : Bool := '0' ≤ c && c ≤ '9' 276 /-- okch -/ 277 def okch (c : Char) : Bool := isDig c || c == '-' || ('a' ≤ c && c ≤ 'z') 278 279 /-- lnend/the scan loops: complete lines (start offset, bytes without the newline); a trailing 280 partial line is dropped. -/ 281 def lines : Nat → List Char → Nat → List (Nat × List Char) 282 | 0, _, _ => [] 283 | fuel + 1, s, pos => 284 match s.idxOf? '\n' with 285 | none => [] 286 | some i => (pos, s.take i) :: lines fuel (s.drop (i + 1)) (pos + i + 1) 287 288 def linesOf (s : List Char) : List (Nat × List Char) := lines (s.length + 1) s 0 289 290 /-- ists -/ 291 def ists (l : List Char) : Bool := 292 decide (11 ≤ l.length) && (List.range 11).all fun i => 293 let c := l.getD i ' ' 294 if i == 4 || i == 7 then c == '-' else if i == 10 then c == 'T' else isDig c 295 296 def fields (l : List Char) : List String := (String.ofList l).splitOn "|" 297 298 /-- lfmt: a last field starting "ocb2:" or leftover "ocb1:" is the codebook signature, not content; 299 then the tag is field 3 in the 6-field format, else field 2. -/ 300 def lfmt (l : List Char) : List String × Nat := 301 let fs := fields l 302 let n := fs.length 303 let last := fs.getD (n - 1) "" 304 let fs' := if 2 ≤ n && (last.startsWith "ocb2:" || last.startsWith "ocb1:") then fs.take (n - 1) else fs 305 (fs', if fs'.length == 6 then 3 else 2) 306 307 /-- stopx: exact STOP -/ 308 def stopx (t : String) : Bool := 309 let c := t.toList 310 c.take 4 == ['S', 'T', 'O', 'P'] && (c.length == 4 || c.getD 4 ' ' == ' ' || c.getD 4 ' ' == ':') 311 312 /-- lnkind: stop wins over fyi. -/ 313 def lnkind (l : List Char) : Trit := 314 let (fs, tg) := lfmt l 315 if fs[tg]? == some "stop" then .two 316 else if (fs[tg + 1]?.map stopx).getD false then .two 317 else if fs[tg]? == some "fyi" then .zero 318 else .one 319 320 /-- okname -/ 321 def okname (allow : List String) (s : String) : Bool := 322 decide (1 ≤ s.length) && decide (s.length ≤ 64) && s.toList.all okch && 323 (s == "drake" || allow.contains s) 324 325 def dig2 (l : List Char) (q : Nat) : Nat := 326 let a := l.getD q ' ' 327 let b := l.getD (q + 1) ' ' 328 if isDig a && isDig b then (a.toNat - 48) * 10 + (b.toNat - 48) else 100000 329 330 /-- days (civil to days, as in the .om) -/ 331 def days (y m d : Nat) : Nat := 332 let yy := if m ≤ 2 then y - 1 else y 333 let era := yy / 400 334 let yoe := yy - era * 400 335 let mp := if 2 < m then m - 3 else m + 9 336 let doy := (153 * mp + 2) / 5 + (d - 1) 337 let doe := yoe * 365 + yoe / 4 + doy - yoe / 100 338 era * 146097 + doe 339 340 /-- minute: 0 when the timestamp does not parse -/ 341 def minute (l : List Char) : Nat := 342 if l.length < 16 then 0 else 343 if l.getD 13 ' ' != ':' then 0 else 344 let y := dig2 l 0 * 100 + dig2 l 2 345 let mo := dig2 l 5 346 let d := dig2 l 8 347 let hh := dig2 l 11 348 let mi := dig2 l 14 349 if mo < 1 || 12 < mo then 0 else 350 if d < 1 || 31 < d then 0 else 351 if 23 < hh || 59 < mi then 0 else 352 if y < 1 then 0 else 353 days y mo d * 1440 + hh * 60 + (mi + 1) 354 355 def absd (a b : Nat) : Nat := if b < a then a - b else b - a 356 357 /-! SHA-256 and HMAC-SHA256, from the seeded constants (codebook.om hmb/hmac/mkk0). -/ 358 def kTab : Array UInt32 := #[`1116352408`, `1899447441`, `3049323471`, `3921009573`, `961987163`, `1508970993`, `2453635748`, `2870763221`, `3624381080`, `310598401`, `607225278`, `1426881987`, `1925078388`, `2162078206`, `2614888103`, `3248222580`, `3835390401`, `4022224774`, `264347078`, `604807628`, `770255983`, `1249150122`, `1555081692`, `1996064986`, `2554220882`, `2821834349`, `2952996808`, `3210313671`, `3336571891`, `3584528711`, `113926993`, `338241895`, `666307205`, `773529912`, `1294757372`, `1396182291`, `1695183700`, `1986661051`, `2177026350`, `2456956037`, `2730485921`, `2820302411`, `3259730800`, `3345764771`, `3516065817`, `3600352804`, `4094571909`, `275423344`, `430227734`, `506948616`, `659060556`, `883997877`, `958139571`, `1322822218`, `1537002063`, `1747873779`, `1955562222`, `2024104815`, `2227730452`, `2361852424`, `2428436474`, `2756734187`, `3204031479`, `3329325298`] 359 def hInit : Array UInt32 := #[`1779033703`, `3144134277`, `1013904242`, `2773480762`, `1359893119`, `2600822924`, `528734635`, `1541459225`] 360 def rotr (x n : UInt32) : UInt32 := (x >>> n) ||| (x <<< (32 - n)) 361 362 def compress (hs : Array UInt32) (m : Array UInt8) (o : Nat) : Array UInt32 := Id.run do 363 let mut w : Array UInt32 := #[] 364 for i in [0:16] do 365 let by_ (j : Nat) : UInt32 := (m[o + 4 * i + j]!).toUInt32 366 w := w.push ((by_ 0 <<< 24) ||| (by_ 1 <<< 16) ||| (by_ 2 <<< 8) ||| by_ 3) 367 for i in [16:64] do 368 let x := w[i - 15]! 369 let y := w[i - 2]! 370 let s0 := rotr x 7 ^^^ rotr x 18 ^^^ (x >>> 3) 371 let s1 := rotr y 17 ^^^ rotr y 19 ^^^ (y >>> 10) 372 w := w.push (w[i - 16]! + s0 + w[i - 7]! + s1) 373 let mut a := hs[0]! 374 let mut b := hs[1]! 375 let mut c := hs[2]! 376 let mut d := hs[3]! 377 let mut e := hs[4]! 378 let mut f := hs[5]! 379 let mut g := hs[6]! 380 let mut h := hs[7]! 381 for i in [0:64] do 382 let t1 := h + (rotr e 6 ^^^ rotr e 11 ^^^ rotr e 25) + ((e &&& f) ^^^ ((~~~e) &&& g)) + kTab[i]! + w[i]! 383 let t2 := (rotr a 2 ^^^ rotr a 13 ^^^ rotr a 22) + ((a &&& b) ^^^ (a &&& c) ^^^ (b &&& c)) 384 h := g; g := f; f := e; e := d + t1; d := c; c := b; b := a; a := t1 + t2 385 return #[hs[0]! + a, hs[1]! + b, hs[2]! + c, hs[3]! + d, hs[4]! + e, hs[5]! + f, hs[6]! + g, hs[7]! + h] 386 387 def hex8 (x : UInt32) : String := 388 let s := String.ofList (Nat.toDigits 16 x.toNat) 389 String.ofList (List.replicate (8 - s.length) '0') ++ s 390 391 def shaW (bs : List UInt8) : Array UInt32 := Id.run do 392 let bytes : Array UInt8 := bs.toArray 393 let len := bytes.size 394 let k := (64 - (len + 9) % 64) % 64 395 let mut m := bytes.push 0x80 396 for _ in [0:k] do m := m.push 0 397 let bits := len * 8 398 for i in [0:8] do m := m.push ((bits >>> (8 * (7 - i))) % 256).toUInt8 399 let mut hs := hInit 400 for blk in [0:m.size / 64] do hs := compress hs m (64 * blk) 401 return hs 402 403 def toB (msg : List Char) : List UInt8 := msg.map fun ch => ch.toNat.toUInt8 404 def sha256 (msg : List Char) : String := String.join ((shaW (toB msg)).toList.map hex8) 405 def shaB (bs : List UInt8) : List UInt8 := 406 (shaW bs).toList.flatMap fun (w : UInt32) => [(w >>> 24).toUInt8, (w >>> 16).toUInt8, (w >>> 8).toUInt8, w.toUInt8] 407 def hexB (bs : List UInt8) : String := String.join (bs.map fun b => 408 let s := String.ofList (Nat.toDigits 16 b.toNat) 409 if s.length < 2 then "0" ++ s else s) 410 def k0 (key : List UInt8) : List UInt8 := 411 let k := if 64 < key.length then shaB key else key 412 k ++ List.replicate (64 - k.length) 0 413 def hmacHex (key msg : List UInt8) : String := 414 let kz := k0 key 415 hexB (shaB (kz.map (· ^^^ 0x5c) ++ shaB (kz.map (· ^^^ 0x36) ++ msg))) 416 417 /-! The codebook verify (codebook.om verl..verl4), as trit runs it: quiet, counters in a table. -/ 418 structure VC where 419 cs : String 420 codes : List String 421 key : List UInt8 422 423 def BIG : Nat := `9223372036854775807` 424 def isHex (c : Char) : Bool := isDig c || ('a' ≤ c && c ≤ 'f') 425 def numOf (c : List Char) : Nat := c.foldl (fun a ch => a * 10 + (ch.toNat - 48)) 0 426 427 /-- ctrval: 1..18 digits, no leading zero, else 0. -/ 428 def ctrval (t : String) : Nat := 429 let c := t.toList 430 if c.length == 0 || 18 < c.length || c.head? == some '0' || !c.all isDig then 0 else numOf c 431 432 /-- decl + the code split: each code ends at the first group below 900; a dangling escape drops. -/ 433 def codesOf : List Char → List Char → List (List Char) 434 | a :: b :: c :: rest, cur => 435 if numOf [a, b, c] < 900 then (cur ++ [a, b, c]) :: codesOf rest [] else codesOf rest (cur ++ [a, b, c]) 436 | _, _ => [] 437 438 /-- tsok: YYYY-MM-DDTHH:MM, 16 bytes (codebook.om ntsok / tsok). -/ 439 def tsok (ts : String) : Bool := 440 let c := ts.toList 441 decide (c.length = 16) && (List.range 16).all fun i => 442 let ch := c.getD i ' ' 443 if i == 4 || i == 7 then ch == '-' 444 else if i == 10 then ch == 'T' 445 else if i == 13 then ch == ':' 446 else isDig ch 447 448 /-- verifyM: some (sender, counter, ts, has a 3xx) exactly when format, codebook id, codes and MAC 449 all check (every refusal before `stale` / `badto` in codebook.om's order). Lane is bound in the MAC. -/ 450 def verifyM (vc : VC) (lane : Char) (l : List Char) : Option (String × Nat × String × Bool) := 451 let (body, _) := lfmt l 452 if body.length != 6 then none else 453 if !tsok (body.getD 0 "") then none else 454 let fs := fields l 455 if fs.length < 2 then none else 456 let lf := fs.getD (fs.length - 1) "" 457 if lf.length < 5 then none else 458 let ps := lf.splitOn ":" 459 if ps.getD 0 "" != "ocb2" || ps.length < 5 || ps.getD 4 "" == "" then none else 460 let s := body.getD 1 "" 461 if s.length == 0 || 64 < s.length || !s.toList.all okch then none else 462 if ps.length != 5 then none else 463 let mac := ps.getD 4 "" 464 if mac.length != 64 || !mac.toList.all isHex then none else 465 if (ps.getD 1 "").length != 64 then none else 466 let ct := ps.getD 2 "" 467 let c := ctrval ct 468 if c == 0 || ps.getD 1 "" != vc.cs then none else 469 let ds := (ps.getD 3 "").toList 470 if ds.length % 3 != 0 || !ds.all isDig then none else 471 let cds := codesOf ds [] 472 if (cds.map List.length).sum != ds.length then none else 473 if !cds.all (fun cd => vc.codes.contains (String.ofList cd)) then none else 474 let ts := body.getD 0 "" 475 let msg := "ocb2|" ++ vc.cs ++ "|" ++ ct ++ "|" ++ String.singleton lane ++ "|" ++ 476 ts ++ "|" ++ s ++ "|" ++ body.getD 2 "" ++ "|" ++ body.getD 3 "" ++ "|" ++ 477 body.getD 4 "" ++ "|" ++ body.getD 5 "" ++ "|" ++ String.ofList ds 478 if hmacHex vc.key (toB msg.toList) != mac then none else 479 some (s, c, ts, cds.any fun cd => cd.length == 3 && 300 ≤ numOf cd && numOf cd < 400) 480 481 def tsGe (last ts : String) : Bool := last == "" || (decide (last.length = ts.length) && decide (last ≤ ts)) 482 483 /-- verify: verifyM plus the counter and ts checks (fresh = strictly above last counter and ts ≥ last ts). -/ 484 def verify (vc : VC) (lane : Char) (last : String → Nat × String) (l : List Char) : 485 Option (String × Nat × Bool × Bool) := 486 (verifyM vc lane l).map fun (s, c, ts, e) => 487 let (lc, lts) := last s 488 (s, c, decide (lc < c) && tsGe lts ts, e) 489 490 /-- rdctf: the counter file; (0, "") when absent, (BIG, "") when malformed (fail closed). 491 Form is " \n"; a lone counter (old form) is accepted with an empty last ts. -/ 492 def rdctf : Option (List Char) → Nat × String 493 | none => (0, "") 494 | some c0 => 495 let c := c0.take 128 496 if c.length == 0 then (BIG, "") else 497 let m := if c.getLast? == some '\n' then c.dropLast else c 498 match m.idxOf? ' ' with 499 | none => 500 if m.length == 0 || 18 < m.length || !m.all isDig then (BIG, "") else (numOf m, "") 501 | some k => 502 let ctr := m.take k 503 let ts := String.ofList (m.drop (k + 1)) 504 if ctr.length == 0 || 18 < ctr.length || !ctr.all isDig then (BIG, "") else (numOf ctr, ts) 505 506 abbrev Tbl := List (String × Nat × String) 507 def tget (t : Tbl) (s : String) : Nat × String := ((t.find? (·.1 == s)).map (fun e => (e.2.1, e.2.2))).getD (0, "") 508 def tput (t : Tbl) (s : String) (c : Nat) (ts : String) : Tbl := 509 if t.any (·.1 == s) then t.map fun (s', c', ts') => 510 if s' == s then (if c' < c then (s', c, ts) else (s', c', ts')) else (s', c', ts') 511 else t ++ [(s, c, ts)] 512 513 abbrev VR := Option (String × Nat × Bool × Bool) 514 def isTwo : VR → Bool 515 | some (_, _, f, e) => f && e 516 | none => false 517 def freshOf : VR → Option (String × Nat) 518 | some (s, c, true, _) => some (s, c) 519 | _ => none 520 521 /-- max of file and table last-counter (and the ts that goes with the winner). -/ 522 def lastOf (fc : String → Nat × String) (t : Tbl) (s : String) : Nat × String := 523 let (fv, fts) := fc s 524 let (tv, tts) := tget t s 525 if fv < tv then (tv, tts) else (fv, fts) 526 527 /-- Destination binding for a signed line: 6 content fields and `to` equals the reading bot. -/ 528 def destOk (l : List Char) (bot : String) : Bool := 529 decide ((lfmt l).1.length = 6) && decide ((lfmt l).1.getD 2 "" = bot) 530 531 /-- verified (trit.om) = verx in table mode, with to = bot and the file's lane in the MAC. 532 A 6-field line whose `to` is not the bot never verifies. -/ 533 def vline (vc : Option VC) (fc : String → Nat × String) (t : Tbl) (bot : String) (lane : Char) 534 (l : List Char) : VR × Tbl := 535 match vc with 536 | none => (none, t) 537 | some v => 538 if destOk l bot then 539 let fs := (lfmt l).1 540 let r := verify v lane (lastOf fc t) l 541 (r, match r with 542 | some (s, c, true, _) => tput t s c (fs.getD 0 "") 543 | _ => t) 544 else (none, t) 545 546 /-- lvl: 2 only from a verified, fresh line with a 3xx code; fyi 0; anything else 1. -/ 547 def lvl (r : VR) (l : List Char) : Trit := 548 if isTwo r then .two else if lnkind l == .zero then .zero else .one 549 550 /-- admit + cntwin + seenc: only MAC-good lines count, once per (sender, counter). -/ 551 def admit (allow : List String) (acc : List (String × Nat × Nat)) (r : VR) (l : List Char) : 552 Option (List (String × Nat × Nat)) := 553 match (fields l)[1]? with 554 | none => none 555 | some s => 556 if !okname allow s then none else 557 let m := minute l 558 if m == 0 then none else 559 match r with 560 | none => some acc 561 | some (_, c, _, _) => 562 if acc.any (fun (s', _, c') => s' == s && c' == c) then some acc else 563 if 3 ≤ (acc.filter fun (s', m', _) => s' == s && absd m' m < 60).length then none 564 else some (acc ++ [(s, m, c)]) 565 566 /-- scane: every complete content line is verified and goes through admission. -/ 567 def scane (vc : Option VC) (fc : String → Nat × String) (allow : List String) (st : Nat) 568 (ls : List (Nat × List Char)) : Trit × Nat × Tbl := 569 let r := ls.foldl (fun (acc, t, rej, tb) (p, l) => 570 if !ists l then (acc, t, rej, tb) else 571 let (v, tb') := vline vc fc tb "a" 'e' l 572 match admit allow acc v l with 573 | some acc' => (acc', if st ≤ p then t.max (lvl v l) else t, rej, tb') 574 | none => (acc, t, if st ≤ p then rej + 1 else rej, tb')) 575 (([] : List (String × Nat × Nat)), Trit.zero, 0, ([] : Tbl)) 576 (r.2.1, r.2.2.1, r.2.2.2) 577 578 /-- one step of scann -/ 579 def nstep (vc : Option VC) (fc : String → Nat × String) (st : Nat) (x : Trit × Tbl) (y : Nat × List Char) : Trit × Tbl := 580 if st ≤ y.1 && ists y.2 then 581 let (v, tb') := vline vc fc x.2 "a" 'n' y.2 582 (x.1.max (lvl v y.2), tb') 583 else x 584 585 def scann (vc : Option VC) (fc : String → Nat × String) (t0 : Tbl) (st : Nat) (ls : List (Nat × List Char)) : Trit := 586 (ls.foldl (nstep vc fc st) (.zero, t0)).1 587 588 /-- rdcur: the unread start, from at most the first 128 cursor bytes. -/ 589 def rdcur (cur : Option (List Char)) (fb : List Char) : Nat := 590 match cur with 591 | none => 0 592 | some c0 => 593 let cb := c0.take 128 594 let n := cb.length 595 if n < 66 then 0 else 596 let digits := cb.takeWhile (· != ' ') 597 if !digits.all isDig then 0 else 598 let i := digits.length 599 let bad := (List.range i).any fun j => 600 decide (`100000000000000` < (digits.take j).foldl (fun a ch => a * 10 + (ch.toNat - 48)) 0) 601 if bad then 0 else 602 let off := digits.foldl (fun a ch => a * 10 + (ch.toNat - 48)) 0 603 if off == 0 || fb.length < off then 0 else 604 if n < i + 65 then 0 else 605 if fb.getD (off - 1) ' ' != '\n' then 0 else 606 if (sha256 (fb.take off)).toList == (cb.drop (i + 1)).take 64 then off else 0 607 608 /-- lastnl + mktok: the token for a lane. -/ 609 def token (lane : Char) (fb : List Char) : String := 610 let off := fb.length - (fb.reverse.idxOf '\n') 611 String.singleton lane ++ toString off ++ ":" ++ sha256 (fb.take off) 612 613 def digit : Trit → String 614 | .zero => "0" | .one => "1" | .two => "2" 615 616 /-- state + emit + rejout + main's exit status for one bot `a` (stdout, stderr, status). -/ 617 def runBot (vc : Option VC) (fc : String → Nat × String) (allow : List String) (nm em nc ec : Option (List Char)) : 618 String × String × Nat := 619 let (te, rej, tb) := match em with 620 | none => (Trit.zero, 0, ([] : Tbl)) 621 | some e => scane vc fc allow (rdcur ec e) (linesOf e) 622 let err := if 0 < rej then "rejected a " ++ toString rej ++ "\n" else "" 623 let (t, tok) : Trit × String := 624 if te == .two then (te, token 'e' (em.getD [])) else 625 let tn := match nm with 626 | none => Trit.zero 627 | some n => scann vc fc tb (rdcur nc n) (linesOf n) 628 if tn != .zero then (tn, token 'n' (nm.getD [])) else 629 if te != .zero then (te, token 'e' (em.getD [])) else (.zero, "") 630 if t == .zero then ("", err, 1) else ("a " ++ digit t ++ " " ++ tok ++ "\n", err, 0) 631 632 /-! Properties of the shipped logic. -/ 633 634 /-- A 2 comes only from a line whose codebook verify returned fresh with a 3xx code. -/ 635 theorem lvl_two (r : VR) (l : List Char) (h : lvl r l = .two) : isTwo r = true := by 636 unfold lvl at h 637 by_cases hr : isTwo r = true 638 · exact hr 639 · simp only [hr, Bool.false_eq_true, ite_false] at h 640 split at h <;> cases h 641 642 theorem isTwo_some (r : VR) (h : isTwo r = true) : ∃ s c, r = some (s, c, true, true) := by 643 match r, h with 644 | some (s, c, true, true), _ => exact ⟨s, c, rfl⟩ 645 646 /-- In trit, the verify result is exactly codebook verify against max(counter file, table). -/ 647 theorem vline_none (fc : String → Nat × String) (t : Tbl) (bot : String) (lane : Char) (l : List Char) : 648 vline none fc t bot lane l = (none, t) := rfl 649 650 /-- verify refuses every line whose MAC does not check, and a fresh line has a strictly greater counter. -/ 651 theorem verify_fresh (v : VC) (lane : Char) (last : String → Nat × String) (l : List Char) 652 (s : String) (c : Nat) (e : Bool) 653 (h : verify v lane last l = some (s, c, true, e)) : (last s).1 < c := by 654 unfold verify at h 655 cases hm : verifyM v lane l with 656 | none => simp [hm] at h 657 | some x => 658 obtain ⟨s', c', ts', e'⟩ := x 659 simp [hm] at h 660 obtain ⟨rfl, rfl, ⟨hlt, _⟩, rfl⟩ := h 661 exact hlt 662 663 theorem lvl_ne_two_none (l : List Char) : lvl none l ≠ .two := by 664 intro h; have := lvl_two _ _ h; simp [isTwo] at this 665 666 theorem max_ne_two (a b : Trit) (ha : a ≠ .two) (hb : b ≠ .two) : a.max b ≠ .two := by 667 cases a <;> cases b <;> simp_all <;> decide 668 669 /-- Without a codebook and key nothing in the normal lane is a 2 (STOP, stop tags included). -/ 670 theorem scann_capped (fc : String → Nat × String) (t0 : Tbl) (st : Nat) (ls : List (Nat × List Char)) : 671 scann none fc t0 st ls ≠ .two := by 672 unfold scann 673 suffices h : ∀ (xs : List (Nat × List Char)) (x : Trit × Tbl), x.1 ≠ .two → 674 (xs.foldl (nstep none fc st) x).1 ≠ .two from h ls _ (fun h => by cases h) 675 intro xs 676 induction xs with 677 | nil => intro x hx; exact hx 678 | cons y ys ih => 679 intro x hx 680 simp only [List.foldl_cons] 681 apply ih 682 unfold nstep 683 split 684 · exact max_ne_two _ _ hx (lvl_ne_two_none _) 685 · exact hx 686 687 /-- Never starved: when the emergency lane is at 2 (a verified 3xx), the output is the emergency 688 lane's whatever the normal lane holds. -/ 689 theorem emergency_first (vc : Option VC) (fc : String → Nat × String) (allow : List String) 690 (em ec n1 n2 c1 c2 : Option (List Char)) 691 (h : (match em with 692 | none => (Trit.zero, 0, ([] : Tbl)) 693 | some e => scane vc fc allow (rdcur ec e) (linesOf e)).1 = .two) : 694 runBot vc fc allow n1 em c1 ec = runBot vc fc allow n2 em c2 ec := by 695 unfold runBot 696 revert h 697 generalize (match em with 698 | none => (Trit.zero, 0, ([] : Tbl)) 699 | some e => scane vc fc allow (rdcur ec e) (linesOf e)) = r 700 intro h 701 obtain ⟨te, rej, tb⟩ := r 702 simp only at h ⊢ 703 subst h 704 simp 705 706 /-- A 2 from verified+lvl requires the 6-field form and to = the bot being read. -/ 707 theorem lvl_two_bound (v : VC) (fc : String → Nat × String) (t : Tbl) (bot : String) (lane : Char) 708 (l : List Char) (h : lvl (vline (some v) fc t bot lane l).1 l = .two) : 709 (lfmt l).1.length = 6 ∧ (lfmt l).1.getD 2 "" = bot := by 710 have ht := lvl_two _ _ h 711 unfold vline at ht 712 cases hb : destOk l bot 713 · simp [hb, isTwo] at ht 714 · have ⟨h1, h2⟩ := (Bool.and_eq_true _ _).mp hb 715 exact ⟨of_decide_eq_true h1, of_decide_eq_true h2⟩ 716 717 end TritBin 718 719 #print axioms TritSignal.classify_append 720 #print axioms TritSignal.scan_correct 721 #print axioms TritSignal.never_starved 722 #print axioms TritSignal.ack_race 723 #print axioms TritSignal.refused_ack_unchanged 724 #print axioms TritSignal.classify_total 725 #print axioms TritBin.scann_capped 726 #print axioms TritBin.lvl_two 727 #print axioms TritBin.verify_fresh 728 #print axioms TritBin.isTwo_some 729 #print axioms TritBin.emergency_first 730 #print axioms TritBin.lvl_two_bound