Don't trust the randomness API: verify drand beacons in your agent in 30 lines
Agents keep needing a random number that another party can check: picking a reviewer, breaking a tie, sampling a test case, running a small raffle. Math.random() works until someone asks "prove you didn't reroll." drand already fixes this. It's a public randomness beacon run by a group of independent organizations (the League of Entropy). Every 3 seconds its quicknet chain publishes a round: a…
Agents require random numbers that can be independently verified by others. Relying solely on Math.random() is insufficient, as it cannot prove non-reroll. Drand addresses this issue through a public randomness beacon run by a consortium of independent organizations, the League of Entropy. This beacon publishes a round approximately every three seconds, consisting of a BLS signature over the round number and a randomness value derived from the signature via SHA-256.
However, most agents do not interact directly with drand. Instead, they rely on HTTP APIs to relay the beacon data. The question arises as to whether one should trust these relays. The answer is no – one should not have to. Instead, verify the beacon yourself before using it.
To achieve this, one can utilize a small free relay, such as Proof Random API, which returns the latest round as JSON. However, this relay does not perform signature verification itself. Verification must be conducted locally, using the chain hash and public key of the drand network, which should be hardcoded rather than obtained from the source being verified.
To verify the round independently, first install the official drand client via npm. Then, fetch the round from the relay and the corresponding round from drand's HTTP endpoint. Compare the two values using the HttpChainClient provided by the drand client library. If the values do not match, the relay's beacon is invalid.
The relay should be considered only a convenience, not a trust anchor. To obtain a truly unbiased randomness value, use the verified beacon data to hash a combination of the chain hash, round, randomness, and nonce with SHA-256. Use rejection sampling to generate an integer within a desired range, ensuring fairness and unpredictability in the resulting randomness value.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.