Verify a draw yourself
You need the draw code, a drand relay and about forty lines of code. Every results page also has a button that does all of this in your browser.
-
1
Get the files
From the results page: verify.json (the commitment and the published result) and entries.txt (the locked list). Check SHA-256(entries.txt) equals the entries hash.
-
2
Fetch the round from drand
Not from us: GET https://api.drand.sh/52db9ba7.../public/R from any relay (api.drand.sh, api2.drand.sh, api3.drand.sh, drand.cloudflare.com). Check randomness = SHA-256(signature).
-
3
Compute the seed
HMAC-SHA256 with the 32 randomness bytes as the key and "entries_hash|code|draw number" as the message. Compare with the published seed.
-
4
Shuffle and compare
Run the stream and Fisher-Yates shuffle, skip repeat people, take the winners and backups. Compare with the results page.
From the command line
curl -O https://pickfaire.com/brand/faire/verify.py
python3 verify.py https://pickfaire.com/d/DRAWCODE/verify.json
curl -O https://pickfaire.com/brand/faire/verify.js
node verify.js https://pickfaire.com/d/DRAWCODE/verify.jsonBoth print each check and end with "Everything matches." Our test suite runs both files against the server implementation on a fixed fixture, so they cannot drift apart.
Python reference (standard library only)
verify.py
#!/usr/bin/env python3
"""Independent re-run of a beacon draw. Python 3.8+, standard library only.
python3 verify.py https://<site>/d/<code>/verify.json
It downloads the verification file and the frozen entry list from the site, and the drand
round straight from a drand relay, then recomputes every step and prints whether it matches.
It does not check the round's BLS signature; drand's own client does that.
"""
import hashlib
import hmac
import json
import struct
import sys
import urllib.request
MAX63 = (1 << 63) - 1
def derive_seed(randomness_hex, entries_hash, code, draw_number):
"""seed = hex(HMAC-SHA256(key = randomness bytes, message = "<entries hash>|<code>|<draw number>"))"""
message = "{}|{}|{}".format(entries_hash.lower(), code, draw_number).encode("ascii")
return hmac.new(bytes.fromhex(randomness_hex), message, hashlib.sha256).hexdigest()
class Stream:
"""block i = HMAC-SHA256(key = ASCII seed string, message = uint64_be(i)); four 63-bit words per block."""
def __init__(self, seed_hex):
self.key = seed_hex.encode("ascii")
self.counter = 0
self.words = []
def next63(self):
if not self.words:
block = hmac.new(self.key, struct.pack(">Q", self.counter), hashlib.sha256).digest()
self.counter += 1
self.words = [struct.unpack(">Q", block[i:i + 8])[0] & MAX63 for i in range(0, 32, 8)]
return self.words.pop(0)
def below(self, n):
"""Uniform integer in [0, n) by rejection sampling."""
if n <= 1:
return 0
limit = MAX63 - (MAX63 % n)
while True:
v = self.next63()
if v < limit:
return v % n
def shuffle(items, seed_hex):
a = list(items)
s = Stream(seed_hex)
for i in range(len(a) - 1, 0, -1):
j = s.below(i + 1)
a[i], a[j] = a[j], a[i]
return a
def recompute(lines, seed_hex, skipped, winners, alternates):
"""Shuffle the frozen list; skip anyone skipped and anyone already picked; winners first, then backups."""
names = [line.split(":", 1)[1] for line in lines]
skip = {u.lower() for u in skipped}
seen, out = set(), []
for u in shuffle(names, seed_hex):
k = u.lower()
if k in skip or k in seen:
continue
seen.add(k)
out.append(u)
if len(out) >= winners + alternates:
break
return out[:winners], out[winners:winners + alternates]
def get(url):
req = urllib.request.Request(url, headers={"User-Agent": "beacon-draw-verifier"})
with urllib.request.urlopen(req, timeout=20) as r:
return r.read()
def main(verify_url):
v = json.loads(get(verify_url))
text = get(v["entries_list_url"]).decode("utf-8")
lines = text.split("\n") if text else []
ok = True
def check(label, good):
nonlocal ok
ok = ok and good
print(("OK " if good else "FAIL ") + label)
check("entry list SHA-256 = " + v["entries_hash"], hashlib.sha256(text.encode("utf-8")).hexdigest() == v["entries_hash"])
rnd = None
for url in v["beacon"]["round_urls"]:
try:
rnd = json.loads(get(url))
break
except Exception:
continue
if rnd is None:
sys.exit("no drand relay answered")
randomness = hashlib.sha256(bytes.fromhex(rnd["signature"])).hexdigest()
check("drand round %d, randomness = SHA-256(signature)" % rnd["round"], rnd["round"] == v["beacon"]["round"] and randomness == v["beacon"]["randomness"])
seed = derive_seed(randomness, v["entries_hash"], v["code"], v["post_draw_number"])
check("seed " + seed, seed == v["seed"])
w, a = recompute(lines, seed, v["skipped"], len(v["winners"]), len(v["alternates"]))
check("winners " + ", ".join(w), w == v["winners"])
check("backups " + (", ".join(a) or "none"), a == v["alternates"])
print("Everything matches." if ok else "MISMATCH")
return 0 if ok else 1
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "--fixture":
# Offline mode for tests: {randomness, entries_hash, code, number, lines, skipped, winners, alternates}
fx = json.load(open(sys.argv[2]))
sd = derive_seed(fx["randomness"], fx["entries_hash"], fx["code"], fx["number"])
w, a = recompute(fx["lines"], sd, fx["skipped"], fx["winners"], fx["alternates"])
print(json.dumps({"entries_hash": hashlib.sha256("\n".join(fx["lines"]).encode("utf-8")).hexdigest(), "seed": sd, "winners": w, "alternates": a}))
elif len(sys.argv) == 2:
sys.exit(main(sys.argv[1]))
else:
sys.exit(__doc__)
JavaScript reference (browser and Node, no dependencies)
verify.js (the same file the results page runs)
/*
* Independent re-run of a beacon draw, in plain JavaScript with no dependencies.
* Runs in the browser (the "Re-run this draw" button on a results page) and in Node 18+:
*
* node verify.js https://<site>/d/<code>/verify.json
*
* Steps: fetch the verification file, the frozen entry list and the drand round (from a drand
* relay, not from the site), then check: SHA-256(list) = entries hash; SHA-256(signature) =
* randomness; HMAC-SHA256(randomness, "<entries hash>|<code>|<draw number>") = seed; the
* HMAC-SHA256 counter stream + Fisher-Yates shuffle with that seed gives the published winners.
* It does not check the BLS signature itself; drand's own client does that.
*/
(function (root) {
'use strict';
var K = new Uint32Array([
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
]);
function rotr(x, n) {
return (x >>> n) | (x << (32 - n));
}
/** SHA-256 of a Uint8Array, as a Uint8Array(32). */
function sha256(bytes) {
var l = bytes.length;
var padded = (((l + 9 + 63) / 64) | 0) * 64;
var m = new Uint8Array(padded);
m.set(bytes);
m[l] = 0x80;
var dv = new DataView(m.buffer);
dv.setUint32(padded - 8, Math.floor(l / 0x20000000));
dv.setUint32(padded - 4, (l * 8) >>> 0);
var h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
var w = new Uint32Array(64);
for (var off = 0; off < padded; off += 64) {
for (var i = 0; i < 16; i++) w[i] = dv.getUint32(off + i * 4);
for (i = 16; i < 64; i++) {
var x = w[i - 15], y = w[i - 2];
w[i] = w[i - 16] + (rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3)) + w[i - 7] + (rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10));
}
var a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], k = h[7];
for (i = 0; i < 64; i++) {
var t1 = (k + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) | 0;
var t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
k = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0;
}
h[0] = (h[0] + a) | 0; h[1] = (h[1] + b) | 0; h[2] = (h[2] + c) | 0; h[3] = (h[3] + d) | 0;
h[4] = (h[4] + e) | 0; h[5] = (h[5] + f) | 0; h[6] = (h[6] + g) | 0; h[7] = (h[7] + k) | 0;
}
var out = new Uint8Array(32);
var odv = new DataView(out.buffer);
for (i = 0; i < 8; i++) odv.setUint32(i * 4, h[i] >>> 0);
return out;
}
function hmac(key, msg) {
if (key.length > 64) key = sha256(key);
var k = new Uint8Array(64);
k.set(key);
var inner = new Uint8Array(64 + msg.length);
var outer = new Uint8Array(64 + 32);
for (var i = 0; i < 64; i++) {
inner[i] = k[i] ^ 0x36;
outer[i] = k[i] ^ 0x5c;
}
inner.set(msg, 64);
outer.set(sha256(inner), 64);
return sha256(outer);
}
function utf8(s) {
return new TextEncoder().encode(s);
}
function hex(bytes) {
var s = '';
for (var i = 0; i < bytes.length; i++) s += (bytes[i] < 16 ? '0' : '') + bytes[i].toString(16);
return s;
}
function unhex(s) {
var out = new Uint8Array(s.length / 2);
for (var i = 0; i < out.length; i++) out[i] = parseInt(s.substr(i * 2, 2), 16);
return out;
}
/** seed = hex(HMAC-SHA256(key = randomness bytes, message = "<entries hash>|<code>|<draw number>")) */
function deriveSeed(randomnessHex, entriesHash, code, drawNumber) {
return hex(hmac(unhex(randomnessHex), utf8(entriesHash.toLowerCase() + '|' + code + '|' + drawNumber)));
}
var MAX63 = (BigInt(1) << BigInt(63)) - BigInt(1);
/** The draw's random stream: block i = HMAC-SHA256(key = ASCII seed, message = uint64_be(i)); four 63-bit words per block. */
function Stream(seedHex) {
this.key = utf8(seedHex);
this.counter = 0;
this.words = [];
}
Stream.prototype.next63 = function () {
if (this.words.length === 0) {
var msg = new Uint8Array(8);
new DataView(msg.buffer).setBigUint64(0, BigInt(this.counter++));
var block = new DataView(hmac(this.key, msg).buffer);
for (var i = 0; i < 4; i++) this.words.push(block.getBigUint64(i * 8) & MAX63);
}
return this.words.shift();
};
/** Uniform integer in [0, n) by rejection sampling, exactly as the server does it. */
Stream.prototype.below = function (n) {
if (n <= 1) return 0;
var bn = BigInt(n);
var limit = MAX63 - (MAX63 % bn);
var v;
do {
v = this.next63();
} while (v >= limit);
return Number(v % bn);
};
function shuffle(items, seedHex) {
var a = items.slice();
var s = new Stream(seedHex);
for (var i = a.length - 1; i > 0; i--) {
var j = s.below(i + 1);
var t = a[i];
a[i] = a[j];
a[j] = t;
}
return a;
}
/** Winners and backups from the frozen list ("id:username" lines). */
function recompute(lines, seedHex, skipped, winners, alternates) {
var names = lines.map(function (l) {
return l.slice(l.indexOf(':') + 1);
});
var skip = {};
(skipped || []).forEach(function (u) {
skip[u.toLowerCase()] = true;
});
var seen = {};
var out = [];
var order = shuffle(names, seedHex);
for (var i = 0; i < order.length && out.length < winners + alternates; i++) {
var k = order[i].toLowerCase();
if (skip[k] || seen[k]) continue;
seen[k] = true;
out.push(order[i]);
}
return { winners: out.slice(0, winners), alternates: out.slice(winners, winners + alternates) };
}
function same(a, b) {
return a.length === b.length && a.every(function (x, i) {
return x === b[i];
});
}
/** Full re-run. onStep(label, ok, detail) is called after each check. Resolves to true when everything matches. */
async function run(verifyUrl, onStep) {
var step = onStep || function () {};
var v = await (await fetch(verifyUrl)).json();
if (v.mode !== 'beacon' || !v.entries_list_url) throw new Error('This file is not a beacon draw with a public entry list.');
var text = await (await fetch(v.entries_list_url)).text();
var listHash = hex(sha256(utf8(text)));
step('Entry list: ' + v.entries_count + ' entries, SHA-256 ' + listHash, listHash === v.entries_hash, 'committed hash ' + v.entries_hash);
var round = null, from = null;
for (var i = 0; i < v.beacon.round_urls.length && !round; i++) {
try {
var r = await fetch(v.beacon.round_urls[i]);
if (r.ok) {
round = await r.json();
from = v.beacon.round_urls[i];
}
} catch (e) {
/* next relay */
}
}
if (!round) throw new Error('No drand relay answered from this browser.');
var randomness = hex(sha256(unhex(round.signature)));
step('drand round ' + round.round + ' fetched from ' + new URL(from).host, round.round === v.beacon.round && randomness === v.beacon.randomness && (!round.randomness || round.randomness === randomness), 'randomness = SHA-256(signature) = ' + randomness);
var t = v.beacon.genesis_time + (v.beacon.round - 1) * v.beacon.period_seconds;
var after = t - Math.floor(Date.parse(v.locked_at) / 1000);
step('Round ' + v.beacon.round + ' was published ' + after + ' seconds after the list was locked', after > 0, new Date(t * 1000).toISOString());
var seed = deriveSeed(randomness, v.entries_hash, v.code, v.post_draw_number);
step('Seed = HMAC-SHA256(randomness, "' + v.entries_hash.slice(0, 12) + '…|' + v.code + '|' + v.post_draw_number + '") = ' + seed, seed === v.seed, 'published seed ' + v.seed);
var res = recompute(text === '' ? [] : text.split('\n'), seed, v.skipped, v.winners.length, v.alternates.length);
step('Shuffle gives winners ' + res.winners.map(function (u) { return '@' + u; }).join(', '), same(res.winners, v.winners), 'published ' + v.winners.join(', '));
step('and backups ' + (res.alternates.map(function (u) { return '@' + u; }).join(', ') || 'none'), same(res.alternates, v.alternates), 'published ' + (v.alternates.join(', ') || 'none'));
return listHash === v.entries_hash && seed === v.seed && same(res.winners, v.winners) && same(res.alternates, v.alternates);
}
var api = { sha256: sha256, hmac: hmac, hex: hex, unhex: unhex, utf8: utf8, deriveSeed: deriveSeed, shuffle: shuffle, recompute: recompute, run: run };
root.BeaconVerify = api;
if (typeof module !== 'undefined' && module.exports) {
module.exports = api;
if (typeof require !== 'undefined' && require.main === module && process.argv[2]) {
var arg = process.argv[2];
if (arg === '--fixture') {
// Offline mode for tests: {randomness, entries_hash, code, number, lines, skipped, winners, alternates}
var fx = JSON.parse(require('fs').readFileSync(process.argv[3], 'utf8'));
var sd = deriveSeed(fx.randomness, fx.entries_hash, fx.code, fx.number);
var rr = recompute(fx.lines, sd, fx.skipped, fx.winners, fx.alternates);
console.log(JSON.stringify({ entries_hash: hex(sha256(utf8(fx.lines.join('\n')))), seed: sd, winners: rr.winners, alternates: rr.alternates }));
} else {
run(arg, function (label, ok) {
console.log((ok ? 'OK ' : 'FAIL ') + label);
}).then(function (ok) {
console.log(ok ? 'Everything matches.' : 'MISMATCH');
process.exit(ok ? 0 : 1);
});
}
}
}
})(typeof window !== 'undefined' ? window : globalThis);
The BLS signature
The steps above check that the round number and the randomness are consistent with the signature a relay serves. To check the signature itself against the League of Entropy's public key, use drand's own client (for example the drand-client library or the drand util check tools from github.com/drand). We do not run that check in our PHP code, and we say so on every verification file (signature_checked_here: false).