Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion services/drand-tools/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
164 changes: 164 additions & 0 deletions services/drand-tools/src/chain-hash.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string | undefined>,
): void {
const previous = new Map<string, string | undefined>();
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<ChainInfo> {
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, []);
});
13 changes: 11 additions & 2 deletions services/drand-tools/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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;
});
77 changes: 71 additions & 6 deletions services/drand-tools/src/quicknet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -21,14 +32,68 @@ export interface Beacon {
signature: string; // compressed G1, hex (48 bytes)
}

export async function getChainInfo(): Promise<ChainInfo> {
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<string, string | undefined> = 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<ChainInfo> {
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<Beacon> {
const res = await fetch(`${API}/${QUICKNET_HASH}/public/${round}`);
export async function getBeacon(
round: number | "latest",
config: DrandConfig = loadDrandConfig(),
): Promise<Beacon> {
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;
}
Expand Down
Loading