Full read-only audit of all 13 mini-apps against README's problem-mapping table + each module's own doc comments. 6 COHERENT (lightclock, fairdraw, healthpost, theclimb, sky, mentor), 7 GAP-FOUND and fixed in prior commits (fairshare, waterwatch, tunnelsafety, housing, assembly, findfamily, farms).
11 KiB
Coherence Audit: Fair Draw (ma-fairdraw)
Scope: src/miniapps/fairdraw/, src/lib/fairdraw.ts, cross-app integration in src/lib/theclimb.ts.
Claim under test (README.md:97): "Fair Draw (ma-fairdraw): Commit-reveal lottery engine; its tie-break utility is reused by other mini-apps that need a provably unriggable draw" (answers P14).
Verdict: COHERENT
The commit-reveal cryptography is sound for what it actually promises (tamper-evidence after publication, not multi-party grinding-resistance), the draw outcome is a deterministic pure function of the revealed seed, the cross-app reuse by The Climb is a real import/call (not a README-only claim), and there is correctly no device-sensor input anywhere in the randomness path. One caveat is worth flagging to the user even though it does not break the verdict: the module's own docstring explicitly scopes out solo-party seed grinding before publication, which is a narrower guarantee than "provably unriggable" might suggest to a reader who skips the fine print.
1. Is commit-reveal genuinely cryptographically sound?
Yes. src/lib/fairdraw.ts:
commit(seed, salt)(lines ~70-78) hashesseed+saltwith the real Web Cryptocrypto.subtle.digest("SHA-256", ...)— not a mock, notMath.random()-seeded, not a stub. The message is length-prefixed per field (commitMessage, lines ~50-58:`${seedBytes.length}:${seed}:${saltBytes.length}:${salt}`) specifically to close a real ambiguity bug: a naive${seed}:${salt}join lets("7","x:9")and("7:x","9")collide on the same byte string.fairdraw.test.ts("closes the seed/salt separator collision", lines 44-63) proves both that the collision no longer occurs and that each commit does NOT verify against the other pair's reveal — i.e. a drawer cannot commit once and later choose whichever of two ambiguous splits favors them.verifyCommit/verify(lines ~95-104) recomputescommit(revealedSeed, revealedSalt)and does a strict string-equality check against the publishedcommitHash, returningfalse(never throwing) on any mismatch. Proven in tests: "fails verify() visibly for a tampered reveal with the wrong seed" and "...wrong salt" (fairdraw.test.ts lines 33-41), plus "fairdraw QA - failure path" (lines 101-111) using an attacker-chosen seed.- Call-site ordering is enforced, not just advisory:
RevealDraw.tsx'sstartDraw()publishes the commit to the signed Event Log viaappend()and then re-reads it back withreadAll()before the UI even unlocks the Reveal button (lines ~195-212: "Gate on a fresh readAll() actually finding the commit entry... this is what makes the commit auditable after a reload between commit and reveal").revealDraw()only computesverified/winnerafterverify()resolves (lines ~222-230) — the winner is never rendered optimistically. validateReveal()(fairdraw.ts lines ~230-270) is an independent, replay-only auditor over the raw Event Log: it requires (a) afairdraw.commitexists for the drawId, (b) exactly onefairdraw.revealexists (zero = not yet revealed, two+ = a re-roll attempt, both rejected), (c) the reveal'slamportTsis strictly greater than the commit's, and (d)verify()passes. All four branches are covered by dedicated tests infairdraw.test.ts("rejects a reveal with no prior commit", "rejects a second reveal...", "rejects when reveal's lamportTs is not strictly after its commit's", "rejects when the reveal does not verify..., tampered seed", plus a cold-replay-snapshot test and a canonical-earliest-commit test for duplicate commits).RevealDraw.tsxwires this into the UI as a live "Draw integrity: valid / rejected" badge (lines ~280-290), not just a backend check nobody surfaces.
2. Is the draw outcome genuinely derived from the committed value, and can a party bias it?
Derivation is sound; the honest documented limitation is solo-grinding, not post-commit bias.
drawOutcome(seed, optionCount)(fairdraw.ts lines ~155-175) re-hashes"draw:" + seedwith SHA-256, folds all 32 digest bytes into a BigInt, and reduces modoptionCount— so the outcome depends on the whole hash (not a truncated, more-guessable slice), and is reproducible: same seed + optionCount always gives the same index (proven in "fairdraw QA - happy path", fairdraw.test.ts lines 85-99,outcomeA === outcomeB).- Because
drawOutcomeis only ever invoked inrevealDraw()afterverify()has passed (RevealDraw.tsxconst winnerIndex = verified ? await drawOutcome(...) : undefined), a tampered/mismatched reveal can never produce a winner — a falseverify()short-circuits straight towinnerIndex = undefinedand the "Invalid" badge, never a credited prize. - Documented, correct scope limit (fairdraw.ts module docstring, "Append-to-log payload shapes" section): "This is explicitly NOT a multiparty commit protocol... a solo drawer can still grind outcomes offline before ever publishing a commit... only re-rolling AFTER a commit is published becomes auditable and rejectable." That is: the single local-identity drawer chooses seed/salt before committing and could in principle try several off-the-record seed/salt pairs before ever calling
commit()— nothing stops private pre-commit grinding by the one party who initiates the draw, and nothing stops them from simply never revealing a commit they don't like (an abort, not a bias). What the protocol does guarantee, and what is tested, is that once a commit is published, that specific draw's revealed seed cannot be swapped for a more-favorable one —validateReveal's tests above cover exactly this. This is a correctly-scoped, explicitly-disclosed limitation, not a hidden gap — but README's one-line "provably unriggable draw" phrasing is a looser gloss than the in-code spec. Worth tightening the README language (e.g. "tamper-evident after publication") if advisory follow-up is wanted; not a code defect. - In The Climb's reuse (
src/lib/theclimb.ts), the limitation above is actually closed:deriveTieBreakSeed/deriveTieBreakSalt(lines ~215-221) derive the seed/salt purely fromplanInputsHash(a SHA-256 over the already-signed, already-committed plan content) plus the contested slot's node/distance/iteration — there is no freely-chosen value for anyone to grind, random or otherwise ("Nothing random ever enters it" per thehashScheduleInputsdocstring). The draw-affecting information (the plan) is locked in and hashed before any tie-break seed exists, which is a stronger non-grindable design than fairdraw's own standalone demo screen.
3. Is the "tie-break utility is reused by other mini-apps" claim real?
Yes, genuinely wired — a real import and function call, not a README-only claim.
src/lib/theclimb.tsline 32:import { commit, drawOutcome, reveal, verify } from "./fairdraw";— a direct module import, no indirection/registry.createLoggingTieBreaker()(theclimb.ts lines ~255-305) callscommit(),reveal(),verify(), anddrawOutcome()from fairdraw.ts in the correct commit-before-reveal order, publishingtheclimb.tiebreak.commitandtheclimb.tiebreak.revealevents to the same signed Event Log, and fails closed ifverify()ever returns false (throw new Error("...refusing to resolve a contested wave-slot tie without a verifiable draw")).- The min-cost-flow engine's path-reconstruction code (
findAugmentingPath/reconstruct, lines ~440-480) callstieBreaker.resolve(viable.length, {...})exactly at the point where more than one tied predecessor edge is found for a contested wave slot, and the function docstring states "It never falls back to array order or any ad hoc ordering of its own; if the injected Fair Draw integration throws, that error propagates (fails closed)". This is corroborated by this session's separate cross-device-sync audit finding (referenced in the task) thattheclimb.tiebreakwiring is real. verifyClimbTieBreakAudit()(theclimb.ts, final function) independently re-verifies everytheclimb.tiebreak.revealagainst its matchingtheclimb.tiebreak.commitusing fairdraw's ownverify()anddrawOutcome()— a second, auditor-facing integration point, not just the draw-time call.
4. Device-API angle?
None found, correctly. Grepped src/lib/fairdraw.ts, src/miniapps/fairdraw/RevealDraw.tsx, and src/lib/theclimb.ts for geolocation, DeviceMotion, DeviceOrientation, accelerometer, and generic navigator.* calls — zero matches. The only entropy source is crypto.getRandomValues() (randomSeedSalt() in RevealDraw.tsx, a real non-mocked CSPRNG call documented as "Real (non-mocked) randomness source for the seed/salt a draw commits to"), and in The Climb's reuse there is no randomness at all (deterministic hash of committed plan data). This is the correct design: a sensor-based entropy source would be unverifiable by other parties and would weaken, not strengthen, the provable-fairness property this app exists to deliver.
5. Any claimed-but-unwired UI/feature?
None found. The "re-rolling after the commit is published is auditable and rejected" subtitle text in RevealDraw.tsx is backed by the live validateReveal() call and its integrity badge (section 1 above) — not an aspirational claim with no enforcement. The component is mounted in the shell registry (src/shell/miniappComponents.tsx imports fairdraw), and FairDraw() wires the real local identity's account id into participant index 0 via useActiveAccountId() so a genuine win credits the real wallet through a real wallet.issue event (not a fabricated/demo-only credit) — DEMO_NEIGHBOR_ACCOUNTS are explicitly documented as never backing a real identity and never read by WalletCard, which matches their only use (symbolic opponents in the fixed 5-slot roster).
Evidence index
src/lib/fairdraw.ts— commit/reveal/verify/drawOutcome/validateReveal, SHA-256 via Web Crypto, length-prefixed canonical encoding.src/lib/fairdraw.test.ts— property test (100 random seed/salt pairs), tamper-rejection tests, separator-collision regression test, fullvalidateRevealbranch coverage including cold-replay and canonical-earliest-commit cases.src/miniapps/fairdraw/RevealDraw.tsx— UI wiring: realcrypto.getRandomValuesseed/salt, commit-before-reveal-button gating viareadAll()confirmation, live integrity badge fromvalidateReveal(), real wallet credit viaappend({type:"wallet.issue",...}).src/lib/theclimb.ts— realimport {...} from "./fairdraw",createLoggingTieBreaker(commit/reveal/verify/drawOutcome call chain, fail-closed on verify failure),fairDrawTieBreakerdeterministic default,verifyClimbTieBreakAuditindependent re-verification.README.md:97-98— the two claims under test (P14 Fair Draw, P15 The Climb "calling Fair Draw for contested wave slots").