## Leak checker: replays a leak-transcript.jsonl written by tools/leak.mjs and verifies one player's ## whole view (DESIGN 10.1, 10.2, 10.3; M3 slice 5 / #20). Ground truth is the GM socket: the GM sees ## every token and every wall, so the checker never trusts the subject's own messages for *what is*. ## ## Independent oracles: the subject's visibility polygons and explored cells are recomputed from the ## GM's truth with geometry.nim, and the explored set is additionally probed with a clear-segment ## test (no ray fan), because the prototype's explored check was self-consistent only (10.2). ## ## Every failure carries a class, and tools/fault.test.mjs asserts the EXACT class set of each ## injected server fault: ## HIDDEN_TOKEN a token the subject may not see reached it, or one its polygons admit only ## through a wall (#26: the fan's over-approximation is a token-level leak, so the ## class is checked on token centres and the viewer->token segment, never on ## sampled polygon points; a crossing within the 5.4 boundary tolerance is fine) ## GMONLY_TOKEN the same, for a `gm_only` token inside the subject's LOS ## WALLDATA a wall-ish key or frame reached the subject ## WITHHELD a token the subject may see was not sent (or was taken away while visible) ## NO_REMOVE a token that left the view was never withdrawn ## OWN_VIEW the subject's own token position or its vision polygon is wrong ## OTHER_PLAYER another player's polygon, `mine` flag, explored cells or presence leaked ## EXPLORED the explored set differs from the recomputation / the clear-segment oracle ## OWNER_PROP the `owner` property bucket reached someone who does not control the token ## GM_PROP the `gm` property bucket reached a player at all ## STATUS_SOURCE a player frame carried the `source` of a status (5.5, 6.1 note 6) ## ACTUAL_NAME an actual name the subject was never told reached it (8) ## STALE_NAME an encountered entry names a subject something other than the name that player ## knows (8): a stale snapshot the old "not the unrevealed actual" check let pass ## CHAR_LIST another player's character record or encountered entry reached the subject ## CONTROLLER_CHANGE a token changed controller in a group that asked for no such thing (8) ## CHAR_OWNER_PROP a character's owner bucket reached a player who does not own it (8) ## GEOMETRY the recomputed polygon disagrees with the clear-segment oracle (sanity): it only ## tests missing vision, so an over-approximated polygon is HIDDEN_TOKEN's job ## ONEWAY the subject's fan ignores `sight_dir` (the two-way fan; TESTING 10.3, #58) ## MARKER_EARLY a marker arrived before the subject had seen that wall's extent (the extent ## gate was dropped: it reveals a position early; TESTING 10.3, #60) ## MARKER_EXTRA a marker exists for a wall that should never produce one (the derived-`window` ## gate was dropped, or the wall is not a marker candidate at all; #60) ## MARKER_OFF a marker the visible-extent oracle expects was never sent (#60) ## PROTOCOL a frame the catalogue does not allow, a bad `n` sequence, a missing hello block ## ## One-way sight (DESIGN 5.8, TESTING 10.3): the checker reads `sight_dir` from the GM's frames and ## applies its OWN side test (`blindTo`, the sign of the cross product with `(-dy, dx)`) to decide ## whether a one-way wall is in a viewer's fan. It never calls `server/vision.nim`. Once the ## subject's own `vision` frame proves the sight_dir-dropped fan (the ONEWAY fault), the oracles ## evaluate that two-way perspective so the fault is reported as exactly ONEWAY. ## ## usage: leakcheck exit 0 = clean import std/[algorithm, json, math, options, os, sequtils, sets, strutils, tables] import geometry const AllowedTypes = ["hello", "ack", "roster", "token", "token_gone", "vision", "explored", "marker", "character", "character_gone", "encountered"] MarkerIdLength = 12 MarkerIdAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-" BannedAlways = ["walls", "wall", "wall_gone", "a", "b", "open", "kind", "controller", "gm_only", "flags", "radius_own", "extra", # every wall field name (#54): geometry, switches, door settings, label "thickness", "position", "height", "blocks_sight", "blocks_movement", "sight_dir", "player_marker", "door", "secret", "locked", "label"] BannedToken = ["descriptive_name", "actual_name", "reveal_all", "revealed"] BannedCharacterTop = ["owner", "reveal_all", "revealed"] ## top-level only: `props.owner` is fine BannedEncountered = ["player", "character_id", "pos"] type TruthToken = object pos: Vec controller: int gmOnly: bool hasVision: bool visionRadius: Option[float] radius: float props: JsonNode ## the GM's three buckets (the truth for every bucket question) statuses: seq[string] ## the status names the GM sees, in order characterId: string ## "" = a plain token (8) descriptive, actual: string ## a plain token's own names ("" for a linked token) revealAll: bool ## a plain token's reveal flag, "" names otherwise revealed: seq[int] ## the players a plain token's actual name was revealed to TruthCharacter = object owner: int descriptive, actual: string revealAll: bool revealed: seq[int] props: JsonNode Truth = object walls: seq[Wall] markerWalls: seq[MarkerWall] tokens: Table[string, TruthToken] characters: Table[string, TruthCharacter] MarkerWall = object ## A wall that should produce a marker (DESIGN 5.8): `player_marker:true` and the derived shape ## label `window` (`blocks_sight:false`, `blocks_movement:true`; a door either way). The checker ## keeps the geometry and the id from the GM's frames and does its own visible-extent test. id: int a, b: Vec thickness: float position: string playerMarker: bool isWindow: bool ExpectedMarker = object ## The oracle's accumulated memory for one wall: the anchor the subject should hold and the ## marker signature it was earned for. A cause change (5.8: gone, switch off, not a window, ## geometry moved) drops the entry, mirroring the server's retraction (#60). anchor: (int, int) sig: string MarkerSeen = object ## One marker id the subject was sent, resolved to the GM-truth wall it belongs to. Keying by ## wall (not by anchor) is what keeps two candidate walls that share a midpoint distinct. A ## `wall` of -1 means no candidate wall stands at that anchor (an extra marker). wall: int pos: (int, int) Group = object label: string gmMsgs: seq[JsonNode] subjMsgs: seq[JsonNode] intents: seq[JsonNode] ## what the clients asked for in this group (see CONTROLLER_CHANGE) var fails = 0 var classes: CountTable[string] proc fail(cls, s: string) = inc fails classes.inc cls if fails <= 25: echo "FAIL [", cls, "] ", s proc vec(j: JsonNode): Vec = (j[0].getFloat, j[1].getFloat) proc wallDir(j: JsonNode): WallDir = ## The GM's wall frames carry `sight_dir` (proto 2, #54); the checker reads it as its own input. if j.kind != JString: return wdBoth case j.getStr of "left": wdLeft of "right": wdRight else: wdBoth proc samePos(j: JsonNode, p: Vec): bool = ## JSON numbers lose their int/float spelling on the wire round trip: compare numerically. j.kind == JArray and j.len == 2 and abs(j[0].getFloat - p.x) < 1e-6 and abs(j[1].getFloat - p.y) < 1e-6 # --------------------------------------------------------------------------------------------------- # Transcript proc readGroups(path, subject: string): seq[Group] = ## One entry per group marker; every message belongs to the group that was open when it arrived. var current = -1 var groups: seq[Group] for line in lines(path): if line.strip.len == 0: continue let j = parseJson(line) case j["k"].getStr of "group": groups.add Group(label: j["label"].getStr) current = groups.high of "msg": if current < 0: continue let who = j["who"].getStr if who == "GM": groups[current].gmMsgs.add j["m"] elif who == subject: groups[current].subjMsgs.add j["m"] of "intent": if current >= 0: groups[current].intents.add j else: discard groups # --------------------------------------------------------------------------------------------------- # Truth from the GM socket (walls and every token) proc markerWallOf(id: int, w: JsonNode): MarkerWall = ## The marker-relevant projection of a GM wall frame (5.8): the derived `window` gate, the switch ## and the geometry whose change retracts (#60). MarkerWall(id: id, a: vec(w["a"]), b: vec(w["b"]), thickness: w["thickness"].getFloat, position: w["position"].getStr, playerMarker: w["player_marker"].getBool, isWindow: not w["blocks_sight"].getBool and w["blocks_movement"].getBool) proc isMarkerCandidate(m: MarkerWall): bool = m.playerMarker and m.isWindow proc markerSig(m: MarkerWall): string = ## The oracle's own copy of the retraction signature: endpoints, thickness, placement, switch and ## the derived window gate. Height and label have no marker consequence (5.8, #60). $m.a.x & "," & $m.a.y & "," & $m.b.x & "," & $m.b.y & "," & $m.thickness & "," & m.position & "," & $m.playerMarker & "," & $m.isWindow proc setMarkerWall(truth: var Truth, mw: MarkerWall) = ## Upsert by wall id, so a `wall` update replaces the marker projection in place. for i in 0 ..< truth.markerWalls.len: if truth.markerWalls[i].id == mw.id: if mw.isMarkerCandidate: truth.markerWalls[i] = mw else: truth.markerWalls.delete i return if mw.isMarkerCandidate: truth.markerWalls.add mw proc applyGmWalls(truth: var Truth, ids: var seq[int], m: JsonNode) = ## `wall` (upsert) and `wall_gone` need the id, which geometry.Wall does not carry. case m["t"].getStr of "walls": truth.walls.setLen(0) truth.markerWalls.setLen(0) ids.setLen(0) for w in m["walls"]: truth.walls.add Wall(a: vec(w["a"]), b: vec(w["b"]), door: w["door"].getBool, open: w["open"].getBool, sightDir: wallDir(w["sight_dir"]), sightBarrier: w["blocks_sight"].getBool, movementBarrier: w["blocks_movement"].getBool) ids.add w["id"].getInt truth.setMarkerWall markerWallOf(w["id"].getInt, w) of "wall": let id = m["id"].getInt let w = Wall(a: vec(m["a"]), b: vec(m["b"]), door: m["door"].getBool, open: m["open"].getBool, sightDir: wallDir(m["sight_dir"]), sightBarrier: m["blocks_sight"].getBool, movementBarrier: m["blocks_movement"].getBool) var found = false for i in 0 ..< ids.len: if ids[i] == id: truth.walls[i] = w found = true if not found: truth.walls.add w ids.add id truth.setMarkerWall markerWallOf(id, m) of "wall_gone": let id = m["id"].getInt for i in 0 ..< ids.len: if ids[i] == id: truth.walls.delete i ids.delete i break for i in 0 ..< truth.markerWalls.len: if truth.markerWalls[i].id == id: truth.markerWalls.delete i break else: discard proc applyGmTokens(truth: var Truth, m: JsonNode) = case m["t"].getStr of "token": var t = TruthToken(pos: vec(m["pos"]), controller: (if m["controller"].kind == JNull: 0 else: m["controller"].getInt), gmOnly: m["gm_only"].getBool, hasVision: m["flags"].hasKey("vision") and m["flags"]["vision"].kind == JBool and m["flags"]["vision"].getBool, radius: m["radius"].getFloat) if m["vision_radius"].kind != JNull: t.visionRadius = some(m["vision_radius"].getFloat) t.props = m["props"] for st in m["statuses"]: t.statuses.add st["status"].getStr # Slice 8 (#23): the GM frame always carries `character_id`, and a plain token carries its own # names and reveal state (a linked token's live on the `character` record). if m.hasKey("character_id") and m["character_id"].kind != JNull: t.characterId = m["character_id"].getStr if m.hasKey("descriptive_name"): t.descriptive = m["descriptive_name"].getStr t.actual = m["actual_name"].getStr t.revealAll = m["reveal_all"].getBool for p in m["revealed"]: t.revealed.add p.getInt truth.tokens[m["id"].getStr] = t of "token_gone": truth.tokens.del m["id"].getStr else: discard proc applyGmCharacters(truth: var Truth, m: JsonNode) = case m["t"].getStr of "character": var c = TruthCharacter(owner: m["owner"].getInt, descriptive: m["descriptive_name"].getStr, actual: m["actual_name"].getStr, revealAll: m["reveal_all"].getBool, props: m["props"]) for p in m["revealed"]: c.revealed.add p.getInt truth.characters[m["id"].getStr] = c of "character_gone": truth.characters.del m["id"].getStr else: discard # --------------------------------------------------------------------------------------------------- # Independent oracles var checkDir = true ## False once the subject's own `vision` frame shows `sight_dir` dropped (the ONEWAY fault): from ## then on the oracles evaluate the faulty perspective so the fault is reported as exactly ONEWAY, ## not as a cascade of WITHHELD/OWN_VIEW/EXPLORED. proc blindTo(w: Wall, o: Vec): bool = ## The checker's OWN copy of the 5.8 side test, never `vision.nim`: cross(a->b, o - a) is the ## signed distance along the `(-dy, dx)` normal of `a -> b`, positive = left. On the drawn line ## both directions answer blind, so the predicate is never ambiguous. if w.sightDir == wdBoth: return false let s = cross(w.b - w.a, o - w.a) case w.sightDir of wdBoth: false of wdLeft: s >= -Eps of wdRight: s <= Eps proc wallsFor(truth: Truth, o: Vec, honourDir: bool): seq[Wall] = ## The wall list one viewer's fan gets. With `honourDir`, a sight-blocking one-way wall is kept ## only for a viewer on its blind side (the checker's own side test); otherwise every `sight_dir` ## is dropped, which is exactly the ONEWAY fault's two-way wall list. if honourDir: for w in truth.walls: if w.sightDir != wdBoth and not w.blindTo(o): continue result.add w else: result = truth.walls for w in result.mitems: w.sightDir = wdBoth proc clearLine(walls: seq[Wall], o, p: Vec): bool = ## The clear-segment oracle: no sight-blocking wall between o and p (independent of the ray fan). ## Two independent readings: the one-way side test for the sample's viewer `o` (#58) and the GM's ## `blocks_sight` switch (#57: a window never blocks, an open door never blocks, a solid or closed ## door does). Neither uses the server's vision code. for w in walls: if checkDir and w.sightDir != wdBoth and not w.blindTo(o): continue if w.blocksSight and segsCross(o, p, w.a, w.b): return false true proc rangeOf(sceneDefault: float, t: TruthToken): float = if t.hasVision and t.visionRadius.isSome and t.visionRadius.get > 0: t.visionRadius.get else: sceneDefault proc polygonsOf(truth: Truth, controller: int, sceneDefault: float, honourDir = true): seq[(string, seq[Vec])] = for id, t in truth.tokens: if t.controller != controller or not t.hasVision: continue result.add (id, visibilityPolygon(t.pos, wallsFor(truth, t.pos, honourDir), rangeOf(sceneDefault, t))) # deterministic order: by token id (the server keeps creation order; the checker sorts) result.sort(proc (a, b: (string, seq[Vec])): int = cmp(a[0], b[0])) proc samePolySet(got, want: seq[(string, seq[Vec])], tol = 0.5): bool = ## Every polygon present with the same id, vertex count and vertices within `tol` px (the wire's ## integer rounding, 6.4). Used to tell the correct fan from the ONEWAY fault's two-way fan. if got.len != want.len: return false var used = newSeq[bool](want.len) for (gid, gpts) in got: var matched = false for i in 0 ..< want.len: if used[i] or want[i][0] != gid: continue used[i] = true matched = true let wpts = want[i][1] if gpts.len != wpts.len: return false for k in 0 ..< gpts.len: if abs(gpts[k].x - wpts[k].x) > tol + 1e-6 or abs(gpts[k].y - wpts[k].y) > tol + 1e-6: return false break if not matched: return false true proc parsePolys(m: JsonNode): seq[(string, seq[Vec])] = for p in m["polys"]: var pts: seq[Vec] for q in p["pts"]: pts.add vec(q) result.add (p["id"].getStr, pts) proc insideAny(polys: seq[(string, seq[Vec])], p: Vec): bool = for (_, pts) in polys: if inside(pts, p): return true const BoundaryTol = 0.5 ## DESIGN 5.4: a point within 0.5 px of a vision boundary is ambiguous; the checker's ## clear-segment oracle already uses that neighbourhood (TESTING 5.4). proc shrink(a, b: Vec, tol: float): (Vec, Vec) = ## `a -> b` with both ends pulled in by `tol`; a segment too short to shrink is kept whole. let dx = b.x - a.x let dy = b.y - a.y let l = hypot(dx, dy) if l <= 2 * tol: return (a, b) ((a.x + dx / l * tol, a.y + dy / l * tol), (b.x - dx / l * tol, b.y - dy / l * tol)) proc insideThroughWall(truth: Truth, polys: seq[(string, seq[Vec])], p: Vec): bool = ## #26: a point inside a polygon that only a wall admits. The polygons are the same fan the ## server runs, and `inside` alone cannot see this leak (the GEOMETRY class checks the opposite ## direction, missing vision), so this is the token-level assertion the class list promises: ## for the polygon containing `p`, the segment from that viewer's centre to `p` must not pass ## through the interior of a sight-blocking wall. Both segments are shrunk by the 5.4 boundary ## tolerance first, so a token grazing a corner (inside the polygon while touching the wall's ## endpoint) stays tolerated and only a real crossing is a leak. for (pid, pts) in polys: if not inside(pts, p): continue if pid notin truth.tokens: continue let o = truth.tokens[pid].pos let (o2, p2) = shrink(o, p, BoundaryTol) for w in truth.walls: if checkDir and w.sightDir != wdBoth and not w.blindTo(o): continue if not w.blocksSight: continue let (wa, wb) = shrink(w.a, w.b, BoundaryTol) if segsCross(o2, p2, wa, wb): return true false proc extentSeen(polys: seq[(string, seq[Vec])], a, b: Vec): bool = ## The checker's OWN visible-extent test (DESIGN 5.8, TESTING 10.3; never `vision.nim`): any point ## of the segment inside one of the subject's polygons means an endpoint is inside or the segment ## crosses a polygon edge. The polygons themselves are the GM-truth recomputation above. for (_, pts) in polys: if pts.len < 3: continue if inside(pts, a) or inside(pts, b): return true for i in 0 ..< pts.len: if segsCross(a, b, pts[i], pts[(i + 1) mod pts.len]): return true proc anchorOf(mw: MarkerWall): (int, int) = ## The drawn midpoint, rounded once to integer px (5.8, 6.1). (int(round((mw.a.x + mw.b.x) / 2)), int(round((mw.a.y + mw.b.y) / 2))) proc validMarkerId(id: string): bool = if id.len != MarkerIdLength: return false for c in id: if c notin MarkerIdAlphabet: return false true proc markerShapeOk(m: JsonNode): bool = ## Only `{id, pos}` per entry, the id opaque and the anchor integer px (6.1). A wall id or any ## other field here is a shape failure, and `keysDeep` catches the banned wall names separately. for e in m["set"]: if e.kind != JObject or e.len != 2 or not e.hasKey("id") or not e.hasKey("pos"): return false if e["id"].kind != JString or not validMarkerId(e["id"].getStr): return false if e["pos"].kind != JArray or e["pos"].len != 2: return false for q in e["pos"]: if q.kind != JInt: return false if m.hasKey("del"): for d in m["del"]: if d.kind != JString or not validMarkerId(d.getStr): return false true proc cellOf(sceneW: float, cell: int, ix, iy: int): (float, float) = (float(ix * cell) + float(cell) / 2, float(iy * cell) + float(cell) / 2) proc definitelySeen(walls: seq[Wall], polys: seq[(string, seq[Vec])], sceneW: float, cell, cx, cy: int): bool = ## A cell is seen if any of its corners or its centre is in clear LOS inside a polygon. The ## tolerance for the opposite direction (explored but no sample in LOS) lives in the caller. let (mx, my) = cellOf(sceneW, cell, cx, cy) let pts = [(mx, my), (float(cx * cell), float(cy * cell)), (float((cx + 1) * cell), float(cy * cell)), (float((cx + 1) * cell), float((cy + 1) * cell)), (float(cx * cell), float((cy + 1) * cell))] for p in pts: if insideAny(polys, p) and clearLine(walls, (mx, my), p): return true false proc keysDeep(node: JsonNode, into: var HashSet[string]) = if node.kind == JObject: for k, v in node: into.incl k keysDeep(v, into) elif node.kind == JArray: for v in node: keysDeep(v, into) # --------------------------------------------------------------------------------------------------- proc subjectKnewActual(truth: Truth, t: TruthToken, me: int): bool = ## DESIGN 8: a player is told a subject's actual name when they own the character it belongs to, ## when the GM revealed it to everyone, or when the GM revealed it to them. if t.characterId.len > 0: if not truth.characters.hasKey(t.characterId): return false let c = truth.characters[t.characterId] result = c.owner == me or c.revealAll or me in c.revealed else: result = t.revealAll or me in t.revealed proc subjectNames(truth: Truth, t: TruthToken): (string, string) = ## The descriptive and actual name of what a token figures: the character's when linked (8). if t.characterId.len > 0 and truth.characters.hasKey(t.characterId): let c = truth.characters[t.characterId] (c.descriptive, c.actual) else: (t.descriptive, t.actual) proc checkArgs(): (string, string) = if paramCount() < 2: echo "usage: leakcheck " quit 2 (paramStr(1), paramStr(2)) proc main() = let (path, subject) = checkArgs() let groups = readGroups(path, subject) if groups.len == 0: echo "leakcheck: no groups in ", path quit 2 var truth: Truth var wallIds: seq[int] var me = 0 var other = 0 var sceneDefault = 400.0 var sceneW = 4096.0 var cell = 32 var haveHello = false var expectedN = 1 # what the subject has been told var view: Table[string, JsonNode] # token id -> last `token` frame var leaked: Table[string, string] # token id -> the class it was first reported under var exploredSent: HashSet[int] var otherExplored: HashSet[int] var removes = 0 var groupsSeen = 0 var recomputedSoFar: HashSet[int] # every cell the subject has ever seen, recomputed var seenAny: HashSet[string] # token ids the subject was legitimately shown var encounterable: HashSet[string] # token ids the subject may have met (independent oracle) var viewCharacters: HashSet[string] # character ids the subject was sent var prevController: Table[string, int] # controller of each token at the previous group var markers: Table[string, MarkerSeen] # marker id -> the GM-truth wall it was minted for var expectedMarkers: Table[int, ExpectedMarker] # wall id -> accumulated memory (#59/#60) var markerPositive = false # the scenario exercised the oracle at least once for g in groups: inc groupsSeen for m in g.gmMsgs: applyGmWalls(truth, wallIds, m) applyGmTokens(truth, m) applyGmCharacters(truth, m) if m["t"].getStr == "marker": fail "PROTOCOL", "the GM received a marker frame (5.8: player memory only)" # player ids: the subject from its hello, the other from any token it does not control for m in g.subjMsgs: if m["t"].getStr == "hello": haveHello = true me = m["me"]["id"].getInt if m.hasKey("scene"): sceneW = m["scene"]["w"].getFloat cell = m["scene"]["cell"].getInt sceneDefault = m["scene"]["vision_radius_default"].getFloat else: fail "PROTOCOL", "hello without a scene block for a named player" for id, t in truth.tokens: if me != 0 and t.controller != me and t.controller != 0 and (other == 0 or t.controller < other): other = t.controller # Before the subject's hello there is no subject side to check: `me` is unknown, so "mine" and # "visible to the subject" would both be meaningless. Always apply the GM truth first. if me == 0: continue let polys = polygonsOf(truth, me, sceneDefault) var anyOneWay = false for w in truth.walls: if w.sightDir != wdBoth: anyOneWay = true # The fault's fan is only worth recomputing in a world that has a one-way wall at all. let faultPolys = if anyOneWay: polygonsOf(truth, me, sceneDefault, honourDir = false) else: polys # The subject's own `vision` frame decides the perspective this group is checked against: if it # matches the sight_dir-dropped fan and not the correct one, the ONEWAY fault is live. Then the # oracles evaluate that perspective, so the fault surfaces as exactly ONEWAY instead of a # cascade of WITHHELD/OWN_VIEW/EXPLORED. if anyOneWay: for m in g.subjMsgs: if m["t"].getStr != "vision": continue let got = parsePolys(m) if not samePolySet(got, polys) and samePolySet(got, faultPolys): checkDir = false let polysChecks = if checkDir: polys else: faultPolys let otherPolys = if other != 0: polygonsOf(truth, other, sceneDefault, honourDir = checkDir) else: @[] # The encountered oracle, computed from the GM's truth and the subject's own polygons - never # from what the subject was sent: every token the subject can see right now is one it may have # met. It only grows, exactly like the server's list (8). var visibleNow = initHashSet[string]() for id, actual in truth.tokens: if actual.controller == me or (not actual.gmOnly and insideAny(polysChecks, actual.pos)): visibleNow.incl id encounterable.incl id # the other player's explored cells, independently (attribute leaks, 3.1 OTHER_PLAYER) for (_, pts) in otherPolys: for (cx, cy) in cellsTouched(pts, float(cell)): if cx < 0 or cy < 0: continue otherExplored.incl cy * int(ceil(sceneW / float(cell))) + cx # --- the subject's frames of this group ----------------------------------------------------- var sawExploredFull = false for m in g.subjMsgs: let t = m["t"].getStr if not m.hasKey("n") or m["n"].getInt != expectedN: fail "PROTOCOL", "n " & (if m.hasKey("n"): $m["n"].getInt else: "missing") & " where " & $expectedN & " was expected (" & t & ")" expectedN = (if m.hasKey("n"): m["n"].getInt else: expectedN) + 1 if t notin AllowedTypes: fail (if t in ["walls", "wall", "wall_gone"]: "WALLDATA" else: "PROTOCOL"), "frame type the catalogue forbids: " & t continue var keys = initHashSet[string]() keysDeep(m, keys) for k in keys: if k == "source": # 5.5 / 6.1 note 6: a viewer sees the status, never what caused it. fail "STATUS_SOURCE", "player frame carries a status source" elif k in BannedAlways: fail "WALLDATA", "player frame has wall-ish/GM-only key " & k if t == "token": for k in BannedToken: if k in keys: fail "WALLDATA", "a `token` frame for a player carries " & k elif t == "character": # An owner reads both names and its own `props.owner`; it must never learn `owner` (theirs), # `reveal_all` or the list of players a name was revealed to. for k, _ in m: if k in BannedCharacterTop: fail "CHAR_LIST", "a `character` frame carries " & k elif t == "encountered": for k in BannedEncountered: if k in keys: fail "CHAR_LIST", "an `encountered` frame carries " & k case t of "ack": # only a bad shape is interesting here; the driver already checked the outcomes it expected if m["ok"].getBool and m.hasKey("code"): fail "PROTOCOL", "ok ack with a code" of "token": let id = m["id"].getStr if id notin truth.tokens: fail "HIDDEN_TOKEN", "token " & id & " is not in the GM's truth" continue let actual = truth.tokens[id] # props: the public bucket always, the owner bucket only for the controller, the gm bucket # never (6.1 leak notes; the typed view has no field for it, so an injected fault shows here) var buckets = initHashSet[string]() if m.hasKey("props") and m["props"].kind == JObject: for name, _ in m["props"]: buckets.incl name if "gm" in buckets: fail "GM_PROP", "token " & id & " carried the gm property bucket to a player" # A frame that claims `mine` is the OTHER_PLAYER fault's shape: the bucket then matches the # (wrong) claim, so the claim itself is what gets reported, not the bucket. if "owner" in buckets and not (actual.controller == me) and not m["mine"].getBool: fail "OWNER_PROP", "token " & id & " carried the owner bucket to a non-controller" if actual.controller == me and "owner" notin buckets: fail "OWNER_PROP", "the controller is missing the owner bucket of token " & id if m.hasKey("props"): for name in ["public", "owner"]: if name notin buckets or not actual.props.hasKey(name): continue if m["props"][name] != actual.props[name]: fail (if name == "public": "OWN_VIEW" else: "OWNER_PROP"), "token " & id & " has a " & name & " bucket that is not the truth" # statuses: the names the GM sees, and nothing else on the entry var gotStatuses: seq[string] for st in m["statuses"]: if st.len != 1: fail "STATUS_SOURCE", "a player status entry carries more than `status`" gotStatuses.add st["status"].getStr if gotStatuses != actual.statuses: fail "OWN_VIEW", "token " & id & " statuses " & $gotStatuses & " != truth " & $actual.statuses if not samePos(m["pos"], actual.pos): fail "OWN_VIEW", "token " & id & " position " & $m["pos"] & " != truth " & $[actual.pos.x, actual.pos.y] let wantMine = actual.controller == me if m["mine"].getBool != wantMine: fail (if wantMine: "OWN_VIEW" else: "OTHER_PLAYER"), "mine flag on " & id # names (8): the one name this recipient may see, from the character when the token is linked let (dname, aname) = subjectNames(truth, actual) let knows = subjectKnewActual(truth, actual, me) let wantName = if knows: aname else: dname if m["name"].getStr != wantName: if aname != dname and m["name"].getStr == aname: fail "ACTUAL_NAME", "token " & id & " carries an actual name the subject was not told" else: fail "OWN_VIEW", "token " & id & " name " & m["name"].getStr & " != " & wantName # `character_id` goes only to the GM and the character's owner (6.1 leak note 2): showing it # to anyone else would link two tokens of one character (10.3 CHAR_LIST). if m.hasKey("character_id"): let owned = actual.characterId.len > 0 and truth.characters.hasKey(actual.characterId) and truth.characters[actual.characterId].owner == me if not owned or m["character_id"].getStr != actual.characterId: fail "CHAR_LIST", "token " & id & " carries character_id to a non-owner" # cprops: the character's `public` bucket and nothing else, `{}` when there is nothing to say if m.hasKey("cprops"): for name, _ in m["cprops"]: if name != "public": fail "CHAR_OWNER_PROP", "token " & id & " cprops carries the " & name & " bucket" var want = newJObject() if actual.characterId.len > 0 and truth.characters.hasKey(actual.characterId) and truth.characters[actual.characterId].owner != me: want = truth.characters[actual.characterId].props["public"] let got = if m["cprops"].hasKey("public"): m["cprops"]["public"] else: newJObject() if got != want: fail "CHAR_OWNER_PROP", "token " & id & " cprops public bucket is not the truth" view[id] = m let visible = wantMine or (not actual.gmOnly and insideAny(polysChecks, actual.pos)) if not visible: let cls = if actual.gmOnly and insideAny(polysChecks, actual.pos): "GMONLY_TOKEN" else: "HIDDEN_TOKEN" leaked[id] = cls fail cls, "token " & id & " sent but not visible (group " & g.label & ")" else: seenAny.incl id # #26: the polygon is an over-approximation by design only up to the 5.4 boundary. A # token that is inside it with a wall crossing the viewer -> token segment (away from # either end) is hidden, and this is the token-level assertion the class list promises. if not wantMine and insideThroughWall(truth, polysChecks, actual.pos): leaked[id] = "HIDDEN_TOKEN" fail "HIDDEN_TOKEN", "token " & id & " is inside the subject's polygon only through a wall (group " & g.label & ")" of "token_gone": let id = m["id"].getStr if id notin view: fail "PROTOCOL", "token_gone for a token this player never had: " & id else: view.del id inc removes if id in truth.tokens: let actual = truth.tokens[id] if actual.controller == me or (not actual.gmOnly and insideAny(polysChecks, actual.pos)): fail "WITHHELD", "token_gone for a token still visible: " & id of "character": # 6.1: a player gets only the characters it owns, with both names and the public/owner # buckets. Anything else is CHAR_LIST (10.3). let id = m["id"].getStr if not truth.characters.hasKey(id): fail "CHAR_LIST", "a character record the GM's truth does not have: " & id elif truth.characters[id].owner != me: fail "CHAR_LIST", "another player's character record: " & id else: let c = truth.characters[id] if m["descriptive_name"].getStr != c.descriptive or m["actual_name"].getStr != c.actual: fail "PROTOCOL", "character " & id & " names differ from the truth" for name, value in m["props"]: if not c.props.hasKey(name) or c.props[name] != value: fail (if name == "public": "OWN_VIEW" else: "CHAR_OWNER_PROP"), "character " & id & " has a " & name & " bucket that is not the truth" viewCharacters.incl id of "character_gone": let id = m["id"].getStr if id notin viewCharacters: fail "PROTOCOL", "character_gone for a character this player never had: " & id viewCharacters.excl id of "encountered": # 6.1: the subject's own list only; an entry names a token the subject really did see, under # the name it knows (8). No position, no character link. for e in m["set"]: let id = e["id"].getStr if id notin encounterable: fail "CHAR_LIST", "encountered entry the subject never saw: " & id elif truth.tokens.hasKey(id): let (dname, aname) = subjectNames(truth, truth.tokens[id]) let knows = subjectKnewActual(truth, truth.tokens[id], me) # The expected name, not merely "not the unrevealed actual": a stale snapshot that still # carries an old descriptive name is a bug the old check could not see (#30). let want = if knows: aname else: dname let got = e["name"].getStr if got != want: if aname != dname and got == aname: fail "ACTUAL_NAME", "encountered " & id & " carries an unrevealed actual name" else: fail "STALE_NAME", "encountered " & id & " has name " & got & " not " & want & " (group " & g.label & ")" if m.hasKey("del"): for d in m["del"]: if d.getStr notin encounterable: fail "CHAR_LIST", "del for an entry the subject never had: " & d.getStr of "roster": # 6.1 leak note 4: players see named players only. for pl in m["players"]: if pl["name"].kind == JNull or pl["name"].getStr.len == 0: fail "PROTOCOL", "the roster handed a player an unnamed entry" of "vision": let got = parsePolys(m) if not samePolySet(got, polys): if anyOneWay and samePolySet(got, faultPolys): # TESTING 10.3: the fan behaves as if `sight_dir` were dropped (a two-way wall). fail "ONEWAY", "vision is the sight_dir-dropped fan (group " & g.label & ")" else: let want = polys var haveIds = initHashSet[string]() for (id, pts) in got: haveIds.incl id var matched = false for (wid, wpts) in want: if wid != id: continue matched = true if pts.len != wpts.len: fail "OWN_VIEW", "polygon " & id & " has " & $pts.len & " of " & $wpts.len & " vertices" else: for i in 0 ..< pts.len: # integer px on the wire (6.4): 0.5 px is the documented tolerance if abs(pts[i].x - wpts[i].x) > 0.5 + 1e-6 or abs(pts[i].y - wpts[i].y) > 0.5 + 1e-6: fail "OWN_VIEW", "polygon " & id & " vertex " & $i & " is " & $pts[i] & " not " & $wpts[i] break if not matched: var theirs = false for (oid, _) in otherPolys: if oid == id: theirs = true fail (if theirs: "OTHER_PLAYER" else: "PROTOCOL"), "vision carries a polygon for a token this player does not control: " & id for (id, _) in want: if id notin haveIds: fail "OWN_VIEW", "vision is missing the polygon of " & id of "explored": if m["full"].getBool: sawExploredFull = true # a resync snapshot replaces the set; every cell must be one the recomputation has seen var cells: seq[(int, int)] let cols = int(ceil(sceneW / float(cell))) for row in m["rle"]: let cy = row[0].getInt var i = 1 while i + 1 < row.len: let x0 = row[i].getInt let len = row[i + 1].getInt for k in 0 ..< len: cells.add (x0 + k, cy) i += 2 discard cols exploredSent = initHashSet[int]() for (cx, cy) in cells: exploredSent.incl cy * int(ceil(sceneW / float(cell))) + cx else: for c in m["cells"]: let cx = c[0].getInt let cy = c[1].getInt let k = cy * int(ceil(sceneW / float(cell))) + cx exploredSent.incl k of "marker": # DESIGN 5.8/6.1/6.3: the player's own opaque ids and integer-px anchors, nothing else. # `full:true` is the resync set and must follow `explored` full (the client draws it over the # fog just rebuilt); a diff adds ids in `set` and (from #60) retracts in `del`. if not markerShapeOk(m): fail "PROTOCOL", "malformed marker frame (group " & g.label & ")" elif m["full"].getBool and not sawExploredFull: fail "PROTOCOL", "marker full before explored full (group " & g.label & ")" else: if m["full"].getBool: markers.clear() for e in m["set"]: let id = e["id"].getStr let pos = (e["pos"][0].getInt, e["pos"][1].getInt) if markers.hasKey(id): fail "PROTOCOL", "duplicate marker id " & id & " (group " & g.label & ")" continue # Resolve the id to a GM-truth wall by anchor. Prefer the wall the oracle expects and # that has no id yet, so two candidates sharing a midpoint each get their own id; then # any free candidate; then the marker is extra (or a re-mint, below). var cand: seq[int] for mw in truth.markerWalls: if anchorOf(mw) == pos: cand.add mw.id var pick = -1 for c in cand: var used = false for _, seen in markers: if seen.wall == c: used = true if not used and expectedMarkers.hasKey(c): pick = c break if pick < 0: for c in cand: var used = false for _, seen in markers: if seen.wall == c: used = true if not used: pick = c break if pick < 0 and cand.len == 1 and expectedMarkers.hasKey(cand[0]): # The one wall this anchor belongs to already has a live id: the marker was re-minted # without the old one dying. A marker id is minted once and stable across refreshes # (5.8); only a re-earn after a retraction gets a fresh one. This is a protocol break, # not one of the four marker fault classes (documented in TESTING 10.3). fail "PROTOCOL", "marker for wall " & $cand[0] & " re-minted as " & id & " while its old id is still live (group " & g.label & ")" if pick < 0: markers[id] = MarkerSeen(wall: -1, pos: pos) # extra: no free candidate at anchor else: markers[id] = MarkerSeen(wall: pick, pos: pos) if m.hasKey("del"): for d in m["del"]: let id = d.getStr if not markers.hasKey(id): fail "PROTOCOL", "del for a marker the subject never had: " & id markers.del id else: discard # --- player markers (5.8, TESTING 10.3 #59/#60) --------------------------------------------- # The oracle's own memory: a marked window enters `expectedMarkers` once any part of its drawn # extent is inside the subject's polygons, and stays while the cause is unchanged. The four # retraction causes (wall gone, switch off, no longer a window, geometry moved) drop it, which # is the server's rule read independently from the GM's truth. It never calls vision.nim: # `polysChecks` is this file's recomputed fan. for id in expectedMarkers.keys.toSeq: var match = none(MarkerWall) for mw in truth.markerWalls: if mw.id == id: match = some(mw) if match.isNone or markerSig(match.get) != expectedMarkers[id].sig: expectedMarkers.del id for mw in truth.markerWalls: if expectedMarkers.hasKey(mw.id): continue if extentSeen(polysChecks, mw.a, mw.b): expectedMarkers[mw.id] = ExpectedMarker(anchor: anchorOf(mw), sig: markerSig(mw)) var owned: HashSet[int] for _, seen in markers: if seen.wall >= 0: owned.incl seen.wall # Keyed by wall, not by anchor: two candidate walls sharing a midpoint stay two obligations, # and an id's stability is its wall's ownership (a re-mint is caught when the set arrives). var missingWalls: seq[int] for wallId in expectedMarkers.keys: if wallId notin owned: missingWalls.add wallId if missingWalls.len > 0: missingWalls.sort() fail "MARKER_OFF", "marker for wall " & $missingWalls[0] & " was never sent (" & $missingWalls.len & " missing; group " & g.label & ")" for _, seen in markers: if seen.wall < 0: fail "MARKER_EXTRA", "marker " & $seen.pos & " has no marker candidate wall (group " & g.label & ")" elif not expectedMarkers.hasKey(seen.wall): # It maps to a current candidate wall the oracle does not expect: sent before that wall's # extent was seen (MARKER_EARLY), or a cause change whose del never arrived. It is a marker # at a candidate's anchor either way, which is the class TESTING 10.3 defines. fail "MARKER_EARLY", "marker " & $seen.pos & " sent before its wall was seen (group " & g.label & ")" if expectedMarkers.len > 0: markerPositive = true # --- CONTROLLER_CHANGE (10.3) ---------------------------------------------------------------- # A token's controller may move only when an intent asked for it (`token.create` names one, # `token.update` patches `controller`, `player.remove` hands them to the GM). A character edit # that changed a controller would show up here (DESIGN 8: the controller is set on the token). var controllerIntent = false for it in g.intents: let t = it["t"].getStr if t == "token.create" or t == "player.remove": controllerIntent = true elif t == "token.update" and it["f"].hasKey("controller"): controllerIntent = true for id, actual in truth.tokens: if prevController.hasKey(id) and prevController[id] != actual.controller and not controllerIntent: fail "CONTROLLER_CHANGE", "token " & id & " changed controller in group " & g.label prevController[id] = actual.controller # --- the set of tokens the subject should hold at the end of this group --------------------- for id, actual in truth.tokens: let want = id in visibleNow let have = view.hasKey(id) if want and not have: fail "WITHHELD", "visible token never sent: " & id & " (group " & g.label & ")" elif not want and have: # A token that was never legitimately in view stays a leak under its first class; one that # was legitimately seen and is now invisible is a missing withdrawal. `seenAny` decides, # so a `gm_only` flip after a legitimate sighting is not re-labelled as a gm_only leak. if leaked.hasKey(id): fail leaked[id], "leaked token still in view: " & id elif id notin seenAny and actual.gmOnly and insideAny(polysChecks, actual.pos): fail "GMONLY_TOKEN", "gm_only token still in view: " & id else: fail "NO_REMOVE", "token left the view and was never withdrawn: " & id & " (group " & g.label & ")" elif want and have: if not samePos(view[id]["pos"], actual.pos): fail "OWN_VIEW", "stale position for " & id # --- the explored set ---------------------------------------------------------------------- var recomputed: HashSet[int] let cols = int(ceil(sceneW / float(cell))) let rows = int(ceil(sceneW / float(cell))) for (_, pts) in polysChecks: for (cx, cy) in cellsTouched(pts, float(cell)): # cells outside the world are not cells: the server drops them too (vision.refresh) if cx < 0 or cy < 0 or cx >= cols or cy >= rows: continue recomputed.incl cy * cols + cx for k in recomputed: recomputedSoFar.incl k var suspect = initCountTable[string]() for k in exploredSent: # explored only grows (5.1): a cell seen in an earlier group is legitimately explored now if k in recomputedSoFar: continue let cx = k mod cols let cy = k div cols if definitelySeen(truth.walls, polysChecks, sceneW, cell, cx, cy): recomputed.incl k # grazed cell the sampler does see: fine either way continue # attribution: a cell only the other player has explored is a presence leak, not a bad cell let cls = if k in otherExplored: "OTHER_PLAYER" else: "EXPLORED" suspect.inc(cls) if suspect[cls] <= 3: fail cls, "explored cell (" & $cx & "," & $cy & ") is outside the subject's sight (group " & g.label & ")" for cls, n in suspect: if n > 3: fail cls, $n & " explored cells the subject never saw (group " & g.label & ")" # completeness: every cell the recomputation says is seen must have been sent var missing = 0 for k in recomputed: if k notin exploredSent: inc missing if missing <= 3: fail "EXPLORED", "recomputed explored cell never sent: " & $k if missing > 3: fail "EXPLORED", $missing & " recomputed explored cells were never sent" if getEnv("LEAK_DEBUG") != "": for (id, pts) in polysChecks: var cx0 = 100000; var cx1 = -1; var cy0 = 100000; var cy1 = -1 for (cx, cy) in cellsTouched(pts, float(cell)): cx0 = min(cx0, cx); cx1 = max(cx1, cx); cy0 = min(cy0, cy); cy1 = max(cy1, cy) echo " poly ", id, " verts ", pts.len, " cells x ", cx0, "..", cx1, " y ", cy0, "..", cy1, " group ", g.label, " cell ", cell, " sceneW ", sceneW # --- the clear-segment oracle on the polygon itself ----------------------------------------- for (id, pts) in polysChecks: if pts.len < 3: continue var t: TruthToken for tid, tt in truth.tokens: if tid == id: t = tt let o = t.pos let r = rangeOf(sceneDefault, t) for i in 0 ..< 64: for k in [0.3, 0.6, 0.95]: let p: Vec = (o.x + k * r * cos(2 * PI * i.float / 64), o.y + k * r * sin(2 * PI * i.float / 64)) if p.x < 0 or p.y < 0 or p.x > sceneW or p.y > sceneW: continue if clearLine(truth.walls, o, p) and not inside(pts, p): fail "GEOMETRY", "polygon " & id & " misses a clear-LOS point " & $p if not haveHello: fail "PROTOCOL", "no hello for the subject" if me == 0: fail "PROTOCOL", "no player id in hello" if removes == 0: fail "NO_REMOVE", "the scenario never withdrew a token (harness coverage)" if seenAny.len < 3: fail "WITHHELD", "the scenario never showed the subject 3 tokens" if not markerPositive: fail "PROTOCOL", "the scenario never produced a marker the visible-extent oracle expects" for cls, n in classes: echo "FAILCLASS ", cls, " ", n echo "leakcheck: subject ", subject, " (player ", me, "), ", groupsSeen, " groups, ", view.len, " tokens in view at the end, ", removes, " withdrawals, ", exploredSent.len, " explored cells, ", fails, " failures" quit(if fails > 0: 1 else: 0) main()