prizerail 0.0.1 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +126 -3
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +60 -0
- package/dist/client.d.ts +127 -0
- package/dist/client.js +258 -0
- package/dist/entrant.d.ts +7 -0
- package/dist/entrant.js +14 -0
- package/dist/errors.d.ts +36 -0
- package/dist/errors.js +42 -0
- package/dist/http.d.ts +35 -0
- package/dist/http.js +138 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/types.d.ts +169 -0
- package/dist/types.js +2 -0
- package/dist/verify-draw.d.mts +15 -0
- package/dist/verify-draw.mjs +786 -0
- package/dist/verify.d.ts +64 -0
- package/dist/verify.js +69 -0
- package/package.json +34 -5
- package/cli.mjs +0 -4
|
@@ -0,0 +1,786 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Prizerail draw verifier. Checks a draw's proof without trusting Prizerail's
|
|
4
|
+
* servers: it recomputes every number from the proof's inputs and reports any
|
|
5
|
+
* that don't match.
|
|
6
|
+
*
|
|
7
|
+
* node verify-draw.mjs <proof.json file or link>
|
|
8
|
+
*
|
|
9
|
+
* Needs Node.js 18 or later and nothing else. The hashing is written out
|
|
10
|
+
* below so there's nothing to install; it checks itself against published
|
|
11
|
+
* keccak256 test values before it runs. To cross-check with a library you
|
|
12
|
+
* already trust, viem's keccak256 and encodeAbiParameters give the same
|
|
13
|
+
* results.
|
|
14
|
+
*
|
|
15
|
+
* What it checks, in the order a draw happens. It's the same math the
|
|
16
|
+
* Prizerail contract runs onchain:
|
|
17
|
+
*
|
|
18
|
+
* 1. The prize table's rolls add up: tier weights sum to the denominator,
|
|
19
|
+
* tiers run top prize first, and each threshold is the running total.
|
|
20
|
+
* 2. The entrant list's root: an OpenZeppelin StandardMerkleTree over
|
|
21
|
+
* (uint256 index, bytes32 keccak256(bytes(entrantId)), uint64 weight).
|
|
22
|
+
* The tree sorts its leaves, so the root is a commitment to the set of
|
|
23
|
+
* entries, and the index is the only order: rows are sorted by index,
|
|
24
|
+
* and the indices must run exactly 0 to count - 1. A shuffled list gives
|
|
25
|
+
* the same root and the same winners.
|
|
26
|
+
* 3. Each winner slot j's selection value: the first
|
|
27
|
+
* keccak256(abi.encode(bytes32 entropy, bytes32 campaignId,
|
|
28
|
+
* uint64 drawingNumber, bytes32 "prizerail.entrant", uint256 j, uint256 k))
|
|
29
|
+
* at or above 2^256 mod the weight of the entrants not picked yet. The
|
|
30
|
+
* pick is that value mod the same weight, and the winner is the entrant
|
|
31
|
+
* whose range holds it, counting the ones still in, in index order. They
|
|
32
|
+
* sit out later slots.
|
|
33
|
+
* 4. Each winner's ID hashes to the entry the pick landed on.
|
|
34
|
+
* 5. Each winner's random value is the first
|
|
35
|
+
* keccak256(abi.encode(bytes32 entropy, bytes32 campaignId,
|
|
36
|
+
* uint64 drawingNumber, uint256 position, uint256 k)) for k = 0, 1, …
|
|
37
|
+
* that is at least 2^256 mod denominator. The campaign ID is ASCII,
|
|
38
|
+
* right-padded to 32 bytes. In practice k is always 0.
|
|
39
|
+
* 6. Their roll is random value mod denominator, 0 to denominator - 1.
|
|
40
|
+
* 7. The prize is the first tier whose threshold is above the roll.
|
|
41
|
+
* 8. The top prize is won at most once per draw. If two or more winners roll
|
|
42
|
+
* it, the one with the lowest random value keeps it and the others get
|
|
43
|
+
* the second prize. Only the top tier works this way.
|
|
44
|
+
*
|
|
45
|
+
* The list comes from the proof's entrantList.url, in pages, or a file:
|
|
46
|
+
*
|
|
47
|
+
* node verify-draw.mjs <proof.json> [entrants.json file or link]
|
|
48
|
+
*
|
|
49
|
+
* Note: Python's hashlib.sha3_256 is NOT keccak256. They pad differently and
|
|
50
|
+
* give different hashes, so a check written with it will always fail.
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/* ---------- keccak256 ---------- */
|
|
54
|
+
|
|
55
|
+
const MASK = (1n << 64n) - 1n;
|
|
56
|
+
|
|
57
|
+
const ROUND_CONSTANTS = [
|
|
58
|
+
0x0000000000000001n,
|
|
59
|
+
0x0000000000008082n,
|
|
60
|
+
0x800000000000808an,
|
|
61
|
+
0x8000000080008000n,
|
|
62
|
+
0x000000000000808bn,
|
|
63
|
+
0x0000000080000001n,
|
|
64
|
+
0x8000000080008081n,
|
|
65
|
+
0x8000000000008009n,
|
|
66
|
+
0x000000000000008an,
|
|
67
|
+
0x0000000000000088n,
|
|
68
|
+
0x0000000080008009n,
|
|
69
|
+
0x000000008000000an,
|
|
70
|
+
0x000000008000808bn,
|
|
71
|
+
0x800000000000008bn,
|
|
72
|
+
0x8000000000008089n,
|
|
73
|
+
0x8000000000008003n,
|
|
74
|
+
0x8000000000008002n,
|
|
75
|
+
0x8000000000000080n,
|
|
76
|
+
0x000000000000800an,
|
|
77
|
+
0x800000008000000an,
|
|
78
|
+
0x8000000080008081n,
|
|
79
|
+
0x8000000000008080n,
|
|
80
|
+
0x0000000080000001n,
|
|
81
|
+
0x8000000080008008n,
|
|
82
|
+
];
|
|
83
|
+
|
|
84
|
+
// Rotation for lane (x, y), indexed x + 5y.
|
|
85
|
+
const ROTATIONS = [
|
|
86
|
+
0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18,
|
|
87
|
+
2, 61, 56, 14,
|
|
88
|
+
];
|
|
89
|
+
|
|
90
|
+
const rotl = (lane, n) =>
|
|
91
|
+
n === 0 ? lane : ((lane << BigInt(n)) | (lane >> BigInt(64 - n))) & MASK;
|
|
92
|
+
|
|
93
|
+
function keccakF(state) {
|
|
94
|
+
for (const rc of ROUND_CONSTANTS) {
|
|
95
|
+
// Theta
|
|
96
|
+
const c = [0, 1, 2, 3, 4].map(
|
|
97
|
+
x =>
|
|
98
|
+
state[x] ^ state[x + 5] ^ state[x + 10] ^ state[x + 15] ^ state[x + 20]
|
|
99
|
+
);
|
|
100
|
+
for (let x = 0; x < 5; x++) {
|
|
101
|
+
const d = c[(x + 4) % 5] ^ rotl(c[(x + 1) % 5], 1);
|
|
102
|
+
for (let y = 0; y < 25; y += 5) state[x + y] ^= d;
|
|
103
|
+
}
|
|
104
|
+
// Rho and pi
|
|
105
|
+
const b = new Array(25);
|
|
106
|
+
for (let x = 0; x < 5; x++) {
|
|
107
|
+
for (let y = 0; y < 5; y++) {
|
|
108
|
+
b[y + 5 * ((2 * x + 3 * y) % 5)] = rotl(
|
|
109
|
+
state[x + 5 * y],
|
|
110
|
+
ROTATIONS[x + 5 * y]
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
// Chi
|
|
115
|
+
for (let y = 0; y < 25; y += 5) {
|
|
116
|
+
for (let x = 0; x < 5; x++) {
|
|
117
|
+
state[x + y] =
|
|
118
|
+
b[x + y] ^ (~b[((x + 1) % 5) + y] & MASK & b[((x + 2) % 5) + y]);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
// Iota
|
|
122
|
+
state[0] ^= rc;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** keccak256 as Ethereum and Solidity use it. Bytes in, 0x hex out. */
|
|
127
|
+
export function keccak256(bytes) {
|
|
128
|
+
const rate = 136;
|
|
129
|
+
// Keccak padding: 0x01, zeros, then 0x80 on the last byte of the block.
|
|
130
|
+
const padded = new Uint8Array(Math.floor(bytes.length / rate) * rate + rate);
|
|
131
|
+
padded.set(bytes);
|
|
132
|
+
padded[bytes.length] ^= 0x01;
|
|
133
|
+
padded[padded.length - 1] ^= 0x80;
|
|
134
|
+
const state = new Array(25).fill(0n);
|
|
135
|
+
for (let block = 0; block < padded.length; block += rate) {
|
|
136
|
+
for (let i = 0; i < rate / 8; i++) {
|
|
137
|
+
let lane = 0n;
|
|
138
|
+
for (let j = 7; j >= 0; j--) {
|
|
139
|
+
lane = (lane << 8n) | BigInt(padded[block + i * 8 + j]);
|
|
140
|
+
}
|
|
141
|
+
state[i] ^= lane;
|
|
142
|
+
}
|
|
143
|
+
keccakF(state);
|
|
144
|
+
}
|
|
145
|
+
let hex = "0x";
|
|
146
|
+
for (let i = 0; i < 4; i++) {
|
|
147
|
+
for (let j = 0; j < 8; j++) {
|
|
148
|
+
hex += Number((state[i] >> BigInt(8 * j)) & 0xffn)
|
|
149
|
+
.toString(16)
|
|
150
|
+
.padStart(2, "0");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return hex;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/* ---------- ABI encoding, as Solidity's abi.encode ---------- */
|
|
157
|
+
|
|
158
|
+
function word(value) {
|
|
159
|
+
const out = new Uint8Array(32);
|
|
160
|
+
let v = BigInt(value);
|
|
161
|
+
for (let i = 31; i >= 0; i--) {
|
|
162
|
+
out[i] = Number(v & 0xffn);
|
|
163
|
+
v >>= 8n;
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function hexBytes(hex) {
|
|
169
|
+
if (!/^0x[0-9a-fA-F]*$/.test(hex) || hex.length % 2) {
|
|
170
|
+
throw new Error(`not hex: ${hex}`);
|
|
171
|
+
}
|
|
172
|
+
const out = new Uint8Array((hex.length - 2) / 2);
|
|
173
|
+
for (let i = 0; i < out.length; i++) {
|
|
174
|
+
out[i] = Number.parseInt(hex.slice(2 + i * 2, 4 + i * 2), 16);
|
|
175
|
+
}
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function concat(parts) {
|
|
180
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
181
|
+
let at = 0;
|
|
182
|
+
for (const p of parts) {
|
|
183
|
+
out.set(p, at);
|
|
184
|
+
at += p.length;
|
|
185
|
+
}
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** keccak256(bytes(winner)): how the contract takes each winner. */
|
|
190
|
+
export function winnerHash(winner) {
|
|
191
|
+
return keccak256(new TextEncoder().encode(winner));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** A campaign ID as bytes32: ASCII, right-padded. */
|
|
195
|
+
export function campaignIdBytes32(campaignId) {
|
|
196
|
+
if (!/^[\x20-\x7e]{1,32}$/.test(campaignId)) {
|
|
197
|
+
throw new Error(`campaign ID ${campaignId} isn't 1 to 32 ASCII characters`);
|
|
198
|
+
}
|
|
199
|
+
const out = new Uint8Array(32);
|
|
200
|
+
out.set(new TextEncoder().encode(campaignId));
|
|
201
|
+
return out;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* The first keccak256(abi.encode(bytes32 entropy, bytes32 campaignId,
|
|
206
|
+
* uint64 drawingNumber, uint256 position, uint256 k)) at or above
|
|
207
|
+
* 2^256 mod denominator.
|
|
208
|
+
*/
|
|
209
|
+
export function winnerRandomValue(
|
|
210
|
+
entropy,
|
|
211
|
+
campaignId,
|
|
212
|
+
drawingNumber,
|
|
213
|
+
position,
|
|
214
|
+
denominator
|
|
215
|
+
) {
|
|
216
|
+
const entropyBytes = hexBytes(entropy);
|
|
217
|
+
if (entropyBytes.length !== 32) throw new Error("entropy must be 32 bytes");
|
|
218
|
+
const threshold = (1n << 256n) % BigInt(denominator);
|
|
219
|
+
const id = campaignIdBytes32(campaignId);
|
|
220
|
+
for (let k = 0n; ; k++) {
|
|
221
|
+
const r = keccak256(
|
|
222
|
+
concat([entropyBytes, id, word(drawingNumber), word(position), word(k)])
|
|
223
|
+
);
|
|
224
|
+
if (BigInt(r) >= threshold) return r;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** random value mod denominator, 0 to denominator - 1 */
|
|
229
|
+
export function rollFor(randomValue, denominator) {
|
|
230
|
+
return Number(BigInt(randomValue) % BigInt(denominator));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Index of the first tier, top prize first, whose threshold is above `roll`. */
|
|
234
|
+
export function tierForRoll(tiers, roll) {
|
|
235
|
+
let threshold = 0;
|
|
236
|
+
for (const [i, tier] of tiers.entries()) {
|
|
237
|
+
threshold += tier.weight;
|
|
238
|
+
if (roll < threshold) return i;
|
|
239
|
+
}
|
|
240
|
+
return -1;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/* ---------- Entrant list ---------- */
|
|
244
|
+
|
|
245
|
+
const HASH = /^0x[0-9a-fA-F]{64}$/;
|
|
246
|
+
const MAX_WEIGHT = 2 ** 32 - 1;
|
|
247
|
+
/** /2 rows carry their index. /1 rows didn't. */
|
|
248
|
+
const ENTRANTS_FORMATS = ["prizerail-entrants/1", "prizerail-entrants/2"];
|
|
249
|
+
/** More pages than any list has: 100,000 entrants at 20,000 a page is 5. */
|
|
250
|
+
const MAX_PAGES = 1000;
|
|
251
|
+
|
|
252
|
+
/** "prizerail.entrant", ASCII, right-padded to 32 bytes. */
|
|
253
|
+
const ENTRANT_TAG = (() => {
|
|
254
|
+
const out = new Uint8Array(32);
|
|
255
|
+
out.set(new TextEncoder().encode("prizerail.entrant"));
|
|
256
|
+
return out;
|
|
257
|
+
})();
|
|
258
|
+
|
|
259
|
+
const compareHex = (a, b) => {
|
|
260
|
+
const x = BigInt(a);
|
|
261
|
+
const y = BigInt(b);
|
|
262
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
/** OpenZeppelin's sorted-pair hash. */
|
|
266
|
+
const hashPair = (a, b) =>
|
|
267
|
+
keccak256(
|
|
268
|
+
concat(
|
|
269
|
+
compareHex(a, b) < 0
|
|
270
|
+
? [hexBytes(a), hexBytes(b)]
|
|
271
|
+
: [hexBytes(b), hexBytes(a)]
|
|
272
|
+
)
|
|
273
|
+
);
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* OpenZeppelin's standard leaf for entry `position`:
|
|
277
|
+
* keccak256(keccak256(abi.encode(uint256 position, bytes32 hash, uint64 weight))).
|
|
278
|
+
*/
|
|
279
|
+
export function entrantLeaf(position, hash, weight) {
|
|
280
|
+
return keccak256(
|
|
281
|
+
hexBytes(keccak256(concat([word(position), hexBytes(hash), word(weight)])))
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* The root of OpenZeppelin's StandardMerkleTree over the list, given as
|
|
287
|
+
* [hash, weight] in list order: leaves sorted, stored from the end of a flat
|
|
288
|
+
* array, each node the sorted-pair hash of its two children.
|
|
289
|
+
*/
|
|
290
|
+
export function entrantsRoot(list) {
|
|
291
|
+
if (list.length === 0) throw new Error("an entrant list can't be empty");
|
|
292
|
+
const leaves = list
|
|
293
|
+
.map(([hash, weight], position) => entrantLeaf(position, hash, weight))
|
|
294
|
+
.sort(compareHex);
|
|
295
|
+
const tree = new Array(2 * leaves.length - 1);
|
|
296
|
+
for (const [i, leaf] of leaves.entries()) tree[tree.length - 1 - i] = leaf;
|
|
297
|
+
for (let i = tree.length - 1 - leaves.length; i >= 0; i--) {
|
|
298
|
+
tree[i] = hashPair(tree[2 * i + 1], tree[2 * i + 2]);
|
|
299
|
+
}
|
|
300
|
+
return tree[0];
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* The winners picked from the list, slot by slot, as
|
|
305
|
+
* { entrantIndex, selectionValue, pick }. Sums over the entrants still in
|
|
306
|
+
* are kept in a Fenwick tree, so each pick and removal takes log time.
|
|
307
|
+
*/
|
|
308
|
+
export function selectWinners(
|
|
309
|
+
entropy,
|
|
310
|
+
campaignId,
|
|
311
|
+
drawingNumber,
|
|
312
|
+
list,
|
|
313
|
+
winnerCount
|
|
314
|
+
) {
|
|
315
|
+
const weights = list.map(([, weight]) => weight);
|
|
316
|
+
const sums = new Array(weights.length + 1).fill(0);
|
|
317
|
+
const add = (index, delta) => {
|
|
318
|
+
for (let i = index + 1; i < sums.length; i += i & -i) sums[i] += delta;
|
|
319
|
+
};
|
|
320
|
+
const find = target => {
|
|
321
|
+
let at = 0;
|
|
322
|
+
let rest = target;
|
|
323
|
+
for (let step = 2 ** Math.floor(Math.log2(sums.length)); step >= 1; ) {
|
|
324
|
+
const next = at + step;
|
|
325
|
+
if (next < sums.length && sums[next] <= rest) {
|
|
326
|
+
at = next;
|
|
327
|
+
rest -= sums[next];
|
|
328
|
+
}
|
|
329
|
+
step = Math.floor(step / 2);
|
|
330
|
+
}
|
|
331
|
+
return at;
|
|
332
|
+
};
|
|
333
|
+
for (const [i, w] of weights.entries()) add(i, w);
|
|
334
|
+
let remaining = weights.reduce((a, b) => a + b, 0);
|
|
335
|
+
const entropyBytes = hexBytes(entropy);
|
|
336
|
+
const id = campaignIdBytes32(campaignId);
|
|
337
|
+
const picks = [];
|
|
338
|
+
for (let slot = 0; slot < Math.min(winnerCount, list.length); slot++) {
|
|
339
|
+
const threshold = (1n << 256n) % BigInt(remaining);
|
|
340
|
+
let r;
|
|
341
|
+
for (let k = 0n; ; k++) {
|
|
342
|
+
r = keccak256(
|
|
343
|
+
concat([
|
|
344
|
+
entropyBytes,
|
|
345
|
+
id,
|
|
346
|
+
word(drawingNumber),
|
|
347
|
+
ENTRANT_TAG,
|
|
348
|
+
word(slot),
|
|
349
|
+
word(k),
|
|
350
|
+
])
|
|
351
|
+
);
|
|
352
|
+
if (BigInt(r) >= threshold) break;
|
|
353
|
+
}
|
|
354
|
+
const pick = Number(BigInt(r) % BigInt(remaining));
|
|
355
|
+
const entrantIndex = find(pick);
|
|
356
|
+
picks.push({ entrantIndex, selectionValue: r, pick });
|
|
357
|
+
add(entrantIndex, -weights[entrantIndex]);
|
|
358
|
+
remaining -= weights[entrantIndex];
|
|
359
|
+
}
|
|
360
|
+
return picks;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* The top prize is won at most once per draw. Of the winners whose roll
|
|
365
|
+
* lands in the top tier (index 0, top prize first), the lowest random value
|
|
366
|
+
* keeps it and the rest get the second tier, index 1. Takes each winner's
|
|
367
|
+
* { randomValue, tier } and returns the final tier indexes.
|
|
368
|
+
*/
|
|
369
|
+
export function applyTopTierRule(rolled) {
|
|
370
|
+
let keeper = -1;
|
|
371
|
+
for (const [i, w] of rolled.entries()) {
|
|
372
|
+
if (
|
|
373
|
+
w.tier === 0 &&
|
|
374
|
+
(keeper === -1 ||
|
|
375
|
+
BigInt(w.randomValue) < BigInt(rolled[keeper].randomValue))
|
|
376
|
+
) {
|
|
377
|
+
keeper = i;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return rolled.map((w, i) => (w.tier === 0 && i !== keeper ? 1 : w.tier));
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/* ---------- Checking a proof ---------- */
|
|
384
|
+
|
|
385
|
+
const enc = new TextEncoder();
|
|
386
|
+
const SELF_TEST = [
|
|
387
|
+
["", "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"],
|
|
388
|
+
["abc", "0x4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45"],
|
|
389
|
+
];
|
|
390
|
+
|
|
391
|
+
const usd = cents =>
|
|
392
|
+
`$${(cents / 100).toLocaleString("en-US", {
|
|
393
|
+
minimumFractionDigits: cents % 100 ? 2 : 0,
|
|
394
|
+
})}`;
|
|
395
|
+
|
|
396
|
+
/**
|
|
397
|
+
* Every check on a proof, as { ok, label, detail? }. `ok` is true, false, or
|
|
398
|
+
* null for something worth knowing that the math can't settle.
|
|
399
|
+
*/
|
|
400
|
+
/** The draw contract's limits. */
|
|
401
|
+
const MAX_TIERS = 16;
|
|
402
|
+
const MAX_WINNERS = 500;
|
|
403
|
+
|
|
404
|
+
export function verifyProof(proof, entrants) {
|
|
405
|
+
const checks = [];
|
|
406
|
+
const check = (ok, label, detail) => checks.push({ ok, label, detail });
|
|
407
|
+
|
|
408
|
+
for (const [input, want] of SELF_TEST) {
|
|
409
|
+
if (keccak256(enc.encode(input)) !== want) {
|
|
410
|
+
check(false, "keccak256 self-test", `hash of "${input}" is wrong`);
|
|
411
|
+
return checks;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
if (
|
|
416
|
+
typeof proof.campaign?.id !== "string" ||
|
|
417
|
+
!Number.isInteger(proof.drawing?.number)
|
|
418
|
+
) {
|
|
419
|
+
check(
|
|
420
|
+
false,
|
|
421
|
+
"The proof names its campaign ID and drawing number",
|
|
422
|
+
`this script reads ${proof.format ?? "an unknown format"} proofs only if they have both`
|
|
423
|
+
);
|
|
424
|
+
return checks;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
const { denominator, tiers } = proof.prizeTable ?? {};
|
|
428
|
+
if (!Array.isArray(tiers) || !Array.isArray(proof.results)) {
|
|
429
|
+
check(false, "The proof has a prize table and results");
|
|
430
|
+
return checks;
|
|
431
|
+
}
|
|
432
|
+
const total = tiers.reduce((n, t) => n + t.weight, 0);
|
|
433
|
+
let running = 0;
|
|
434
|
+
const tableOk =
|
|
435
|
+
Number.isInteger(denominator) &&
|
|
436
|
+
denominator > 0 &&
|
|
437
|
+
tiers.length >= 2 &&
|
|
438
|
+
tiers.length <= MAX_TIERS &&
|
|
439
|
+
tiers.every(t => Number.isInteger(t.weight) && t.weight > 0) &&
|
|
440
|
+
total === denominator &&
|
|
441
|
+
tiers.every(
|
|
442
|
+
(t, i) => i === 0 || tiers[i - 1].amountCents >= t.amountCents
|
|
443
|
+
) &&
|
|
444
|
+
tiers.every(t => {
|
|
445
|
+
running += t.weight;
|
|
446
|
+
return t.threshold === undefined || t.threshold === running;
|
|
447
|
+
});
|
|
448
|
+
check(
|
|
449
|
+
tableOk,
|
|
450
|
+
`Prize table: 2 to ${MAX_TIERS} tiers, weights adding up to ${total.toLocaleString("en-US")} of ${Number(denominator).toLocaleString("en-US")} rolls, top prize first`
|
|
451
|
+
);
|
|
452
|
+
// Every prize below comes from the table, so there's nothing more to check.
|
|
453
|
+
if (!tableOk) return checks;
|
|
454
|
+
const withinLimit = proof.results.length <= MAX_WINNERS;
|
|
455
|
+
check(
|
|
456
|
+
withinLimit,
|
|
457
|
+
`At most ${MAX_WINNERS} winners, the contract's limit (${proof.results.length})`
|
|
458
|
+
);
|
|
459
|
+
// The contract can't have drawn more, so don't spend time on the rest.
|
|
460
|
+
if (!withinLimit) return checks;
|
|
461
|
+
const resultAt = new Map(proof.results.map(r => [r.position, r]));
|
|
462
|
+
|
|
463
|
+
const entropy = proof.entropy.value;
|
|
464
|
+
const entrantList = proof.entrantList;
|
|
465
|
+
if (!entrantList) {
|
|
466
|
+
check(
|
|
467
|
+
false,
|
|
468
|
+
"The proof has an entrant list",
|
|
469
|
+
`not an entrants draw proof (${proof.format ?? "unknown format"}). This script checks prizerail-draw-proof/3 proofs`
|
|
470
|
+
);
|
|
471
|
+
return checks;
|
|
472
|
+
}
|
|
473
|
+
// The winners are the results in slot order, picked from the list.
|
|
474
|
+
const winners = [...proof.results]
|
|
475
|
+
.sort((a, b) => a.position - b.position)
|
|
476
|
+
.map(r => r.winner);
|
|
477
|
+
checkEntrants(proof, entrants, check, resultAt);
|
|
478
|
+
check(
|
|
479
|
+
proof.results.length === winners.length,
|
|
480
|
+
`One result per winner (${proof.results.length})`
|
|
481
|
+
);
|
|
482
|
+
// Every winner's roll first, since the top-tier rule looks across them.
|
|
483
|
+
const rolled = winners.map((_, position) => {
|
|
484
|
+
const randomValue = winnerRandomValue(
|
|
485
|
+
entropy,
|
|
486
|
+
proof.campaign.id,
|
|
487
|
+
proof.drawing.number,
|
|
488
|
+
position,
|
|
489
|
+
denominator
|
|
490
|
+
);
|
|
491
|
+
const roll = rollFor(randomValue, denominator);
|
|
492
|
+
return { randomValue, roll, tier: tierForRoll(tiers, roll) };
|
|
493
|
+
});
|
|
494
|
+
const finalTiers = applyTopTierRule(rolled);
|
|
495
|
+
for (const [position, winner] of winners.entries()) {
|
|
496
|
+
const result = resultAt.get(position);
|
|
497
|
+
const label = `Winner ${position} (${winner})`;
|
|
498
|
+
if (!result || result.winner !== winner) {
|
|
499
|
+
check(false, label, "no result for this position and winner");
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
const { randomValue, roll } = rolled[position];
|
|
503
|
+
const tier = finalTiers[position];
|
|
504
|
+
const amountCents = tier === -1 ? null : tiers[tier].amountCents;
|
|
505
|
+
const demoted = rolled[position].tier === 0 && tier === 1;
|
|
506
|
+
const problems = [
|
|
507
|
+
randomValue !== result.randomValue.toLowerCase() &&
|
|
508
|
+
`random value should be ${randomValue}`,
|
|
509
|
+
roll !== result.roll && `roll should be ${roll}`,
|
|
510
|
+
amountCents !== result.amountCents &&
|
|
511
|
+
`prize should be ${amountCents === null ? "none" : usd(amountCents)}`,
|
|
512
|
+
].filter(Boolean);
|
|
513
|
+
check(
|
|
514
|
+
problems.length === 0,
|
|
515
|
+
`${label}: roll ${roll.toLocaleString("en-US")} wins ${usd(result.amountCents)}${demoted ? ", the second prize, since another winner with a lower random value kept the top one" : ""}`,
|
|
516
|
+
problems.join(", ") || undefined
|
|
517
|
+
);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const { lockedAt } = entrantList;
|
|
521
|
+
const { revealedAt, provider, requestId } = proof.entropy;
|
|
522
|
+
if (lockedAt && revealedAt) {
|
|
523
|
+
check(
|
|
524
|
+
new Date(lockedAt) < new Date(revealedAt),
|
|
525
|
+
"The list was locked before the random value was revealed",
|
|
526
|
+
"by Prizerail's own timestamps"
|
|
527
|
+
);
|
|
528
|
+
}
|
|
529
|
+
if (provider === "mock") {
|
|
530
|
+
check(
|
|
531
|
+
null,
|
|
532
|
+
"Random value source: test randomness",
|
|
533
|
+
"made by Prizerail in a test environment, so it can't be checked independently"
|
|
534
|
+
);
|
|
535
|
+
} else {
|
|
536
|
+
check(
|
|
537
|
+
null,
|
|
538
|
+
`Random value source: ${provider}${requestId ? ` request ${requestId}` : ""}`,
|
|
539
|
+
"this script doesn't look up the request onchain yet; check it on the chain's explorer"
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
return checks;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** The entrant list's checks: its root, then every pick. */
|
|
546
|
+
function checkEntrants(proof, entrants, check, results) {
|
|
547
|
+
const { root, count, totalWeight, winnersRequested } = proof.entrantList;
|
|
548
|
+
if (
|
|
549
|
+
typeof root !== "string" ||
|
|
550
|
+
!HASH.test(root) ||
|
|
551
|
+
!Number.isInteger(count) ||
|
|
552
|
+
count < 1 ||
|
|
553
|
+
!Number.isSafeInteger(totalWeight) ||
|
|
554
|
+
!Number.isInteger(winnersRequested) ||
|
|
555
|
+
winnersRequested < 1 ||
|
|
556
|
+
winnersRequested > MAX_WINNERS
|
|
557
|
+
) {
|
|
558
|
+
check(
|
|
559
|
+
false,
|
|
560
|
+
"The proof's entrant list fields are well formed",
|
|
561
|
+
"root must be 32 bytes of hex, count and totalWeight whole numbers, and winnersRequested from 1 to 500"
|
|
562
|
+
);
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
const expected = Math.min(winnersRequested, count);
|
|
566
|
+
check(
|
|
567
|
+
proof.results.length === expected,
|
|
568
|
+
`${expected} winner${expected === 1 ? "" : "s"}: ${winnersRequested} asked for, from ${count.toLocaleString("en-US")} entrants`
|
|
569
|
+
);
|
|
570
|
+
if (!entrants) {
|
|
571
|
+
// The root and the picks are what make an entrants draw checkable, so
|
|
572
|
+
// a run that couldn't load the list hasn't verified the draw.
|
|
573
|
+
check(
|
|
574
|
+
false,
|
|
575
|
+
"Entrant list loaded",
|
|
576
|
+
"the root and the picks weren't checked. Pass the proof's link, or the list's link or file as a second argument"
|
|
577
|
+
);
|
|
578
|
+
return;
|
|
579
|
+
}
|
|
580
|
+
const bad = entrants.findIndex(
|
|
581
|
+
e =>
|
|
582
|
+
!Array.isArray(e) ||
|
|
583
|
+
e.length !== 3 ||
|
|
584
|
+
!Number.isInteger(e[0]) ||
|
|
585
|
+
typeof e[1] !== "string" ||
|
|
586
|
+
!HASH.test(e[1]) ||
|
|
587
|
+
!Number.isInteger(e[2]) ||
|
|
588
|
+
e[2] < 1 ||
|
|
589
|
+
e[2] > MAX_WEIGHT
|
|
590
|
+
);
|
|
591
|
+
if (bad !== -1) {
|
|
592
|
+
check(
|
|
593
|
+
false,
|
|
594
|
+
"Entrant list is well formed",
|
|
595
|
+
`row ${bad} isn't [index, 32-byte hash, whole weight from 1 to 2^32 - 1]`
|
|
596
|
+
);
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
// The root is a set commitment: the index in each row is the list's only
|
|
600
|
+
// order, so rows are sorted by it, and the indices must be exactly
|
|
601
|
+
// 0 to count - 1, with no duplicate, gap or stray.
|
|
602
|
+
const sorted = [...entrants].sort((a, b) => a[0] - b[0]);
|
|
603
|
+
const stray = sorted.findIndex((e, i) => e[0] !== i);
|
|
604
|
+
if (stray !== -1) {
|
|
605
|
+
check(
|
|
606
|
+
false,
|
|
607
|
+
`Entrant indices run exactly 0 to ${(entrants.length - 1).toLocaleString("en-US")}`,
|
|
608
|
+
`found index ${sorted[stray][0]} where ${stray} belongs, so the list has a duplicate, a gap or a stray index`
|
|
609
|
+
);
|
|
610
|
+
return;
|
|
611
|
+
}
|
|
612
|
+
const list = sorted.map(([, hash, weight]) => [hash, weight]);
|
|
613
|
+
const total = list.reduce((n, [, weight]) => n + weight, 0);
|
|
614
|
+
const sized =
|
|
615
|
+
entrants.length === count &&
|
|
616
|
+
Number.isSafeInteger(total) &&
|
|
617
|
+
total === totalWeight;
|
|
618
|
+
check(
|
|
619
|
+
sized,
|
|
620
|
+
`Entrant list has ${count.toLocaleString("en-US")} entrants and ${totalWeight.toLocaleString("en-US")} total weight`,
|
|
621
|
+
sized ? undefined : `got ${entrants.length} entrants and ${total} weight`
|
|
622
|
+
);
|
|
623
|
+
// The root and the picks are only defined for the committed list.
|
|
624
|
+
if (!sized) return;
|
|
625
|
+
const computed = entrantsRoot(list);
|
|
626
|
+
check(
|
|
627
|
+
computed === root.toLowerCase(),
|
|
628
|
+
"Entrant list root matches the list",
|
|
629
|
+
computed === root.toLowerCase() ? undefined : `computed ${computed}`
|
|
630
|
+
);
|
|
631
|
+
const picks = selectWinners(
|
|
632
|
+
proof.entropy.value,
|
|
633
|
+
proof.campaign.id,
|
|
634
|
+
proof.drawing.number,
|
|
635
|
+
list,
|
|
636
|
+
winnersRequested
|
|
637
|
+
);
|
|
638
|
+
for (const [slot, pick] of picks.entries()) {
|
|
639
|
+
const result = results.get(slot);
|
|
640
|
+
const label = `Slot ${slot} pick`;
|
|
641
|
+
if (!result) {
|
|
642
|
+
check(false, label, "no result for this slot");
|
|
643
|
+
continue;
|
|
644
|
+
}
|
|
645
|
+
const entry = list.at(pick.entrantIndex);
|
|
646
|
+
const problems = [
|
|
647
|
+
pick.selectionValue !== result.selectionValue?.toLowerCase() &&
|
|
648
|
+
`selection value should be ${pick.selectionValue}`,
|
|
649
|
+
pick.pick !== result.pick && `pick should be ${pick.pick}`,
|
|
650
|
+
pick.entrantIndex !== result.entrantPosition &&
|
|
651
|
+
`winner should be entrant ${pick.entrantIndex}`,
|
|
652
|
+
winnerHash(result.winner) !== entry[0].toLowerCase() &&
|
|
653
|
+
`${result.winner} doesn't hash to entrant ${pick.entrantIndex}`,
|
|
654
|
+
].filter(Boolean);
|
|
655
|
+
check(
|
|
656
|
+
problems.length === 0,
|
|
657
|
+
`${label}: lands on entrant ${pick.entrantIndex.toLocaleString("en-US")} (${result.winner})`,
|
|
658
|
+
problems.join(", ") || undefined
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/**
|
|
664
|
+
* Reads JSON from a link or a file. Links use `fetch` (the global one by
|
|
665
|
+
* default) and give up after `timeoutMs`.
|
|
666
|
+
*/
|
|
667
|
+
async function readJson(
|
|
668
|
+
source,
|
|
669
|
+
{ fetch = globalThis.fetch, timeoutMs = 30_000 } = {}
|
|
670
|
+
) {
|
|
671
|
+
if (/^https?:\/\//.test(source)) {
|
|
672
|
+
const response = await fetch(source, {
|
|
673
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
674
|
+
});
|
|
675
|
+
if (!response.ok) throw new Error(`${source}: HTTP ${response.status}`);
|
|
676
|
+
return response.json();
|
|
677
|
+
}
|
|
678
|
+
const { readFile } = await import("node:fs/promises");
|
|
679
|
+
return JSON.parse(await readFile(source, "utf8"));
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/**
|
|
683
|
+
* Every page of an entrant list, as [index, hash, weight] rows in the order
|
|
684
|
+
* served (checkEntrants sorts them by index). Pages are followed in order,
|
|
685
|
+
* on the site the first one came from, exactly up to the page count the
|
|
686
|
+
* first page states. A prizerail-entrants/1 page, from before rows carried
|
|
687
|
+
* their index, has [hash, weight] rows indexed by place. `options` can
|
|
688
|
+
* carry the `fetch` to use and a per-page `timeoutMs`.
|
|
689
|
+
*/
|
|
690
|
+
export async function readEntrants(source, options = {}) {
|
|
691
|
+
const remote = /^https?:\/\//.test(source);
|
|
692
|
+
const origin = remote ? new URL(source).origin : null;
|
|
693
|
+
const list = [];
|
|
694
|
+
let next = source;
|
|
695
|
+
let pages = null;
|
|
696
|
+
for (let expected = 1; ; expected++) {
|
|
697
|
+
const page = await readJson(next, options);
|
|
698
|
+
pages ??= page.pages;
|
|
699
|
+
if (
|
|
700
|
+
page.page !== expected ||
|
|
701
|
+
page.pages !== pages ||
|
|
702
|
+
!Number.isInteger(pages) ||
|
|
703
|
+
pages < 1 ||
|
|
704
|
+
pages > MAX_PAGES ||
|
|
705
|
+
!Array.isArray(page.entrants) ||
|
|
706
|
+
!ENTRANTS_FORMATS.includes(page.format)
|
|
707
|
+
) {
|
|
708
|
+
throw new Error(`${next} isn't page ${expected} of the entrant list`);
|
|
709
|
+
}
|
|
710
|
+
if (page.format === "prizerail-entrants/1") {
|
|
711
|
+
if (!Number.isInteger(page.from)) {
|
|
712
|
+
throw new Error(`${next} is a /1 page with no "from"`);
|
|
713
|
+
}
|
|
714
|
+
list.push(...page.entrants.map((row, i) => [page.from + i, ...row]));
|
|
715
|
+
} else {
|
|
716
|
+
list.push(...page.entrants);
|
|
717
|
+
}
|
|
718
|
+
if (!page.next) {
|
|
719
|
+
if (expected < pages) {
|
|
720
|
+
throw new Error(
|
|
721
|
+
`${next} is page ${expected} of ${pages} but links no further`
|
|
722
|
+
);
|
|
723
|
+
}
|
|
724
|
+
return list;
|
|
725
|
+
}
|
|
726
|
+
if (!remote) {
|
|
727
|
+
throw new Error(
|
|
728
|
+
`${next} is one page of ${pages}. Pass the list's link instead, so every page is fetched.`
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
if (expected >= pages) {
|
|
732
|
+
throw new Error(`${next} links past the list's last page, ${pages}`);
|
|
733
|
+
}
|
|
734
|
+
const url = new URL(page.next, next);
|
|
735
|
+
if (url.origin !== origin) {
|
|
736
|
+
throw new Error(`${url.href} is on another site, so it wasn't fetched`);
|
|
737
|
+
}
|
|
738
|
+
next = url.href;
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
async function main() {
|
|
743
|
+
const source = process.argv[2];
|
|
744
|
+
if (!source) {
|
|
745
|
+
console.log(
|
|
746
|
+
"Usage: node verify-draw.mjs <proof.json file or link> [entrants.json file or link]"
|
|
747
|
+
);
|
|
748
|
+
process.exit(2);
|
|
749
|
+
}
|
|
750
|
+
const proof = await readJson(source);
|
|
751
|
+
let entrants;
|
|
752
|
+
if (proof.entrantList) {
|
|
753
|
+
const listSource =
|
|
754
|
+
process.argv[3] ??
|
|
755
|
+
(/^https?:\/\//.test(source)
|
|
756
|
+
? new URL(proof.entrantList.url, source).href
|
|
757
|
+
: undefined);
|
|
758
|
+
if (listSource) entrants = await readEntrants(listSource);
|
|
759
|
+
}
|
|
760
|
+
console.log(
|
|
761
|
+
`\n${proof.campaign.name}, draw of ${proof.drawing.drawAt} (${proof.drawing.id})\n`
|
|
762
|
+
);
|
|
763
|
+
const checks = verifyProof(proof, entrants);
|
|
764
|
+
for (const { ok, label, detail } of checks) {
|
|
765
|
+
const mark = ok === true ? "✓" : ok === false ? "✗" : "i";
|
|
766
|
+
console.log(`${mark} ${label}${detail ? `\n ${detail}` : ""}`);
|
|
767
|
+
}
|
|
768
|
+
const failed = checks.filter(c => c.ok === false).length;
|
|
769
|
+
console.log(
|
|
770
|
+
failed
|
|
771
|
+
? `\n${failed} check${failed === 1 ? "" : "s"} failed.`
|
|
772
|
+
: "\nEvery result follows from the inputs."
|
|
773
|
+
);
|
|
774
|
+
process.exit(failed ? 1 : 0);
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
// Run main() only when called as a script, not when imported.
|
|
778
|
+
if (typeof process !== "undefined" && process.argv?.[1]) {
|
|
779
|
+
const { pathToFileURL } = await import("node:url");
|
|
780
|
+
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
781
|
+
main().catch(error => {
|
|
782
|
+
console.error(error.message);
|
|
783
|
+
process.exit(2);
|
|
784
|
+
});
|
|
785
|
+
}
|
|
786
|
+
}
|