1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298 | ;; ported-from: src/receipts.ts @ v1.2.0
;;
;; P2P leaderboards: co-signed score receipts, no server.
;;
;; At match end the host assembles a receipt {g, m, r, ts, n, sc[]} and the
;; players present co-sign it (each signature over the same canonical bytes).
;; A receipt counts only with ≥2 DISTINCT valid signatures from players who
;; appear in the score list — that blocks unilateral fabrication and score
;; tampering against non-colluding players, and nothing more. Colluding
;; identities (or one person, two browsers) can sign any score they like;
;; sybils are free. This is a scoreboard among friends, not anti-cheat.
;;
;; Persistence, deliberately not a replicated log:
;; - weekly: a public deterministic mailbox drop per game per ISO week — the
;; node's ring-buffer TTL IS the rolling window, garbage ages out alone;
;; - all-time: every player carries their own receipts (capped) and hubs
;; gossip-merge them opportunistically. Eventually-consistent, partial by
;; design.
(ns ardegazu.social.receipts
(:require [ardegazu.id.crypto :as id-crypto]
[ardegazu.id.identity :as id-identity]
[ardegazu.social.canon :as canon]
[ardegazu.social.consts :as consts]
[ardegazu.social.mailbox :as mailbox]
[shadow.cljs.modern :refer (defclass js-await)]))
(def ^:private MAX-RECEIPT-BYTES 4096)
(def ^:private MAX-PLAYERS 32)
(def MIN-SIGNERS 2)
(defn- sig-bytes-of [base]
(id-crypto/utf8 (str "lb-receipt|v1|" (canon/canon base))))
(defn room-hash [room-id]
(.then (canon/sha256-b64url (str "lbroom|" room-id))
(fn [h] (.slice h 0 22))))
(defn receipt-hash [rec]
(canon/sha256-b64url
(canon/canon (js-obj "v" (unchecked-get rec "v")
"g" (unchecked-get rec "g")
"m" (unchecked-get rec "m")
"r" (unchecked-get rec "r")
"ts" (unchecked-get rec "ts")
"n" (unchecked-get rec "n")
"sc" (unchecked-get rec "sc")))))
;; receipts.ts had its own local btoa-based b64url for signatures — output
;; identical to id-kit's toB64url; kept local for fidelity.
(defn- b64url [b]
(let [n (.-length ^js b)]
(loop [i 0 s ""]
(if (< i n)
(recur (inc i) (str s (js/String.fromCharCode (aget b i))))
(-> (js/btoa s)
(.replaceAll "+" "-")
(.replaceAll "/" "_")
(.replace #"=+$" ""))))))
(defn sign-receipt [identity base]
(js-await [s (.signRaw ^js identity (sig-bytes-of base))]
(js-obj "p" (unchecked-get identity "publicKeyB64")
"s" (b64url s))))
;; signature loop: distinct signers who appear in sc, each verified
(defn- verify-sigs [sigs i pubs signers bytes]
(if (>= i (.-length ^js sigs))
(js/Promise.resolve signers)
(let [s (aget sigs i)
p (when (some? s) (unchecked-get s "p"))
sv (when (some? s) (unchecked-get s "s"))]
(if (or (nil? s) (not (string? p)) (not (string? sv))
(.has ^js signers p) (not (.has ^js pubs p))) ; distinct + must appear in sc
(verify-sigs sigs (inc i) pubs signers bytes)
(js-await [ok (id-identity/verify-raw p sv bytes)]
(when ok (.add ^js signers p))
(verify-sigs sigs (inc i) pubs signers bytes))))))
(defn verify-receipt
"Full verification; null = reject. Resolves {rec, hash} (dedup hash) or null."
[raw opts]
(-> (js/Promise.resolve nil)
(.then
(fn [_]
(let [opts (if (identical? opts js/undefined) (js-obj) opts)
rec raw]
(if (or (nil? rec)
(not (identical? (js* "typeof ~{}" rec) "object"))
(not (identical? 1 (unchecked-get rec "v"))))
nil
(let [size-ok (try (<= (.-length (js/JSON.stringify rec)) MAX-RECEIPT-BYTES)
(catch :default _ false))]
(if-not size-ok
nil
(let [g (unchecked-get rec "g")
m (unchecked-get rec "m")
r (unchecked-get rec "r")
ts (unchecked-get rec "ts")
n (unchecked-get rec "n")
sc (unchecked-get rec "sc")
sig (unchecked-get rec "sig")
now (js/Date.now)
max-score (unchecked-get opts "maxScore")
max-age (unchecked-get opts "maxAgeMs")]
(if (or (not (string? g)) (not (string? m)) (not (string? r))
(not (number? ts)) (not (js/Number.isFinite ts))
(not (number? n))
(not (js/Array.isArray sc)) (not (js/Array.isArray sig))
(zero? (.-length ^js sc))
(> (.-length ^js sc) MAX-PLAYERS)
(> (.-length ^js sig) MAX-PLAYERS)
(> ts (+ now 300000)) ; never from the future
(and (not (identical? max-age js/undefined)) (< ts (- now max-age))))
nil
(let [pubs (js/Set.)
sc-ok (loop [i 0]
(if (>= i (.-length ^js sc))
true
(let [e (aget sc i)
p (when (some? e) (unchecked-get e "p"))
s (when (some? e) (unchecked-get e "s"))]
(cond
(or (nil? e) (not (string? p))
(not (number? s)) (not (js/Number.isFinite s)))
false
(.has pubs p) false ; duplicate player
(and (not (identical? max-score js/undefined))
(or (> s max-score) (< s (- max-score))))
false
:else (do (.add pubs p) (recur (inc i)))))))]
(if-not sc-ok
nil
(let [base (js-obj "v" 1 "g" g "m" m "r" r "ts" ts "n" n "sc" sc)
bytes (sig-bytes-of base)]
(js-await [signers (verify-sigs sig 0 pubs (js/Set.) bytes)]
(if (< (.-size ^js signers) MIN-SIGNERS)
nil
(js-await [h (receipt-hash base)]
(js-obj "rec" rec "hash" h)))))))))))))))))
;; ---- weekly drop + gossip derivations ---------------------------------------
(defn iso-week
"ISO week (\"2026-W35\") of a timestamp — the weekly leaderboard's bucket."
[ts]
(let [d (js/Date. ts)
day (js/Date. (js/Date.UTC (.getUTCFullYear d) (.getUTCMonth d) (.getUTCDate d)))
dow (let [x (.getUTCDay day)] (if (zero? x) 7 x))]
;; Thursday decides the week-year
(.setUTCDate day (+ (.getUTCDate day) (- 4 dow)))
(let [year-start (js/Date.UTC (.getUTCFullYear day) 0 1)
week (js/Math.ceil (/ (+ (/ (- (.getTime day) year-start) 86400000) 1) 7))]
(str (.getUTCFullYear day) "-W" (.padStart (str week) 2 "0")))))
(defn lb-room-id [g week]
(canon/sha256-b64url (str "lb|v1|" g "|" week)))
(defn lb-topic [g]
(.then (canon/sha256-b64url (str "lb-topic|v1|" g))
(fn [h] (str "lb/1/" (.slice h 0 22)))))
(defn deposit-receipt
"Deposit a receipt into this week's public drop (plaintext — it's signed, public data)."
[rec]
(-> (js/Promise.resolve nil)
(.then (fn [_]
(js-await [room (lb-room-id (unchecked-get rec "g") (iso-week (unchecked-get rec "ts")))]
(js-await [mbx (mailbox/mailbox-for room)]
(js-await [res (.deposit ^js mbx (id-crypto/utf8 (js/JSON.stringify rec)))]
(unchecked-get res "ok"))))))
(.catch (fn [_] false))))
;; One receipt per (game, room, 10-min bucket): blocks re-rolling one match.
(defn- has-reroll-of? [seen rec]
(let [bucket (js/Math.floor (/ (unchecked-get rec "ts") 600000))
vals (js/Array.from (.values ^js seen))]
(loop [i 0]
(if (>= i (.-length vals))
false
(let [r (aget vals i)]
(if (and (identical? (unchecked-get r "g") (unchecked-get rec "g"))
(identical? (unchecked-get r "r") (unchecked-get rec "r"))
(identical? (js/Math.floor (/ (unchecked-get r "ts") 600000)) bucket))
true
(recur (inc i))))))))
(defn- fetch-weekly-messages [msgs i out opts state]
;; sequential verify of one replay page's messages; `state` carries the cursor
(if (>= i (.-length ^js msgs))
(js/Promise.resolve nil)
(let [m (aget msgs i)]
(unchecked-set state "cursor" (unchecked-get m "seq"))
(-> (js/Promise.resolve nil)
(.then (fn [_]
(let [parsed (js/JSON.parse (js/atob (unchecked-get m "payload")))
vopts (js/Object.assign (js-obj "maxAgeMs" (* 8 86400000)) opts)]
(js-await [v (verify-receipt parsed vopts)]
(when (and (some? v)
(not (.has ^js out (unchecked-get v "hash")))
(not (has-reroll-of? out (unchecked-get v "rec"))))
(.set ^js out (unchecked-get v "hash") (unchecked-get v "rec")))
nil))))
(.catch (fn [_] nil)) ; garbage deposit
(.then (fn [_] (fetch-weekly-messages msgs (inc i) out opts state)))))))
(defn- fetch-weekly-pages [mbx page out opts state]
(if (>= page 20)
(js/Promise.resolve nil)
(js-await [r (.replay ^js mbx (unchecked-get state "cursor") 100)]
(if-not ^boolean (unchecked-get r "ok")
nil
(let [pg (unchecked-get r "page")]
(js-await [_ (fetch-weekly-messages (unchecked-get pg "messages") 0 out opts state)]
(if ^boolean (unchecked-get pg "hasMore")
(fetch-weekly-pages mbx (inc page) out opts state)
nil)))))))
(defn fetch-weekly
"Replay + verify a week's drop. Best-effort, capped pages."
[g week opts]
(let [opts (if (identical? opts js/undefined) (js-obj) opts)
out (js/Map.)]
(-> (js/Promise.resolve nil)
(.then (fn [_]
(js-await [room (lb-room-id g week)]
(js-await [mbx (mailbox/mailbox-for room)]
(fetch-weekly-pages mbx 0 out opts (js-obj "cursor" nil))))))
(.catch (fn [_] nil)) ; offline
(.then (fn [_] (js/Array.from (.values out)))))))
;; ---- carried set (all-time, per browser) ------------------------------------
(defclass ReceiptSet
(constructor [this ns]
(unchecked-set this "_key" (str ns ":soc:receipts"))
(unchecked-set this "_recs" (js/Map.))
(try
(let [raw (js/JSON.parse (or (js/localStorage.getItem (unchecked-get this "_key")) "[]"))]
(when (js/Array.isArray raw)
(dotimes [i (.-length ^js raw)]
(let [rec (aget raw i)]
(when (and (some? rec) (identical? 1 (unchecked-get rec "v")))
(.set ^js (unchecked-get this "_recs")
(str (unchecked-get rec "g") "|" (unchecked-get rec "r") "|" (unchecked-get rec "ts"))
rec))))))
(catch :default _ nil)))) ; fresh
(defn- receipt-set-add [self rec]
(js-await [key (receipt-hash rec)]
(let [recs ^js (unchecked-get self "_recs")]
(if (.has recs key)
false
(if (has-reroll-of? recs rec)
false
(do
(.set recs key rec)
(let [list (-> (js/Array.from (.entries recs))
(.sort (fn [a b] (- (unchecked-get (aget b 1) "ts")
(unchecked-get (aget a 1) "ts"))))
(.slice 0 consts/RECEIPTS-CAP))]
(unchecked-set self "_recs" (js/Map. list))
(try
(js/localStorage.setItem (unchecked-get self "_key")
(js/JSON.stringify (.map list (fn [e] (aget e 1)))))
(catch :default _ nil)) ; private mode
true)))))))
(let [proto (.-prototype ReceiptSet)]
(unchecked-set proto "all"
(fn []
(this-as self
(js/Array.from (.values ^js (unchecked-get self "_recs"))))))
;; Add a VERIFIED receipt (call verifyReceipt first).
(unchecked-set proto "add"
(fn [rec]
(this-as self (receipt-set-add self rec)))))
(defn aggregate
"Fold receipts into a top list (per player: best single score, totals)."
[recs]
(let [rows (js/Map.)]
(dotimes [i (.-length ^js recs)]
(let [rec (aget recs i)
sc (unchecked-get rec "sc")]
(dotimes [j (.-length ^js sc)]
(let [e (aget sc j)
p (unchecked-get e "p")
row (or (.get rows p)
(js-obj "pub" p "name" "" "best" js/Number.NEGATIVE_INFINITY
"total" 0 "plays" 0))]
(unchecked-set row "best" (js/Math.max (unchecked-get row "best") (unchecked-get e "s")))
(unchecked-set row "total" (+ (unchecked-get row "total") (unchecked-get e "s")))
(unchecked-set row "plays" (inc (unchecked-get row "plays")))
(when ^boolean (js* "!!(~{})" (unchecked-get e "nm"))
(unchecked-set row "name" (.slice ^js (unchecked-get e "nm") 0 32)))
(.set rows p row)))))
(-> (js/Array.from (.values rows))
(.sort (fn [a b] (- (unchecked-get b "best") (unchecked-get a "best")))))))
|