From ee28cbbc55fb636f1a9278446772111adaf5c465 Mon Sep 17 00:00:00 2001 From: bywura Date: Wed, 25 Nov 2026 17:05:14 +0100 Subject: [PATCH] fix(drand-tools): verify configured chain hash at startup --- .env.example | 3 +- services/drand-tools/package.json | 2 +- services/drand-tools/src/chain-hash.test.ts | 164 ++++++++++++++++++++ services/drand-tools/src/index.ts | 13 +- services/drand-tools/src/quicknet.ts | 77 ++++++++- 5 files changed, 249 insertions(+), 10 deletions(-) create mode 100644 services/drand-tools/src/chain-hash.test.ts diff --git a/.env.example b/.env.example index bdd4d13f..e10b3382 100644 --- a/.env.example +++ b/.env.example @@ -18,7 +18,8 @@ STELLAR_SECRET_KEY= USDC_SAC= # --- Drand (quicknet) --- -# Validated against a live round before deploy (see services/drand-tools). +# Required by services/drand-tools. Validated against the fetched chain info +# before any round data is accepted. DRAND_CHAIN_HASH=52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971 DRAND_API_URL=https://api.drand.sh diff --git a/services/drand-tools/package.json b/services/drand-tools/package.json index b0c1d6f1..71d91867 100644 --- a/services/drand-tools/package.json +++ b/services/drand-tools/package.json @@ -11,7 +11,7 @@ }, "scripts": { "validate": "tsx src/index.ts", - "test": "node --import tsx --test src/encode.test.ts src/parity.test.ts", + "test": "node --import tsx --test src/chain-hash.test.ts src/encode.test.ts src/parity.test.ts", "typecheck": "tsc --noEmit -p tsconfig.json" }, "dependencies": { diff --git a/services/drand-tools/src/chain-hash.test.ts b/services/drand-tools/src/chain-hash.test.ts new file mode 100644 index 00000000..34ce5cbb --- /dev/null +++ b/services/drand-tools/src/chain-hash.test.ts @@ -0,0 +1,164 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { test, type TestContext } from "node:test"; +import { fileURLToPath } from "node:url"; + +import { + CHAIN_HASH_INVALID_ERROR, + CHAIN_HASH_MISMATCH_ERROR, + CHAIN_HASH_REQUIRED_ERROR, + DRAND_API_URL_ENV, + DRAND_CHAIN_HASH_ENV, + DrandChainHashMismatchError, + getBeacon, + getChainInfo, + loadDrandConfig, + type Beacon, + type ChainInfo, +} from "./quicknet.js"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const vectorPath = path.resolve(__dirname, "../../../test-vectors/quicknet.json"); +const [fixture] = JSON.parse(fs.readFileSync(vectorPath, "utf-8")) as Array<{ + round: number; + chain_hash: string; + period: number; + genesis_time: number; + schemeID: string; + signature: string; + public_key: string; + randomness?: string; +}>; + +const API_BASE = "https://drand.invalid"; +const MISMATCHED_HASH = "0".repeat(64); + +function chainInfo(hash: string = fixture.chain_hash): ChainInfo { + return { + public_key: fixture.public_key, + period: fixture.period, + genesis_time: fixture.genesis_time, + hash, + schemeID: fixture.schemeID, + }; +} + +function beacon(): Beacon { + return { + round: fixture.round, + randomness: fixture.randomness ?? fixture.signature, + signature: fixture.signature, + }; +} + +function setEnv( + t: TestContext, + values: Record, +): void { + const previous = new Map(); + for (const [key, value] of Object.entries(values)) { + previous.set(key, process.env[key]); + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + t.after(() => { + for (const [key, value] of previous) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }); +} + +function stubDrand( + t: TestContext, + info: ChainInfo, + calls: string[], +): void { + t.mock.method(globalThis, "fetch", async (input: string | URL | Request) => { + const url = + typeof input === "string" + ? input + : input instanceof URL + ? input.toString() + : input.url; + calls.push(url); + const body = url.endsWith("/info") ? info : beacon(); + return new Response(JSON.stringify(body), { + status: 200, + headers: { "content-type": "application/json" }, + }); + }); +} + +async function fetchRoundAfterChainCheck(): Promise { + const config = loadDrandConfig(); + const info = await getChainInfo(config); + await getBeacon(fixture.round, config); + return info; +} + +test("matching chain-hash fixture is accepted before round data", async (t) => { + const calls: string[] = []; + setEnv(t, { + [DRAND_CHAIN_HASH_ENV]: fixture.chain_hash, + [DRAND_API_URL_ENV]: API_BASE, + }); + stubDrand(t, chainInfo(), calls); + + assert.deepEqual(await fetchRoundAfterChainCheck(), chainInfo()); + assert.deepEqual(calls, [ + `${API_BASE}/${fixture.chain_hash}/info`, + `${API_BASE}/${fixture.chain_hash}/public/${fixture.round}`, + ]); +}); + +test("mismatching chain-hash fixture rejects before round data", async (t) => { + const calls: string[] = []; + setEnv(t, { + [DRAND_CHAIN_HASH_ENV]: fixture.chain_hash, + [DRAND_API_URL_ENV]: API_BASE, + }); + stubDrand(t, chainInfo(MISMATCHED_HASH), calls); + + await assert.rejects( + fetchRoundAfterChainCheck(), + (err: unknown) => { + assert.ok(err instanceof DrandChainHashMismatchError); + assert.equal(err.code, "DRAND_CHAIN_HASH_MISMATCH"); + assert.equal(err.message, CHAIN_HASH_MISMATCH_ERROR); + assert.ok(!`${err.name}: ${err.message}`.includes(MISMATCHED_HASH)); + assert.ok(!`${err.name}: ${err.message}`.includes(fixture.chain_hash)); + return true; + }, + ); + assert.deepEqual(calls, [`${API_BASE}/${fixture.chain_hash}/info`]); +}); + +test("missing configured chain hash fails before any fetch", async (t) => { + const calls: string[] = []; + setEnv(t, { + [DRAND_CHAIN_HASH_ENV]: undefined, + [DRAND_API_URL_ENV]: API_BASE, + }); + stubDrand(t, chainInfo(), calls); + + await assert.rejects(fetchRoundAfterChainCheck(), { + message: CHAIN_HASH_REQUIRED_ERROR, + }); + assert.deepEqual(calls, []); +}); + +test("malformed configured chain hash fails before any fetch", async (t) => { + const calls: string[] = []; + setEnv(t, { + [DRAND_CHAIN_HASH_ENV]: "not-a-chain-hash", + [DRAND_API_URL_ENV]: API_BASE, + }); + stubDrand(t, chainInfo(), calls); + + await assert.rejects(fetchRoundAfterChainCheck(), { + message: CHAIN_HASH_INVALID_ERROR, + }); + assert.deepEqual(calls, []); +}); diff --git a/services/drand-tools/src/index.ts b/services/drand-tools/src/index.ts index f2519367..2f34e144 100644 --- a/services/drand-tools/src/index.ts +++ b/services/drand-tools/src/index.ts @@ -6,7 +6,12 @@ const diagnostics = createLogger("services.drand-tools.src.index"); // the contract must use, and emits the exact Soroban-encoded constants for the // deploy configuration (drand_pubkey, negated G2 generator, DST). -import { getChainInfo, getBeacon } from "./quicknet.js"; +import { + CHAIN_HASH_MISMATCH_ERROR, + DrandChainHashMismatchError, + getChainInfo, + getBeacon, +} from "./quicknet.js"; import { detectMessageVariant, DST } from "./parity.js"; import { encodeG1, @@ -83,6 +88,10 @@ async function main() { } main().catch((err) => { - diagnostics.error("harness-error", "harness error:", { "err_0": normalizeError(err) }); + if (err instanceof DrandChainHashMismatchError) { + diagnostics.error("chain-hash-mismatch", CHAIN_HASH_MISMATCH_ERROR); + } else { + diagnostics.error("harness-error", "harness error:", { "err_0": normalizeError(err) }); + } process.exitCode = 1; }); diff --git a/services/drand-tools/src/quicknet.ts b/services/drand-tools/src/quicknet.ts index 768a4c52..976d18c3 100644 --- a/services/drand-tools/src/quicknet.ts +++ b/services/drand-tools/src/quicknet.ts @@ -5,7 +5,18 @@ export const QUICKNET_HASH = "52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971"; -const API = process.env.DRAND_API_URL ?? "https://api.drand.sh"; +export const DRAND_CHAIN_HASH_ENV = "DRAND_CHAIN_HASH"; +export const DRAND_API_URL_ENV = "DRAND_API_URL"; +export const DEFAULT_DRAND_API_URL = "https://api.drand.sh"; +export const CHAIN_HASH_REQUIRED_ERROR = "DRAND_CHAIN_HASH is required"; +export const CHAIN_HASH_INVALID_ERROR = + "DRAND_CHAIN_HASH must be a 64-character hex string"; +export const CHAIN_HASH_MISMATCH_ERROR = "drand chain hash mismatch"; + +export interface DrandConfig { + apiUrl: string; + expectedChainHash: string; +} export interface ChainInfo { public_key: string; // compressed G2, hex (96 bytes) @@ -21,14 +32,68 @@ export interface Beacon { signature: string; // compressed G1, hex (48 bytes) } -export async function getChainInfo(): Promise { - const res = await fetch(`${API}/${QUICKNET_HASH}/info`); +export class DrandChainHashMismatchError extends Error { + readonly code = "DRAND_CHAIN_HASH_MISMATCH"; + + constructor() { + super(CHAIN_HASH_MISMATCH_ERROR); + this.name = "DrandChainHashMismatchError"; + } +} + +function normalizeHash(value: string): string { + return value.trim().toLowerCase(); +} + +function isChainHash(value: string): boolean { + return /^[0-9a-f]{64}$/.test(value); +} + +export function loadDrandConfig( + env: Record = process.env, +): DrandConfig { + const rawHash = env[DRAND_CHAIN_HASH_ENV]; + if (!rawHash || rawHash.trim() === "") { + throw new Error(CHAIN_HASH_REQUIRED_ERROR); + } + const expectedChainHash = normalizeHash(rawHash); + if (!isChainHash(expectedChainHash)) { + throw new Error(CHAIN_HASH_INVALID_ERROR); + } + const apiUrl = env[DRAND_API_URL_ENV]?.trim() || DEFAULT_DRAND_API_URL; + return { + apiUrl: apiUrl.replace(/\/+$/, ""), + expectedChainHash, + }; +} + +export function assertChainHashMatches( + info: ChainInfo, + expectedChainHash: string, +): void { + const actual = typeof info?.hash === "string" ? normalizeHash(info.hash) : ""; + if (!isChainHash(actual) || actual !== normalizeHash(expectedChainHash)) { + throw new DrandChainHashMismatchError(); + } +} + +export async function getChainInfo( + config: DrandConfig = loadDrandConfig(), +): Promise { + const res = await fetch(`${config.apiUrl}/${config.expectedChainHash}/info`); if (!res.ok) throw new Error(`info HTTP ${res.status}`); - return (await res.json()) as ChainInfo; + const info = (await res.json()) as ChainInfo; + assertChainHashMatches(info, config.expectedChainHash); + return info; } -export async function getBeacon(round: number | "latest"): Promise { - const res = await fetch(`${API}/${QUICKNET_HASH}/public/${round}`); +export async function getBeacon( + round: number | "latest", + config: DrandConfig = loadDrandConfig(), +): Promise { + const res = await fetch( + `${config.apiUrl}/${config.expectedChainHash}/public/${round}`, + ); if (!res.ok) throw new Error(`beacon ${round} HTTP ${res.status}`); return (await res.json()) as Beacon; }