WIP ring code: qr-anchored prototype, encoder, bench, lab pages

This commit is contained in:
2026-08-16 18:00:24 +01:00
parent 07137d8b15
commit d507190b11
12 changed files with 811 additions and 0 deletions
+3
View File
@@ -14,3 +14,6 @@ dev = [
"httpx>=0.28.1", "httpx>=0.28.1",
"pytest>=9.2.0", "pytest>=9.2.0",
] ]
[tool.pytest.ini_options]
pythonpath = ["."]
+105
View File
@@ -0,0 +1,105 @@
"""ring code: a static qr in the middle (opens the page, anchors geometry) plus rotating rings of dashes
that carry the time token. layout and bit order must match static/js/ringcode.js exactly.
payload = slot mod 2^16 (2 bytes) + first 4 bytes of the token hmac, reed-solomon(12, 6) over gf(256),
whitened, spread over 3 data rings. the inner ring is a fixed sync pattern used to find the rotation."""
import hmac
SYNC = "010001100101001000111111" # 24 sectors, min distance 12 to any of its rotations
RING_SECTORS = (24, 28, 32, 36) # ring 0 is sync, 1..3 carry 96 data bits
NSYM = 6 # rs parity bytes, fixes up to 3 bad bytes
SLOT_BITS = 16
_EXP = [0] * 512
_LOG = [0] * 256
_x = 1
for _i in range(255):
_EXP[_i] = _x
_LOG[_x] = _i
_x <<= 1
if _x & 0x100:
_x ^= 0x11D
for _i in range(255, 512):
_EXP[_i] = _EXP[_i - 255]
def _mul(a, b):
return 0 if a == 0 or b == 0 else _EXP[_LOG[a] + _LOG[b]]
def _generator(nsym):
g = [1]
for i in range(nsym):
# g *= (x - a^i), coefficients highest degree first
ng = [0] * (len(g) + 1)
for j, c in enumerate(g):
ng[j] ^= c
ng[j + 1] ^= _mul(c, _EXP[i])
g = ng
return g
_GEN = _generator(NSYM)
def rs_encode(msg: bytes) -> bytes:
rem = [0] * NSYM
for byte in msg:
f = byte ^ rem[0]
rem = rem[1:] + [0]
if f:
for j in range(NSYM):
rem[j] ^= _mul(_GEN[j + 1], f)
return bytes(msg) + bytes(rem)
def whitening(n):
"""16-bit galois lfsr, same sequence as the js side"""
lfsr, out = 0xACE1, []
for _ in range(n):
bit = lfsr & 1
lfsr >>= 1
if bit:
lfsr ^= 0xB400
out.append(bit)
return out
def mac32(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> bytes:
msg = f"{poll_id}:{interval_ms}:{slot}".encode()
return hmac.new(secret, msg, "sha256").digest()[:4]
def payload(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> bytes:
return (slot & 0xFFFF).to_bytes(2, "big") + mac32(secret, poll_id, interval_ms, slot)
def data_bits(codeword: bytes) -> str:
bits = [(b >> (7 - k)) & 1 for b in codeword for k in range(8)]
return "".join(str(b ^ w) for b, w in zip(bits, whitening(len(bits))))
def render_bits(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
"""what the projector draws: sync ring then the 96 data sectors, ring by ring"""
return SYNC + data_bits(rs_encode(payload(secret, poll_id, interval_ms, slot)))
def token(secret: bytes, poll_id: str, interval_ms: int, slot: int) -> str:
"""the compact token the phone sends after decoding: r<slot16>.<mac hex>"""
return f"r{slot & 0xFFFF}.{mac32(secret, poll_id, interval_ms, slot).hex()}"
def resolve(secret: bytes, poll_id: str, interval_ms: int, tok: str, now_slot: int, back: int) -> int | None:
"""full slot of a ring token if it matches one of the last `back` slots, else None"""
try:
s16, mac = tok[1:].split(".", 1)
s16 = int(s16)
given = bytes.fromhex(mac)
except (ValueError, IndexError):
return None
if len(given) != 4 or not 0 <= s16 <= 0xFFFF:
return None
for slot in range(now_slot, now_slot - back - 1, -1):
if slot & 0xFFFF == s16:
return slot if hmac.compare_digest(given, mac32(secret, poll_id, interval_ms, slot)) else None
return None
+360
View File
@@ -0,0 +1,360 @@
// ring code: static qr in the middle + rotating rings of dashes carrying the time token.
// layout, bit order and reed-solomon params must match rotatyvote/ringcode.py
// pure functions, no dom: runs in the browser and under node for the cross tests
export const SYNC = "010001100101001000111111";
export const RING_SECTORS = [24, 28, 32, 36];
// radii in units of the center qr side, qr centered on the origin
// tight rings leave more of the diameter to the center qr, which is the detection bottleneck
export const RADII = [0.9, 1.05, 1.2, 1.35];
export const THICK = 0.105;
export const DASH = 0.74; // part of a sector covered by the dash
export const DISC = 1.5; // background disc radius
const NSYM = 6;
// gf(256), poly 0x11d, generator 2
const EXP = new Uint8Array(512), LOG = new Uint8Array(256);
{
let x = 1;
for (let i = 0; i < 255; i++) { EXP[i] = x; LOG[x] = i; x <<= 1; if (x & 0x100) x ^= 0x11d; }
for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];
}
const mul = (a, b) => (a && b ? EXP[LOG[a] + LOG[b]] : 0);
const div = (a, b) => (a ? EXP[(LOG[a] + 255 - LOG[b]) % 255] : 0);
const pow = (x, p) => EXP[(((LOG[x] * p) % 255) + 255) % 255];
const inv = (x) => EXP[255 - LOG[x]];
const polyScale = (p, x) => p.map((c) => mul(c, x));
const polyAdd = (p, q) => {
const r = new Array(Math.max(p.length, q.length)).fill(0);
for (let i = 0; i < p.length; i++) r[i + r.length - p.length] = p[i];
for (let i = 0; i < q.length; i++) r[i + r.length - q.length] ^= q[i];
return r;
};
const polyMul = (p, q) => {
const r = new Array(p.length + q.length - 1).fill(0);
for (let j = 0; j < q.length; j++) for (let i = 0; i < p.length; i++) r[i + j] ^= mul(p[i], q[j]);
return r;
};
const polyEval = (p, x) => { let y = p[0]; for (let i = 1; i < p.length; i++) y = mul(y, x) ^ p[i]; return y; };
let GEN = [1];
for (let i = 0; i < NSYM; i++) GEN = polyMul(GEN, [1, pow(2, i)]);
export function rsEncode(msg) {
const rem = new Array(NSYM).fill(0);
for (const byte of msg) {
const f = byte ^ rem[0];
rem.shift(); rem.push(0);
if (f) for (let j = 0; j < NSYM; j++) rem[j] ^= mul(GEN[j + 1], f);
}
return [...msg, ...rem];
}
// port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2)
export function rsDecode(cw) {
const n = cw.length;
const synd = [0];
for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i)));
if (Math.max(...synd) === 0) return cw.slice(0, n - NSYM);
let errLoc = [1], oldLoc = [1];
for (let i = 0; i < NSYM; i++) {
const K = i + 1;
let delta = synd[K];
for (let j = 1; j < errLoc.length; j++) delta ^= mul(errLoc[errLoc.length - 1 - j], synd[K - j]);
oldLoc = [...oldLoc, 0];
if (delta) {
if (oldLoc.length > errLoc.length) {
const newLoc = polyScale(oldLoc, delta);
oldLoc = polyScale(errLoc, inv(delta));
errLoc = newLoc;
}
errLoc = polyAdd(errLoc, polyScale(oldLoc, delta));
}
}
while (errLoc.length && errLoc[0] === 0) errLoc.shift();
const errs = errLoc.length - 1;
if (errs * 2 > NSYM) return null;
const rev = [...errLoc].reverse();
const errPos = [];
for (let i = 0; i < n; i++) if (polyEval(rev, pow(2, i)) === 0) errPos.push(n - 1 - i);
if (errPos.length !== errs) return null;
const coefPos = errPos.map((p) => n - 1 - p);
let eLoc = [1];
for (const i of coefPos) eLoc = polyMul(eLoc, polyAdd([1], [pow(2, i), 0]));
// error evaluator: (synd reversed * eLoc) mod x^(len)
const prod = polyMul([...synd].reverse(), eLoc);
const evalLen = eLoc.length;
const errEval = prod.slice(prod.length - evalLen).reverse();
const X = coefPos.map((c) => pow(2, -(255 - c)));
const E = new Array(n).fill(0);
X.forEach((Xi, i) => {
const XiInv = inv(Xi);
let prime = 1;
X.forEach((Xj, j) => { if (j !== i) prime = mul(prime, 1 ^ mul(XiInv, Xj)); });
if (!prime) return;
const y = mul(Xi, polyEval([...errEval].reverse(), XiInv));
E[errPos[i]] = div(y, prime);
});
const fixed = cw.map((c, i) => c ^ E[i]);
for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null;
return fixed.slice(0, n - NSYM);
}
export function whitening(n) {
let lfsr = 0xace1;
const out = [];
for (let i = 0; i < n; i++) { const bit = lfsr & 1; lfsr >>= 1; if (bit) lfsr ^= 0xb400; out.push(bit); }
return out;
}
export function dataBits(codeword) {
const bits = [];
for (const b of codeword) for (let k = 7; k >= 0; k--) bits.push((b >> k) & 1);
const w = whitening(bits.length);
return bits.map((b, i) => b ^ w[i]).join("");
}
export function bytesFromBits(bits) {
const w = whitening(bits.length);
const out = [];
for (let i = 0; i < bits.length; i += 8) {
let v = 0;
for (let k = 0; k < 8; k++) v = (v << 1) | (bits[i + k] ^ w[i + k]);
out.push(v);
}
return out;
}
export function tokenFromPayload(p) {
const slot = (p[0] << 8) | p[1];
return `r${slot}.${p.slice(2).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
}
// splits the 120 render bits into rings
export function ringsOf(bits) {
const rings = [];
let k = 0;
for (const n of RING_SECTORS) { rings.push(bits.slice(k, k + n)); k += n; }
return rings;
}
const sectorAngle = (theta, j, n) => theta + ((j + 0.5) * 2 * Math.PI) / n;
// ---- drawing (projector + bench) ----
export function render(ctx, cx, cy, side, theta, bits, modules, colors = {}) {
const ink = colors.ink || "#1c2036", gray = colors.gray || "#a7acbd";
ctx.fillStyle = colors.disc || "#eef0f6";
ctx.beginPath(); ctx.arc(cx, cy, DISC * side, 0, 2 * Math.PI); ctx.fill();
if (modules) {
const n = modules.length, q = 2, s = side / n;
ctx.fillStyle = "#fff";
ctx.fillRect(cx - side / 2 - q * s, cy - side / 2 - q * s, side + 2 * q * s, side + 2 * q * s);
ctx.fillStyle = "#000";
for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
if (modules[y][x] === "1") ctx.fillRect(cx - side / 2 + x * s, cy - side / 2 + y * s, s + 0.5, s + 0.5);
}
}
const rings = ringsOf(bits);
ctx.lineCap = "round";
ctx.lineWidth = THICK * side;
rings.forEach((ring, k) => {
const n = ring.length, r = RADII[k] * side, step = (2 * Math.PI) / n;
// round caps stick out by half the stroke, take that off the arc
const cap = (THICK * side) / 2 / r;
const half = Math.max(0.01, (step * DASH) / 2 - cap);
for (let j = 0; j < n; j++) {
const a = sectorAngle(theta, j, n) - Math.PI / 2;
ctx.strokeStyle = ring[j] === "1" ? ink : gray;
ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke();
}
});
}
// ---- decoding (phone) ----
// homography mapping the unit qr square (-.5..+.5) onto the 4 detected corners (tl, tr, br, bl)
export function homography(c) {
const src = [[-0.5, -0.5], [0.5, -0.5], [0.5, 0.5], [-0.5, 0.5]];
const A = [], B = [];
for (let i = 0; i < 4; i++) {
const [x, y] = src[i], { x: u, y: v } = c[i];
A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); B.push(u);
A.push([0, 0, 0, x, y, 1, -v * x, -v * y]); B.push(v);
}
// gaussian elimination 8x8
for (let i = 0; i < 8; i++) {
let p = i;
for (let r = i + 1; r < 8; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
if (Math.abs(A[i][i]) < 1e-12) return null;
for (let r = 0; r < 8; r++) if (r !== i) {
const f = A[r][i] / A[i][i];
for (let k = i; k < 8; k++) A[r][k] -= f * A[i][k];
B[r] -= f * B[i];
}
}
const h = B.map((b, i) => b / A[i][i]);
return (x, y) => { const w = h[6] * x + h[7] * y + 1; return [(h[0] * x + h[1] * y + h[2]) / w, (h[3] * x + h[4] * y + h[5]) / w]; };
}
export function grayOf(imageData) {
const { data, width, height } = imageData, g = new Float32Array(width * height);
for (let i = 0, j = 0; i < g.length; i++, j += 4) g[i] = 0.299 * data[j] + 0.587 * data[j + 1] + 0.114 * data[j + 2];
return { g, w: width, h: height };
}
function sampler(img, H) {
const { g, w, h } = img;
return (x, y) => {
const [u, v] = H(x, y);
if (!(u >= 0 && v >= 0 && u < w - 1 && v < h - 1)) return NaN;
const x0 = u | 0, y0 = v | 0, fx = u - x0, fy = v - y0, i = y0 * w + x0;
return (g[i] * (1 - fx) + g[i + 1] * fx) * (1 - fy) + (g[i + w] * (1 - fx) + g[i + w + 1] * fx) * fy;
};
}
// mean brightness of one dash: a few points across its middle
function sector(S, r, a, step) {
let sum = 0, n = 0;
for (const dr of [-0.028, 0, 0.028]) for (const da of [-0.18, 0, 0.18]) {
const ang = a + da * step, rr = r + dr;
const v = S(rr * Math.sin(ang), -rr * Math.cos(ang));
if (!Number.isNaN(v)) { sum += v; n++; }
}
return n >= 6 ? sum / n : NaN;
}
const SYNC_BITS = [...SYNC].map(Number);
function corr(vals, bits) {
// dark (1) should be low: correlate values with -bit
const n = vals.length;
let mv = 0, mb = 0;
for (let i = 0; i < n; i++) { mv += vals[i]; mb += bits[i]; }
mv /= n; mb /= n;
let num = 0, dv = 0, db = 0;
for (let i = 0; i < n; i++) { const a = vals[i] - mv, b = -(bits[i] - mb); num += a * b; dv += a * a; db += b * b; }
return dv && db ? num / Math.sqrt(dv * db) : 0;
}
// otsu split of one ring: threshold + how well it separates (between-class / total variance)
function split(vals) {
const s = [...vals].sort((a, b) => a - b), n = s.length;
const total = s.reduce((a, b) => a + b, 0), mean = total / n;
const tv = s.reduce((a, v) => a + (v - mean) ** 2, 0) || 1;
let best = { quality: -1, thr: mean }, left = 0;
for (let i = 1; i < n; i++) {
left += s[i - 1];
const m0 = left / i, m1 = (total - left) / (n - i);
const q = (i * (n - i) * (m0 - m1) ** 2) / n / tv;
if (q > best.quality) best = { quality: q, thr: (s[i - 1] + s[i]) / 2 };
}
return best;
}
function solve(A, B) {
const n = B.length;
for (let i = 0; i < n; i++) {
let p = i;
for (let r = i + 1; r < n; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
if (Math.abs(A[i][i]) < 1e-12) return null;
for (let r = 0; r < n; r++) if (r !== i) {
const f = A[r][i] / A[i][i];
for (let k = i; k < n; k++) A[r][k] -= f * A[i][k];
B[r] -= f * B[i];
}
}
return B.map((b, i) => b / A[i][i]);
}
// the qr corners are a few px off and that error grows with the radius. the rings themselves are the
// better reference: find their dark bands along rays, fit one ellipse family, undo center/scale/shear
function refine(S) {
const rows = [];
const rays = 160, r0 = 0.72, r1 = 1.48, dr = 0.005;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
const prof = [];
for (let r = r0; r <= r1 + 1e-9; r += dr) prof.push(S(r * dx, r * dy));
if (prof.some(Number.isNaN)) continue;
const sorted = [...prof].sort((a, b) => a - b);
const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0];
if (bg - lo < 15) continue;
RADII.forEach((R, k) => {
const c = Math.round((R - r0) / dr), w = Math.round(0.065 / dr);
let m = -1;
for (let j = Math.max(1, c - w); j <= Math.min(prof.length - 2, c + w); j++) if (m < 0 || prof[j] < prof[m]) m = j;
if (m <= 0 || m >= prof.length - 1) return;
// a ray through a gap between dashes has no real dip, skip it
if (bg - prof[m] < 0.4 * (bg - lo)) return;
const a = prof[m - 1], b = prof[m], cc = prof[m + 1], den = a - 2 * b + cc;
const off = den > 0 ? (0.5 * (a - cc)) / den : 0;
const r = r0 + (m + Math.max(-1, Math.min(1, off))) * dr;
const x = r * dx, y = r * dy;
rows.push([x * x, x * y, y * y, x, y, 1, R * R]);
});
}
if (rows.length < 80) return null;
const N = Array.from({ length: 6 }, () => new Array(6).fill(0)), V = new Array(6).fill(0);
for (const row of rows) for (let i = 0; i < 6; i++) { V[i] += row[i] * row[6]; for (let j = 0; j < 6; j++) N[i][j] += row[i] * row[j]; }
const sol = solve(N, V);
if (!sol) return null;
const [a, b, c, d, e] = sol;
const det = a * c - (b * b) / 4;
if (!(a > 0 && det > 0)) return null;
// center: grad = 0 -> [2a b; b 2c] x = -[d e]
const x0 = (-d * 2 * c + e * b) / (4 * a * c - b * b), y0 = (-e * 2 * a + d * b) / (4 * a * c - b * b);
// cholesky of M = [[a, b/2], [b/2, c]] = A^T A, A upper triangular
const p = Math.sqrt(a), q = b / 2 / p, s = Math.sqrt(c - q * q);
if (!(s > 0) || Math.hypot(x0, y0) > 0.15 || Math.abs(Math.log(p * s)) > 0.25) return null;
// true ring space -> measured space: m = c0 + A^-1 t
const i11 = 1 / p, i12 = -q / (p * s), i22 = 1 / s;
return (x, y) => S(x0 + i11 * x + i12 * y, y0 + i22 * y);
}
// returns { token, theta, score, scale } or null
export function decode(img, corners, opts = {}) {
const H = homography(corners);
if (!H) return null;
const S = (opts.refine !== false && refine(sampler(img, H))) || sampler(img, H);
const steps = opts.steps || 360, minScore = opts.minScore ?? 0.8;
let best = null;
for (const scale of opts.scales || [0.94, 0.97, 1.0, 1.03, 1.06]) {
const r0 = RADII[0] * scale, n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0;
// full turn: the sync pattern has no rotational symmetry
for (let t = 0; t < steps; t++) {
const theta = (t / steps) * step0 * n0;
const vals = [];
for (let j = 0; j < n0; j++) vals.push(sector(S, r0, sectorAngle(theta, j, n0), step0));
if (vals.some(Number.isNaN)) return null;
const c = corr(vals, SYNC_BITS);
if (!best || c > best.score) best = { score: c, theta, scale, vals };
}
}
// weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise
if (!best || best.score < minScore) return best ? { token: null, ...best } : null;
const dark = [], light = [];
best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v));
const md = dark.reduce((a, b) => a + b) / dark.length, ml = light.reduce((a, b) => a + b) / light.length;
if (ml - md < 12) return { token: null, ...best };
const bits = [];
for (let k = 1; k < RING_SECTORS.length; k++) {
// corners come from the small center square, so outer rings drift under perspective:
// nudge scale and rotation per ring and keep the cleanest dark/light split
const n = RING_SECTORS[k], step = (2 * Math.PI) / n;
let pick = null;
for (const ds of [-0.03, -0.015, 0, 0.015, 0.03]) for (const dt of [-0.22, 0, 0.22]) {
const r = RADII[k] * best.scale * (1 + ds), vals = [];
for (let j = 0; j < n; j++) vals.push(sector(S, r, sectorAngle(best.theta + dt * step, j, n), step));
if (vals.some(Number.isNaN)) continue;
const sp = split(vals);
if (!pick || sp.quality > pick.quality) pick = { ...sp, vals };
}
if (!pick) return { token: null, ...best };
for (const v of pick.vals) bits.push(v < pick.thr ? 1 : 0);
}
const msg = rsDecode(bytesFromBits(bits));
return { ...best, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null };
}
+113
View File
@@ -0,0 +1,113 @@
<!doctype html>
<html lang="fr">
<head><meta charset="utf-8"><title>Ring code bench</title>
<script src="/static/vendor/qr-scanner.umd.min.js"></script>
<script type="module">
import { render, decode, grayOf, homography, DISC } from "/static/js/ringcode.js";
// warps canvas `src` onto a new w x h canvas so that src's unit square maps to quad `dst` (perspective)
function warp(src, dst, w, h, bg) {
const s = src.getContext("2d").getImageData(0, 0, src.width, src.height);
const sw = src.width, sh = src.height;
// homography from dst quad back to src rect corners
const srcPts = [[0, 0], [sw, 0], [sw, sh], [0, sh]];
const A = [], B = [];
for (let i = 0; i < 4; i++) {
const [x, y] = dst[i], [u, v] = srcPts[i];
A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); B.push(u);
A.push([0, 0, 0, x, y, 1, -v * x, -v * y]); B.push(v);
}
for (let i = 0; i < 8; i++) {
let p = i;
for (let r = i + 1; r < 8; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
for (let r = 0; r < 8; r++) if (r !== i) { const f = A[r][i] / A[i][i]; for (let k = i; k < 8; k++) A[r][k] -= f * A[i][k]; B[r] -= f * B[i]; }
}
const hm = B.map((b, i) => b / A[i][i]);
const out = document.createElement("canvas"); out.width = w; out.height = h;
const octx = out.getContext("2d"), od = octx.createImageData(w, h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
const ww = hm[6] * x + hm[7] * y + 1, u = (hm[0] * x + hm[1] * y + hm[2]) / ww, v = (hm[3] * x + hm[4] * y + hm[5]) / ww;
const o = (y * w + x) * 4;
if (u >= 0 && v >= 0 && u < sw - 1 && v < sh - 1) {
const x0 = u | 0, y0 = v | 0, fx = u - x0, fy = v - y0, i = (y0 * sw + x0) * 4;
for (let c = 0; c < 3; c++) {
od.data[o + c] = (s.data[i + c] * (1 - fx) + s.data[i + 4 + c] * fx) * (1 - fy) + (s.data[i + sw * 4 + c] * (1 - fx) + s.data[i + sw * 4 + 4 + c] * fx) * fy;
}
} else { od.data[o] = bg[0]; od.data[o + 1] = bg[1]; od.data[o + 2] = bg[2]; }
od.data[o + 3] = 255;
}
octx.putImageData(od, 0, 0);
return out;
}
// square of the code area, centred at (cx, cy) with diameter d, tilted by `tilt` deg around an axis at angle `axis`
function quad(cx, cy, d, tilt, axis) {
const t = tilt * Math.PI / 180, a = axis * Math.PI / 180, f = 1.6 * d;
const pts = [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([x, y]) => {
// rotate into axis frame, tilt around that axis, rotate back, perspective project
let X = x * Math.cos(a) + y * Math.sin(a), Y = -x * Math.sin(a) + y * Math.cos(a), Z = 0;
const Y2 = Y * Math.cos(t), Z2 = Y * Math.sin(t);
const xr = X * Math.cos(a) - Y2 * Math.sin(a), yr = X * Math.sin(a) + Y2 * Math.cos(a);
const s = f / (f + Z2 * d / 2);
return [cx + xr * d / 2 * s, cy + yr * d / 2 * s];
});
return pts;
}
window.runBench = async (cfg) => {
const engine = await QrScanner.createQrEngine();
QrScanner._disableBarcodeDetector = !!cfg.noBarcodeDetector;
const results = [];
const A = document.createElement("canvas"); A.width = A.height = 800;
const actx = A.getContext("2d");
for (const trial of cfg.trials) {
const side = A.width / (2 * DISC);
actx.fillStyle = "#f5f6fa"; actx.fillRect(0, 0, A.width, A.height);
render(actx, A.width / 2, A.height / 2, side, trial.theta, trial.bits, cfg.modules);
const q = quad(480 + trial.dx, 360 + trial.dy, trial.d, trial.tilt, trial.axis);
let B = warp(A, q, 960, 720, [60, 62, 74]);
const C = document.createElement("canvas"); C.width = 960; C.height = 720;
const cctx = C.getContext("2d");
cctx.filter = `blur(${trial.blur}px) contrast(${trial.contrast}) brightness(${trial.bright})`;
cctx.drawImage(B, 0, 0);
cctx.filter = "none";
if (trial.noise) {
const id = cctx.getImageData(0, 0, 960, 720);
for (let i = 0; i < id.data.length; i += 4) { const n = (Math.random() - 0.5) * 2 * trial.noise; id.data[i] += n; id.data[i + 1] += n; id.data[i + 2] += n; }
cctx.putImageData(id, 0, 0);
}
const t0 = performance.now();
let res = null, qr = false;
try { res = await QrScanner.scanImage(C, { qrEngine: engine, returnDetailedScanResult: true }); qr = true; } catch { /* no qr */ }
let out = { qr, token: null, score: null };
if (res) {
const d = decode(grayOf(cctx.getImageData(0, 0, 960, 720)), res.cornerPoints);
if (d) {
out = { qr, token: d.token, score: +d.score.toFixed(3), scale: d.scale };
if (d.bits) {
const truth = trial.bits.slice(24);
let k = 0; out.errs = [];
for (const n of [28, 32, 36]) { let e = 0; for (let j = 0; j < n; j++) e += d.bits[k + j] !== truth[k + j]; out.errs.push(e); k += n; }
}
}
}
// same decode with the exact qr corners, to tell corner error from decoder bugs
{
const Hq = homography(q.map(([x, y]) => ({ x, y })));
const hs = side / 2 / A.width;
const tc = [[-hs, -hs], [hs, -hs], [hs, hs], [-hs, hs]].map(([u, v]) => { const [x, y] = Hq(u, v); return { x, y }; });
const dt = decode(grayOf(cctx.getImageData(0, 0, 960, 720)), tc);
out.truthOk = !!dt && dt.token === trial.token;
if (res) out.cornerErr = +Math.max(...res.cornerPoints.map((p, i) => Math.hypot(p.x - tc[i].x, p.y - tc[i].y))).toFixed(2);
}
out.ms = Math.round(performance.now() - t0);
out.ok = out.token === trial.token;
results.push({ ...trial, bits: undefined, ...out });
if (cfg.keep && results.length <= cfg.keep) results[results.length - 1].png = C.toDataURL("image/jpeg", 0.8);
}
return results;
};
window.benchReady = true;
</script></head>
<body></body></html>
+14
View File
@@ -0,0 +1,14 @@
html, body { margin: 0; height: 100%; background: #f5f6fa; color: #1c2036; font: 16px/1.4 system-ui, -apple-system, sans-serif; }
#stage { position: fixed; inset: 0; width: 100%; height: 100%; }
.bar { position: fixed; left: 12px; bottom: 12px; display: flex; gap: 8px; flex-wrap: wrap; font-size: 13px; color: #8a8fa3; }
.bar a { color: #1c2036; background: #fff; border-radius: 99px; padding: 6px 12px; text-decoration: none; }
.bar a.on { background: #1c2036; color: #fff; }
.phone { padding: 16px; max-width: 520px; margin: 0 auto; }
.phone video { width: 100%; border-radius: 16px; background: #1c2036; aspect-ratio: 3/4; object-fit: cover; }
.big { font-size: 44px; font-weight: 800; letter-spacing: -.02em; margin: 6px 0; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin: 12px 0; }
.grid div { background: #fff; border-radius: 12px; padding: 10px 12px; }
.grid b { display: block; font-size: 22px; }
button { font: 600 16px system-ui; padding: 12px 18px; border-radius: 99px; border: 0; background: #ffcc00; color: #1c2036; width: 100%; margin-top: 8px; }
button.ghost { background: #fff; }
.hist { font-size: 14px; color: #4a4f66; }
File diff suppressed because one or more lines are too long
+20
View File
@@ -0,0 +1,20 @@
<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Labo code circulaire, téléphone</title><link rel="stylesheet" href="/static/ringlab/lab.css">
<script src="/static/vendor/qr-scanner.umd.min.js"></script>
<script type="module" src="/static/ringlab/phone.js"></script></head>
<body><main class="phone">
<video id="v" playsinline muted></video>
<div class="big" id="state">Prêt</div>
<div class="grid">
<div>Images analysées<b id="frames">0</b></div>
<div>Images par seconde<b id="fps">0</b></div>
<div>QR central détecté<b id="qr">0 %</b></div>
<div>Anneaux lus (si QR vu)<b id="ring">0 %</b></div>
<div>Codes distincts<b id="count">0 / 5</b></div>
<div>Mode vu<b id="mode">aucun</b></div>
</div>
<button id="go">Démarrer la caméra</button>
<button id="again" class="ghost">Nouvel essai</button>
<p class="hist" id="hist"></p>
</main></body></html>
+66
View File
@@ -0,0 +1,66 @@
import { decode, grayOf } from "/static/js/ringcode.js";
const $ = (id) => document.getElementById(id);
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
let engine, running = false, frames = 0, qr = 0, ring = 0, t0 = 0, fpsT = performance.now(), fpsN = 0;
let tokens = new Set(), mode = "aucun";
const history = [];
function reset() {
tokens = new Set(); t0 = performance.now(); frames = qr = ring = 0;
$("state").textContent = "Visez l'écran";
}
async function start() {
engine = await QrScanner.createQrEngine();
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 } },
});
video.srcObject = stream;
await video.play();
running = true;
reset();
loop();
}
async function loop() {
if (!running) return;
if (video.readyState >= 2) {
const k = Math.min(1, 1280 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
frames++; fpsN++;
let res = null;
try { res = await QrScanner.scanImage(canvas, { qrEngine: engine, returnDetailedScanResult: true }); } catch { /* none */ }
if (res) {
qr++;
if (res.data.includes("#")) {
mode = "QR classique";
tokens.add(res.data.split("#")[1]);
} else {
mode = "anneaux";
const d = decode(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)), res.cornerPoints);
if (d && d.token) { ring++; tokens.add(d.token); }
}
}
if (tokens.size >= 5 && t0) {
const s = (performance.now() - t0) / 1000;
history.push(s.toFixed(1));
$("state").textContent = `5 codes en ${s.toFixed(1)} s`;
$("hist").textContent = `Essais : ${history.join(" s, ")} s`;
t0 = 0;
}
const now = performance.now();
if (now - fpsT > 1000) { $("fps").textContent = (fpsN * 1000 / (now - fpsT)).toFixed(1); fpsT = now; fpsN = 0; }
$("frames").textContent = frames;
$("qr").textContent = `${Math.round((100 * qr) / Math.max(1, frames))} %`;
$("ring").textContent = mode === "anneaux" ? `${Math.round((100 * ring) / Math.max(1, qr))} %` : "–";
$("count").textContent = `${Math.min(tokens.size, 5)} / 5`;
$("mode").textContent = mode;
}
setTimeout(loop, 0);
}
$("go").addEventListener("click", () => start().catch((e) => { $("state").textContent = `Caméra : ${e.message}`; }));
$("again").addEventListener("click", reset);
+8
View File
@@ -0,0 +1,8 @@
<!doctype html>
<html lang="fr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Labo code circulaire, écran</title><link rel="stylesheet" href="/static/ringlab/lab.css">
<script type="module" src="/static/ringlab/screen.js"></script></head>
<body><canvas id="stage"></canvas>
<div class="bar"><a id="m-ring" href="?mode=ring">Anneaux</a><a id="m-qr" href="?mode=qr">QR classique</a>
<a id="i-1000" href="#">1 s</a><a id="i-500" href="#">0,5 s</a><span id="info"></span></div>
</body></html>
+42
View File
@@ -0,0 +1,42 @@
import { render, rsEncode, dataBits, SYNC, DISC } from "/static/js/ringcode.js";
const params = new URLSearchParams(location.search);
const MS = +params.get("ms") || 1000, MODE = params.get("mode") || "ring";
const lab = await fetch("/static/ringlab/lab.json").then((r) => r.json());
const cv = document.getElementById("stage"), ctx = cv.getContext("2d");
document.getElementById(`m-${MODE}`)?.classList.add("on");
for (const ms of [1000, 500]) {
const a = document.getElementById(`i-${ms}`);
a.href = `?mode=${MODE}&ms=${ms}`;
if (ms === MS) a.classList.add("on");
}
let slot = 0, bits = "", idx = 0;
function tick() {
slot = (slot + 1) & 0xffff;
const mac = [...crypto.getRandomValues(new Uint8Array(4))];
bits = SYNC + dataBits(rsEncode([(slot >> 8) & 255, slot & 255, ...mac]));
idx = (idx + 1) % lab.classic.length;
document.getElementById("info").textContent = MODE === "ring" ? `code ${slot}` : `code ${lab.classic[idx].token.split(".")[0].slice(-4)}`;
}
tick();
setInterval(tick, MS);
function frame(t) {
const dpr = devicePixelRatio || 1, w = innerWidth * dpr, h = innerHeight * dpr;
if (cv.width !== w || cv.height !== h) { cv.width = w; cv.height = h; }
ctx.fillStyle = "#f5f6fa"; ctx.fillRect(0, 0, w, h);
const size = Math.min(w, h) * 0.9;
if (MODE === "ring") {
// one full turn every 45 s
render(ctx, w / 2, h / 2, size / (2 * DISC), (t / 1000) * (2 * Math.PI / 45), bits, lab.center);
} else {
const m = lab.classic[idx].modules, n = m.length, s = Math.floor(size / (n + 8));
const x0 = (w - n * s) / 2, y0 = (h - n * s) / 2;
ctx.fillStyle = "#fff"; ctx.fillRect(x0 - 4 * s, y0 - 4 * s, (n + 8) * s, (n + 8) * s);
ctx.fillStyle = "#000";
for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) if (m[y][x] === "1") ctx.fillRect(x0 + x * s, y0 + y * s, s, s);
}
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
+24
View File
@@ -0,0 +1,24 @@
// cross check against vectors produced by the python encoder: node tests/ringcode_cross.mjs vectors.json
import { readFileSync } from "node:fs";
import { dataBits, rsEncode, rsDecode, bytesFromBits, tokenFromPayload, SYNC } from "../static/js/ringcode.js";
const vectors = JSON.parse(readFileSync(process.argv[2], "utf8"));
let fails = 0;
const fail = (m) => { fails++; console.log("FAIL", m); };
for (const v of vectors) {
const payload = [...Buffer.from(v.payload, "hex")];
const cw = rsEncode(payload);
if (Buffer.from(cw).toString("hex") !== v.codeword) fail(`rs encode ${v.codeword}`);
if (SYNC + dataBits(cw) !== v.bits) fail(`bits ${v.token}`);
const back = bytesFromBits([...v.bits.slice(SYNC.length)].map(Number));
const msg = rsDecode(back);
if (!msg || tokenFromPayload(msg) !== v.token) fail(`roundtrip ${v.token}`);
for (const c of v.corrupted) {
const m = rsDecode([...Buffer.from(c.cw, "hex")]);
const ok = m && tokenFromPayload(m) === v.token;
if (c.errors <= 3 && !ok) fail(`fix ${c.errors} errors ${v.token}`);
if (c.errors > 3 && ok) console.log("note: decoded beyond capacity", c.errors);
}
}
console.log(fails ? `${fails} failures` : `ok ${vectors.length} vectors`);
process.exit(fails ? 1 : 0);
+55
View File
@@ -0,0 +1,55 @@
import json
import random
import shutil
import subprocess
from pathlib import Path
import pytest
from rotatyvote import ringcode
ROOT = Path(__file__).resolve().parent.parent
def test_resolve_accepts_recent_and_rejects_others():
secret, pid, iv = b"k" * 32, "abcd2345", 1000
now = 3_000_000_123
for back in range(0, 4):
tok = ringcode.token(secret, pid, iv, now - back)
assert ringcode.resolve(secret, pid, iv, tok, now, 3) == now - back
assert ringcode.resolve(secret, pid, iv, ringcode.token(secret, pid, iv, now - 5), now, 3) is None # stale
assert ringcode.resolve(secret, "otherpid", iv, ringcode.token(secret, pid, iv, now), now, 3) is None
assert ringcode.resolve(b"x" * 32, pid, iv, ringcode.token(secret, pid, iv, now), now, 3) is None
assert ringcode.resolve(secret, pid, iv, "r12.zz", now, 3) is None
# slot16 wraps every 65536 slots: a token from one wrap ago must not match
assert ringcode.resolve(secret, pid, iv, ringcode.token(secret, pid, iv, now - 65536), now, 3) is None
def test_bit_layout():
bits = ringcode.render_bits(b"s" * 32, "pid", 500, 42)
assert len(bits) == sum(ringcode.RING_SECTORS) == 120
assert bits.startswith(ringcode.SYNC)
@pytest.mark.skipif(shutil.which("node") is None, reason="node not installed")
def test_cross_vectors_with_js(tmp_path):
rng = random.Random(5)
vectors = []
for _ in range(60):
secret = rng.randbytes(32)
pid = "".join(rng.choice("abcdefghjk23456789") for _ in range(8))
slot = rng.randrange(1 << 40)
payload = ringcode.payload(secret, pid, 1000, slot)
cw = ringcode.rs_encode(payload)
corrupted = []
for nerr in (1, 2, 3, 4):
c = bytearray(cw)
for pos in rng.sample(range(len(c)), nerr):
c[pos] ^= rng.randrange(1, 256)
corrupted.append({"errors": nerr, "cw": c.hex()})
vectors.append({"payload": payload.hex(), "codeword": cw.hex(), "token": ringcode.token(secret, pid, 1000, slot),
"bits": ringcode.render_bits(secret, pid, 1000, slot), "corrupted": corrupted})
f = tmp_path / "vectors.json"
f.write_text(json.dumps(vectors))
r = subprocess.run(["node", str(ROOT / "tests" / "ringcode_cross.mjs"), str(f)], capture_output=True, text=True)
assert r.returncode == 0, r.stdout + r.stderr