Firebreak

Reference implementation

Council signing

Threshold signatures with the Zcash Foundation's FROST, wrapped in ROAST so disruptive signers cannot stall the Council.

Source
7 files, 626 lines
Tests
4 files, 19 cases
Paper
thm:blocneutral

FROST council signatures

Purpose

The paper gives the Inspection Council a threshold key K_C, generated by distributed key generation and used with FROST so that any t of n signers can sign and fewer cannot. This module is a working demo of that on an existing library, with no cryptography written here: the Zcash Foundation's FROST (frost-core and frost-secp256k1-tr, the BIP340/Taproot ciphersuite) compiled to WebAssembly, plus a typed TypeScript wrapper that runs in Node and in browsers. The group key is used as K_C in the bond's 2-of-2 leaf (src/bond), the Council signs through the ROAST coordinator in src/roast, and bitcoind accepts the resulting signatures (test/regtest). Share refresh (resharing that keeps K_C) is wrapped and tested.

Library and build

Item Version
frost-core 3.0.0 (crates.io, published 2026-04-23)
frost-secp256k1-tr 3.0.0 (crates.io, published 2026-04-23)
rand_core / rand_chacha 0.6.4 / 0.3.1
wasm-bindgen (crate and CLI) 0.2.130
rustc used for the committed build 1.100.0

frost-wasm/ is the Rust crate (src/lib.rs only moves bytes); frost-wasm/build.sh rebuilds src/frost/wasm/ (frost_bg.wasm, frost.js, frost.d.ts, wasm-bindgen --target web). The build output is committed, so tests, the site and Vercel need no Rust. build.sh refuses to run if the wasm-bindgen CLI does not match Cargo.lock.

Audit status (read from the ZF FROST README, 2026-11-27)

The README says NCC Group audited "the v0.6.0 release (corresponding to commit 5fa17ed)" of frost-core, frost-ed25519, frost-ed448, frost-p256, frost-secp256k1 and frost-ristretto255, including "key generation (both trusted dealer and DKG) and FROST signing", and states: "This does not include frost-secp256k1-tr and rerandomized FROST." The report is linked as research.nccgroup.com/2023/10/23/public-report-zcash-frost-security-assessment/.

So, precisely: the ciphersuite this demo uses (frost-secp256k1-tr) was not in the audit's scope, and the frost-core version used here (3.0.0) is later than the audited 0.6.0. frost-secp256k1-tr was added in 2.1.0 (frost-core CHANGELOG; first published on crates.io on 2025-01-15), after the audit. The README calls the crates "stable and feature complete"; that is the maintainers' statement, not an audit finding. We could not open the NCC report itself (the link now redirects to a generic index), so nothing here relies on its contents.

Formats

Every library object crosses the wasm boundary as hex of the library's own canonical serialization (serialize() / deserialize()): secret shares, key packages, the public key package, nonces, commitments, signing packages and signature shares. Participants are identified by the integers 1..n. Maps keyed by participant are JSON objects ({"1": "<hex>", ...}). The group key is returned both as 33-byte SEC1 (groupKey) and as the 32-byte x-only BIP340 key (groupKeyXOnly) that signatures verify under. Signatures are 64-byte BIP340. Errors come back as {"error": "...", "culprits": [ids]} and are thrown as FrostError with culprits.

Flow

keygen (one of):
  trusted dealer:  keygenDealer(t, n, seed)  -> shares[i] (secretShare, keyPackage), publicKeyPackage
                   keyPackageFromSecretShare(secretShare)  -- receiver checks its share against the VSS commitment
  DKG (paper):     dkgPart1(i) -> broadcast package_i
                   dkgPart2(secret_i, {package_j}) -> per-recipient packages
                   dkgPart3(secret2_i, {package_j}, {received_j}) -> keyPackage_i, publicKeyPackage
                   (runDkg runs all three rounds for n simulated signers)

sign (any t signers S, coordinator C):
  signer i in S:   signRound1(keyPackage_i, seed) -> nonces_i (secret), commitments_i -> C
  C:               makeSigningPackage({commitments_i}, message) -> signingPackage -> signers
  signer i in S:   signRound2(signingPackage, nonces_i, keyPackage_i) -> share_i -> C
  C:               aggregate(signingPackage, {share_i}, publicKeyPackage)
                     -> 64-byte BIP340 signature valid under groupKeyXOnly
                     or FrostError naming every signer whose share fails (CheaterDetection::AllCheaters)
  C (per share):   verifyShare(signingPackage, i, share_i, publicKeyPackage) -> true/false
                     (frost_core::verify_signature_share; ROAST uses it to mark a signer malicious)

refresh (resharing that keeps K_C; frost_core::keys::refresh):
  trusted dealer:  refreshDealer(publicKeyPackage, ids, seed) -> zeroShares[i], new publicKeyPackage (same group key)
                   refreshShare(zeroShare_i, keyPackage_i) -> new keyPackage_i
  dealerless:      refresh_dkg_part1/2 and refresh_dkg_shares (runRefreshDkg runs them for simulated signers)
  Refresh keeps t; it can drop participants (not add them).

The plain aggregate applies no Taproot tweak, so signatures verify under the untweaked x-only group key, which is what a tapscript <P_c> OP_CHECKSIG needs. The library normalizes the group key to even y internally (BIP340), so odd-y group keys work too.

Randomness

Every randomized call takes a 32-byte seed and runs ChaCha20Rng::from_seed. If the caller passes no seed, the wrapper draws one from crypto.getRandomValues (the platform CSPRNG, in Node and browsers), so real use gets OS randomness without getrandom in the wasm (no crate in the tree depends on it). Fixed seeds exist only to make demos and tests reproducible. Never reuse a round-1 seed for two signing sessions with the same key package: the same seed gives the same nonces, and two signatures with the same nonces on different messages reveal the signer's share. deriveSeed(master, label) and the demo helpers thresholdSign and runDkg derive per-session seeds from labels and are for demos only.

Loading (Node, browser, Next.js)

await initFrost() once, then call the functions synchronously.

  • Node (22.3+): initFrost() reads wasm/frost_bg.wasm from disk through process.getBuiltinModule("node:fs"), so no import "node:fs" reaches a browser bundle.
  • Browser: initFrost() lets the glue fetch new URL("./wasm/frost_bg.wasm", import.meta.url); webpack 5, Turbopack and Vite emit the .wasm as a static asset from that pattern.
  • Any environment: initFrost(source) accepts a URL, a Response, bytes or a compiled WebAssembly.Module.

For the Next.js site: import from @firebreak/protocol/frost/index inside a client component ("use client") and call await initFrost() in an effect before signing. If a bundler setup does not emit the asset, copy src/frost/wasm/frost_bg.wasm into apps/web/public/ and call initFrost("/frost_bg.wasm"). Do not run it in a server component: nothing on the server needs it, and server bundles rewrite import.meta.url.

Bloc-neutral thresholds

isBlocNeutral(t, n, w) and blocNeutralThresholds(n, w) implement the paper's w < t <= n - w (no plausible coalition of w signers can forge or deny), which has a solution exactly when 2w + 1 <= n.

Security properties and the tests that check them

Property Test (test/frost/)
(2,3), (3,5), (5,7): every t-subset signs; @noble/curves schnorr.verify (an independent implementation) accepts under the x-only group key; the library agrees; a different message fails frost.test.ts "(t,n): every t-subset ..."
Works for both parities of the group key "signs correctly whatever the parity ..."
Reproducible from a seed, distinct across seeds "is reproducible from a seed ..."
t-1 signers cannot complete a signature "refuses to sign with t-1 participants"; DKG test
t-1 honest shares plus a substituted share fail, and the substitute is named "t-1 honest shares plus a forged share ..."
Corrupted signature shares are identified at aggregation, all of them "identifies every corrupted signature share ..."
Every single-byte corruption of a dealer's secret share fails the VSS check "rejects every single-byte corruption ..."
(3,5) DKG: all participants agree on the group key; any 3 sign "distributed key generation"
Loads from a Response (the browser fetch path); refuses calls before loading; default seeds come from the CSPRNG load.test.ts
The group key works as K_C in the bond's 2-of-2 leaf and bitcoind accepts it test/bond "FROST group key as K_C"; test/regtest (3-of-5 DKG key: notices, slashes from B and N mined)
Dealer refresh keeps the group key; new shares sign; a mix of old and new shares fails refresh.test.ts "trusted-dealer refresh ..."
Refresh can remove a participant, whose stale share then signs with nobody "refresh can remove a participant ..."
Dealerless refresh of a DKG key keeps the group key; any 3 new shares sign; stale shares fail "dealerless (DKG-style) refresh ..."
Per-share verification accepts an honest share and rejects a corrupted one "accepts an honest share and rejects a corrupted one"
ROAST: t honest signers succeed despite a malicious and a silent signer test/roast (see src/roast/SPEC.md)
Bloc-neutral rule "bloc-neutral thresholds"

Interpretations

  • Interpretation: trusted dealer for quick demos, DKG for the council. The paper specifies DKG; the regtest suite uses a 3-of-5 DKG key. The dealer path is kept for the site's interactive demo, and the dealer sees the whole key.
  • Interpretation: ROAST lives in src/roast, a TypeScript coordinator over these rounds that uses verifyShare for cheater identification. No new cryptography.
  • Resharing condition (operational requirement, not enforceable in code). The paper's security argument needs that no plausible coalition ever holds t shares of one sharing. Refresh makes old shares useless only if every holder deletes them: a signer who keeps its old share keeps a vote in the old sharing, and t such hoarded shares still sign for the same K_C (the test "old and new shares do not mix" shows only that shares from different sharings cannot be combined, not that old ones are gone). Code cannot prove deletion. Departing signers must be removed by a refresh that excludes them, and the Council's procedures must ensure that across all sharings ever issued no plausible coalition accumulates t shares of any one of them.

Open questions for the paper authors

  1. Audit coverage. The Taproot ciphersuite a Bitcoin-settled council needs is outside the only published audit of this library. The paper should not describe the signing stack as audited without qualification.
  2. Resharing scope. The library's refresh keeps t and can remove but not add participants; adding a signer or changing t needs a new DKG and a new K_C, which forces every bond to roll over (bond SPEC, question 8). The paper should say whether resharing may change t and n, and how it ensures old shares are destroyed.
  3. Threshold decryption for whistleblower evidence is a different primitive (threshold encryption) and is not provided by FROST.

ROAST coordinator

Purpose

The paper's Council signs with FROST through ROAST (Ruffing, Ronge, Jin, Schneider-Bensch, Schroeder, CCS 2022), so that any t honest, responsive signers produce a signature even while other signers send invalid shares or never answer. This module is the coordinator's protocol logic in TypeScript over the FROST rounds in src/frost; it adds no cryptography. A deterministic network simulation (simulateRoast) drives it in tests and in the site.

Formats

  • Signer to coordinator: { from, commitments, reply? }, where commitments is a fresh round-1 commitment (hex, library serialization) and reply is { session, share } for the session the signer was last asked to sign. Every reply carries the signer's next commitment, as in ROAST.
  • Coordinator to signer: { kind: "sign-request", session, to, commitments }, where commitments maps the session's t signers to the commitments it will sign with. Signers rebuild the signing package from these and the message, so they check what they sign.
  • Coordinator outputs: { kind: "malicious", signer, session } and { kind: "done", session, signers, signature } (64-byte BIP340).

Flow

R := {}  (responsive signers with a fresh commitment), M := {} (malicious)
on message from i (ignored if i is in M, unknown, or a result exists):
  if i is in an open session s:
      the message must carry a reply for s, else it is ignored
      verifyShare(s.package, i, share)  fails -> M += i, s fails, emit "malicious"   (i never used again)
                                        holds -> s.valid[i] = share
      if |s.valid| = t: signature = aggregate(...); check it verifies; emit "done"
  R[i] := i's new commitment
  if |R| >= t: take t signers from R (lowest ids), remove them from R,
               build the signing package, open session s', send sign requests

A session never completes without t shares that each passed verifyShare, and the aggregate is checked against the group key before it is output. A signer is in at most one open session; a silent signer leaves its session open forever, which costs nothing because new sessions start as soon as t other signers are responsive. With at most n - t faulty signers, at most n - t + 1 sessions start.

Security properties and the tests that check them

Property Test (test/roast/roast.test.ts)
Honest signers produce a valid BIP340 signature (checked with @noble/curves), marking nobody, within n - t + 1 sessions "signs when everyone is honest ..."
n = 5, t = 3, one signer sending invalid shares and one never responding: a valid BIP340 signature over 40 delivery orders; the signed session has exactly t verified shares from honest signers; at most n - t + 1 sessions; once marked, the malicious signer is in no later session "with one signer sending invalid shares and one never responding ..."
With only two honest signers no signature or "done" is ever output, and no session holds t valid shares "never outputs a signature without t valid shares ..."
A share valid for another signer, or with one bit flipped, marks its sender malicious; later messages from it are ignored "rejects a forged share, marks its sender, and ignores it afterwards"
The Council's signatures in the regtest suite (notices, slashes, including one with a malicious and a silent signer) come from this coordinator and bitcoind accepts them test/regtest/bond.test.ts

Interpretations

  • Interpretation: session choice. When more than t signers are responsive the coordinator takes the t lowest ids. ROAST allows any choice.
  • Interpretation: one coordinator. ROAST assumes a coordinator that may be unreliable but cannot forge; the paper does not say who runs it. Running several coordinators in parallel (as the ROAST paper suggests for a faulty coordinator) is not built.
  • The simulation's delivery order uses a seeded xorshift generator; it never touches keys or nonces, whose seeds come from deriveSeed (demo) or the CSPRNG (real use).

Open questions for the paper authors

  1. Who coordinates, and what if the coordinator withholds? A coordinator can stall signing (for example, delay a slash) without being caught by ROAST. The paper should name the coordinator role and a fallback.
  2. Nonce storage. Each signer keeps one secret nonce per outstanding commitment; a signer that crashes and restores old state could reuse a nonce and leak its share. Signer implementations need durable, monotonic nonce state.

Source

The code

src/frost/council.ts18 lines
/**
 * The paper's bloc-neutral threshold rule for the Inspection Council:
 * no plausible coalition of w signers can forge (w < t) or deny (t <= n - w).
 */

/** True when threshold t is bloc-neutral for n signers against coalitions of up to w. */
export function isBlocNeutral(t: number, n: number, w: number): boolean {
  if (![t, n, w].every(Number.isInteger) || n < 1 || t < 1 || w < 0) return false;
  return w < t && t <= n - w;
}

/** Every bloc-neutral threshold for n signers and coalition size w (empty unless 2w + 1 <= n). */
export function blocNeutralThresholds(n: number, w: number): number[] {
  const out: number[] = [];
  for (let t = w + 1; t <= n - w; t++) out.push(t);
  return out;
}

View on GitHub

src/frost/frost.ts266 lines
/**
 * Typed calls into the Zcash Foundation FROST library (frost-secp256k1-tr 3.0.0)
 * compiled to wasm. Every library object travels as hex of its canonical
 * serialization; participant identifiers are the integers 1..n.
 */
import { sha256 } from "@noble/hashes/sha2.js";
import { bytesToHex, concatBytes, hexToBytes, utf8ToBytes } from "@noble/hashes/utils.js";
import * as wasm from "./wasm/frost.js";
import { assertLoaded } from "./load";

/** Hex of a library object (key package, nonces, commitments, shares, ...). */
export type Hex = string;
/** Values keyed by participant identifier (1..n). */
export type ById<T> = Record<number, T>;

/** A FROST failure, with the identifiers of any participants the library blamed. */
export class FrostError extends Error {
  /** Participants whose shares or packages failed verification. */
  readonly culprits: number[];
  constructor(message: string, culprits: number[]) {
    super(message);
    this.name = "FrostError";
    this.culprits = culprits;
  }
}

/** Calls a wasm export and turns its JSON error string into a FrostError. */
function call<T>(fn: () => string): T {
  assertLoaded();
  let out: string;
  try {
    out = fn();
  } catch (e) {
    if (typeof e === "string") {
      const parsed = JSON.parse(e) as { error: string; culprits: number[] };
      throw new FrostError(parsed.error, parsed.culprits);
    }
    throw e;
  }
  return JSON.parse(out) as T;
}

/** 32 bytes from the platform CSPRNG (crypto.getRandomValues), the default for every seed. */
export function freshSeed(): Uint8Array {
  return globalThis.crypto.getRandomValues(new Uint8Array(32));
}

/** Derives a per-call seed from a demo master seed and a label. Demo use only: see SPEC.md on nonce reuse. */
export function deriveSeed(master: Uint8Array, label: string): Uint8Array {
  return sha256(concatBytes(master, utf8ToBytes(label)));
}

/** JSON object with string keys for the wasm side. */
function idMap(m: ById<Hex>): string {
  return JSON.stringify(Object.fromEntries(Object.entries(m)));
}

/** Converts the wasm side's string-keyed map to ById. */
function fromIdMap<T>(m: Record<string, T>): ById<T> {
  return Object.fromEntries(Object.entries(m).map(([k, v]) => [Number(k), v]));
}

/** The group's public key in the forms Bitcoin needs. */
export interface GroupKey {
  /** 33-byte SEC1 compressed group key, as the library serializes it. */
  readonly groupKey: Uint8Array;
  /** 32-byte x-only key: the BIP340 public key FROST signatures verify under (P_c in the bond). */
  readonly groupKeyXOnly: Uint8Array;
  /** Hex of the library's PublicKeyPackage (group key plus every verifying share). */
  readonly publicKeyPackage: Hex;
}

/** Output of trusted-dealer key generation. */
export interface DealerKeygen extends GroupKey {
  readonly shares: ReadonlyArray<{ readonly id: number; readonly secretShare: Hex; readonly keyPackage: Hex }>;
}

interface RawGroup {
  group_key: string;
  group_key_xonly: string;
  public_key_package: string;
}

/** Maps the wasm JSON group fields to GroupKey. */
function toGroup(r: RawGroup): GroupKey {
  return {
    groupKey: hexToBytes(r.group_key),
    groupKeyXOnly: hexToBytes(r.group_key_xonly),
    publicKeyPackage: r.public_key_package,
  };
}

/** Trusted-dealer keygen for t-of-n (the dealer sees the whole key; use DKG for a real council). */
export function keygenDealer(t: number, n: number, seed: Uint8Array = freshSeed()): DealerKeygen {
  const r = call<RawGroup & { shares: Array<{ id: number; secret_share: string; key_package: string }> }>(() =>
    wasm.keygen_dealer(t, n, bytesToHex(seed)),
  );
  return {
    ...toGroup(r),
    shares: r.shares.map((s) => ({ id: s.id, secretShare: s.secret_share, keyPackage: s.key_package })),
  };
}

/** Checks a dealer's secret share against its VSS commitment and returns the key package. */
export function keyPackageFromSecretShare(secretShare: Hex): Hex {
  return call<string>(() => wasm.key_package_from_secret_share(secretShare));
}

/** DKG round 1 for participant `id`. */
export function dkgPart1(id: number, n: number, t: number, seed: Uint8Array = freshSeed()): { secretPackage: Hex; package: Hex } {
  const r = call<{ secret_package: string; package: string }>(() => wasm.dkg_part1(id, n, t, bytesToHex(seed)));
  return { secretPackage: r.secret_package, package: r.package };
}

/** DKG round 2: from the others' round-1 packages, one package per recipient. */
export function dkgPart2(secretPackage: Hex, round1Packages: ById<Hex>): { secretPackage: Hex; packages: ById<Hex> } {
  const r = call<{ secret_package: string; packages: Record<string, string> }>(() =>
    wasm.dkg_part2(secretPackage, idMap(round1Packages)),
  );
  return { secretPackage: r.secret_package, packages: fromIdMap(r.packages) };
}

/** DKG round 3: this participant's key package and the group key. */
export function dkgPart3(
  round2Secret: Hex,
  round1Packages: ById<Hex>,
  round2Packages: ById<Hex>,
): GroupKey & { keyPackage: Hex } {
  const r = call<RawGroup & { key_package: string }>(() =>
    wasm.dkg_part3(round2Secret, idMap(round1Packages), idMap(round2Packages)),
  );
  return { ...toGroup(r), keyPackage: r.key_package };
}

/** Runs all three DKG rounds for n simulated participants in one process (a demo; real signers run apart). */
export function runDkg(t: number, n: number, master: Uint8Array = freshSeed()): GroupKey & { keyPackages: ById<Hex> } {
  const ids = Array.from({ length: n }, (_, i) => i + 1);
  const r1 = new Map(ids.map((id) => [id, dkgPart1(id, n, t, deriveSeed(master, `dkg1/${id}`))]));
  const others = <T>(m: Map<number, T>, me: number, pick: (v: T) => Hex): ById<Hex> =>
    Object.fromEntries([...m].filter(([k]) => k !== me).map(([k, v]) => [k, pick(v)]));
  const r2 = new Map(ids.map((id) => [id, dkgPart2(r1.get(id)!.secretPackage, others(r1, id, (v) => v.package))]));
  const outs = ids.map((id) => {
    const received: ById<Hex> = {};
    for (const [from, v] of r2) if (from !== id) received[from] = v.packages[id]!;
    return [id, dkgPart3(r2.get(id)!.secretPackage, others(r1, id, (v) => v.package), received)] as const;
  });
  const first = outs[0]![1];
  for (const [, o] of outs) {
    if (o.publicKeyPackage !== first.publicKeyPackage) throw new FrostError("DKG participants disagree on the group key", []);
  }
  return {
    groupKey: first.groupKey,
    groupKeyXOnly: first.groupKeyXOnly,
    publicKeyPackage: first.publicKeyPackage,
    keyPackages: Object.fromEntries(outs.map(([id, o]) => [id, o.keyPackage])),
  };
}

/** Signing round 1: secret nonces (never reuse) and public commitments. */
export function signRound1(keyPackage: Hex, seed: Uint8Array = freshSeed()): { nonces: Hex; commitments: Hex } {
  return call(() => wasm.sign_round1(keyPackage, bytesToHex(seed)));
}

/** Coordinator: the signing package for the chosen signers' commitments and a message. */
export function makeSigningPackage(commitments: ById<Hex>, message: Uint8Array): Hex {
  return call<string>(() => wasm.signing_package(idMap(commitments), bytesToHex(message)));
}

/** Signing round 2: this participant's signature share. */
export function signRound2(signingPackage: Hex, nonces: Hex, keyPackage: Hex): Hex {
  return call<string>(() => wasm.sign_round2(signingPackage, nonces, keyPackage));
}

/** Aggregates shares into a 64-byte BIP340 signature; throws FrostError naming every bad share. */
export function aggregate(signingPackage: Hex, shares: ById<Hex>, publicKeyPackage: Hex): Uint8Array {
  return hexToBytes(call<string>(() => wasm.aggregate(signingPackage, idMap(shares), publicKeyPackage)));
}

/** The library's own signature check against the group key. */
export function verifyWithLibrary(publicKeyPackage: Hex, message: Uint8Array, signature: Uint8Array): boolean {
  return call<boolean>(() => wasm.verify(publicKeyPackage, bytesToHex(message), bytesToHex(signature)));
}

/** Runs both signing rounds and aggregation for the given signers (a demo of one coordinator session). */
export function thresholdSign(
  keyPackages: ById<Hex>,
  signers: readonly number[],
  message: Uint8Array,
  publicKeyPackage: Hex,
  master: Uint8Array = freshSeed(),
): Uint8Array {
  const r1 = new Map(signers.map((id) => [id, signRound1(keyPackages[id]!, deriveSeed(master, `r1/${id}`))]));
  const sp = makeSigningPackage(Object.fromEntries([...r1].map(([id, v]) => [id, v.commitments])), message);
  const shares = Object.fromEntries(signers.map((id) => [id, signRound2(sp, r1.get(id)!.nonces, keyPackages[id]!)]));
  return aggregate(sp, shares, publicKeyPackage);
}

/** Checks one signer's share on its own against its verifying share (used by the ROAST coordinator). */
export function verifyShare(signingPackage: Hex, id: number, share: Hex, publicKeyPackage: Hex): boolean {
  return call<boolean>(() => wasm.verify_share(signingPackage, id, share, publicKeyPackage));
}

/** Trusted-dealer refresh: zero-shares for `ids` (others are removed) and the refreshed public key package. */
export function refreshDealer(
  publicKeyPackage: Hex,
  ids: readonly number[],
  seed: Uint8Array = freshSeed(),
): GroupKey & { zeroShares: ById<Hex> } {
  const r = call<RawGroup & { zero_shares: Record<string, string> }>(() =>
    wasm.refresh_dealer(publicKeyPackage, JSON.stringify(ids), bytesToHex(seed)),
  );
  return { ...toGroup(r), zeroShares: fromIdMap(r.zero_shares) };
}

/** A participant applies its zero-share and gets a fresh share of the same group key. */
export function refreshShare(zeroShare: Hex, keyPackage: Hex): Hex {
  return call<string>(() => wasm.refresh_share(zeroShare, keyPackage));
}

/** Runs the dealerless (DKG-style) refresh for every listed participant in one process (a demo). */
export function runRefreshDkg(
  t: number,
  keyPackages: ById<Hex>,
  publicKeyPackage: Hex,
  master: Uint8Array = freshSeed(),
): GroupKey & { keyPackages: ById<Hex> } {
  const ids = Object.keys(keyPackages).map(Number);
  const n = ids.length;
  const r1 = new Map(
    ids.map((id) => {
      const r = call<{ secret_package: string; package: string }>(() =>
        wasm.refresh_dkg_part1(id, n, t, bytesToHex(deriveSeed(master, `refresh1/${id}`))),
      );
      return [id, r] as const;
    }),
  );
  const others = (me: number): ById<Hex> =>
    Object.fromEntries([...r1].filter(([k]) => k !== me).map(([k, v]) => [k, v.package]));
  const r2 = new Map(
    ids.map((id) => {
      const r = call<{ secret_package: string; packages: Record<string, string> }>(() =>
        wasm.refresh_dkg_part2(r1.get(id)!.secret_package, idMap(others(id))),
      );
      return [id, { secretPackage: r.secret_package, packages: fromIdMap(r.packages) }] as const;
    }),
  );
  const outs = ids.map((id) => {
    const received: ById<Hex> = {};
    for (const [from, v] of r2) if (from !== id) received[from] = v.packages[id]!;
    const r = call<RawGroup & { key_package: string }>(() =>
      wasm.refresh_dkg_shares(r2.get(id)!.secretPackage, idMap(others(id)), idMap(received), publicKeyPackage, keyPackages[id]!),
    );
    return [id, { ...toGroup(r), keyPackage: r.key_package }] as const;
  });
  const first = outs[0]![1];
  for (const [, o] of outs) {
    if (o.publicKeyPackage !== first.publicKeyPackage) throw new FrostError("refresh participants disagree", []);
  }
  return {
    groupKey: first.groupKey,
    groupKeyXOnly: first.groupKeyXOnly,
    publicKeyPackage: first.publicKeyPackage,
    keyPackages: Object.fromEntries(outs.map(([id, o]) => [id, o.keyPackage])),
  };
}

View on GitHub

src/frost/load.ts52 lines
/**
 * Loads the FROST wasm module in Node or in a browser.
 *
 * Node: reads src/frost/wasm/frost_bg.wasm from disk through
 * process.getBuiltinModule, so no `import "node:fs"` reaches a browser bundle.
 * Browser: lets the wasm-bindgen glue fetch the file from
 * `new URL("./wasm/frost_bg.wasm", import.meta.url)`, a pattern webpack 5,
 * Turbopack and Vite all turn into an emitted static asset. A caller can also
 * pass bytes, a URL, a Response or a compiled WebAssembly.Module.
 */
import init, { type InitInput } from "./wasm/frost.js";

let ready: Promise<void> | null = null;
let loaded = false;

interface NodeBuiltins {
  getBuiltinModule?: (id: string) => unknown;
}

/** Reads the wasm bytes from disk when running under Node (22.3+); returns null elsewhere. */
function readWasmInNode(url: URL): Uint8Array | null {
  const proc = (globalThis as { process?: NodeBuiltins }).process;
  if (url.protocol !== "file:" || typeof proc?.getBuiltinModule !== "function") return null;
  const fs = proc.getBuiltinModule("node:fs") as { readFileSync(p: string): Uint8Array };
  const nodeUrl = proc.getBuiltinModule("node:url") as { fileURLToPath(u: URL): string };
  return fs.readFileSync(nodeUrl.fileURLToPath(url));
}

/** Initializes the wasm module once; later calls return the same promise. */
export function initFrost(source?: InitInput): Promise<void> {
  if (!ready) {
    ready = (async () => {
      let input: InitInput | undefined = source;
      if (input === undefined) {
        const url = new URL("./wasm/frost_bg.wasm", import.meta.url);
        input = readWasmInNode(url) ?? url;
      }
      await init({ module_or_path: input });
      loaded = true;
    })();
    ready.catch(() => {
      ready = null;
    });
  }
  return ready;
}

/** Throws unless initFrost() has finished. */
export function assertLoaded(): void {
  if (!loaded) throw new Error("FROST wasm not loaded: await initFrost() first");
}

View on GitHub

src/frost/index.ts34 lines
/**
 * FROST t-of-n threshold Schnorr (BIP340) signatures for the Inspection Council,
 * from the Zcash Foundation's frost-secp256k1-tr compiled to wasm. See SPEC.md.
 *
 * Call `await initFrost()` once before any other function.
 */
export { assertLoaded, initFrost } from "./load";
export {
  aggregate,
  deriveSeed,
  dkgPart1,
  dkgPart2,
  dkgPart3,
  freshSeed,
  FrostError,
  keygenDealer,
  keyPackageFromSecretShare,
  makeSigningPackage,
  refreshDealer,
  refreshShare,
  runRefreshDkg,
  runDkg,
  signRound1,
  signRound2,
  thresholdSign,
  verifyShare,
  verifyWithLibrary,
  type ById,
  type DealerKeygen,
  type GroupKey,
  type Hex,
} from "./frost";
export { blocNeutralThresholds, isBlocNeutral } from "./council";

View on GitHub

src/roast/coordinator.ts127 lines
/**
 * A ROAST coordinator (Ruffing, Ronge, Jin, Schneider-Bensch, Schroder, CCS 2022)
 * over the FROST rounds in src/frost.
 *
 * ROAST makes FROST robust and asynchronous: the coordinator never waits on a
 * particular signer. It keeps the set R of responsive signers, each with a fresh
 * nonce commitment, and starts a new signing session as soon as t of them are
 * available. Every reply carries the signer's next commitment, so honest signers
 * return to R as soon as they answer, while a silent signer only stalls the
 * sessions it is in. A signer whose share fails verification is marked malicious
 * and never used again. With at least t honest signers it finishes after at most
 * n - t + 1 sessions. No new cryptography: shares are checked and aggregated by
 * the ZF FROST library.
 */
import { aggregate, makeSigningPackage, verifyShare, verifyWithLibrary, type ById, type Hex } from "../frost";

/** A message from a signer: its next commitment and, if it was asked, its share for that session. */
export interface SignerMessage {
  readonly from: number;
  /** Fresh round-1 commitment for the next session. */
  readonly commitments: Hex;
  /** Present when answering a sign request. */
  readonly reply?: { readonly session: number; readonly share: Hex };
}

/** What the coordinator asks the transport to do. */
export type RoastAction =
  | { readonly kind: "sign-request"; readonly session: number; readonly to: number; readonly commitments: ById<Hex> }
  | { readonly kind: "malicious"; readonly signer: number; readonly session: number }
  | { readonly kind: "done"; readonly session: number; readonly signers: readonly number[]; readonly signature: Uint8Array };

/** One signing session and what came of it. */
export interface SessionRecord {
  readonly id: number;
  readonly signers: readonly number[];
  readonly commitments: ById<Hex>;
  readonly signingPackage: Hex;
  /** Shares that passed per-share verification. */
  readonly validShares: Map<number, Hex>;
  outcome: "pending" | "signed" | "failed";
}

/** Coordinator configuration. */
export interface RoastConfig {
  readonly t: number;
  /** All participant identifiers (1..n). */
  readonly signers: readonly number[];
  readonly message: Uint8Array;
  readonly publicKeyPackage: Hex;
}

/** The ROAST coordinator state machine. Feed it signer messages; act on the actions it returns. */
export class RoastCoordinator {
  private readonly responsive = new Map<number, Hex>(); // R, with each signer's latest commitment
  private readonly pendingSession = new Map<number, number>(); // signer -> session it was asked to sign in
  private readonly mal = new Set<number>();
  private readonly log: SessionRecord[] = [];
  private result: { signature: Uint8Array; session: number } | null = null;

  constructor(private readonly cfg: RoastConfig) {
    if (!Number.isInteger(cfg.t) || cfg.t < 1 || cfg.t > cfg.signers.length) throw new Error("need 1 <= t <= n");
  }

  /** Signers marked malicious (never used again). */
  get malicious(): ReadonlySet<number> {
    return this.mal;
  }

  /** Every session started so far. */
  get sessions(): readonly SessionRecord[] {
    return this.log;
  }

  /** The signature, once a session has collected t valid shares. */
  get signature(): Uint8Array | null {
    return this.result?.signature ?? null;
  }

  /** Handles one incoming message and returns the actions it triggers. */
  receive(msg: SignerMessage): RoastAction[] {
    const { from } = msg;
    if (this.result || this.mal.has(from) || !this.cfg.signers.includes(from)) return [];
    const actions: RoastAction[] = [];
    const asked = this.pendingSession.get(from);

    if (asked !== undefined) {
      // A signer in a session must answer that session; anything else is ignored until it does.
      if (!msg.reply || msg.reply.session !== asked) return [];
      const s = this.log[asked - 1]!;
      this.pendingSession.delete(from);
      if (!verifyShare(s.signingPackage, from, msg.reply.share, this.cfg.publicKeyPackage)) {
        this.mal.add(from);
        this.responsive.delete(from);
        s.outcome = "failed";
        return [{ kind: "malicious", signer: from, session: asked }];
      }
      s.validShares.set(from, msg.reply.share);
      if (s.validShares.size === this.cfg.t) {
        const signature = aggregate(s.signingPackage, Object.fromEntries(s.validShares), this.cfg.publicKeyPackage);
        if (!verifyWithLibrary(this.cfg.publicKeyPackage, this.cfg.message, signature)) throw new Error("aggregate failed to verify");
        s.outcome = "signed";
        this.result = { signature, session: s.id };
        actions.push({ kind: "done", session: s.id, signers: s.signers, signature });
        return actions;
      }
    } else if (msg.reply) {
      return []; // an answer nobody asked for
    }

    this.responsive.set(from, msg.commitments);
    if (this.responsive.size >= this.cfg.t) actions.push(...this.startSession());
    return actions;
  }

  /** Takes t responsive signers out of R and asks them to sign. */
  private startSession(): RoastAction[] {
    const chosen = [...this.responsive.keys()].sort((a, b) => a - b).slice(0, this.cfg.t);
    const commitments: ById<Hex> = Object.fromEntries(chosen.map((id) => [id, this.responsive.get(id)!]));
    for (const id of chosen) this.responsive.delete(id);
    const id = this.log.length + 1;
    const signingPackage = makeSigningPackage(commitments, this.cfg.message);
    this.log.push({ id, signers: chosen, commitments, signingPackage, validShares: new Map(), outcome: "pending" });
    for (const s of chosen) this.pendingSession.set(s, id);
    return chosen.map((to) => ({ kind: "sign-request", session: id, to, commitments }));
  }
}

View on GitHub

src/roast/simulate.ts116 lines
/**
 * A deterministic simulation of ROAST signers talking to a coordinator over an
 * asynchronous network, for tests and for the site's demo. Message delivery order
 * is shuffled by a seeded generator, so every interleaving is reproducible.
 */
import { bytesToHex, hexToBytes } from "@noble/hashes/utils.js";
import { deriveSeed, makeSigningPackage, signRound1, signRound2, type ById, type Hex } from "../frost";
import { RoastCoordinator, type RoastAction, type SessionRecord, type SignerMessage } from "./coordinator";

/** How a simulated signer behaves. */
export type Behavior = "honest" | "malicious" | "silent";

/** A simulated signer: keeps its secret nonces per commitment and uses each at most once. */
class SimSigner {
  private readonly nonces = new Map<Hex, Hex>();
  private counter = 0;

  constructor(
    readonly id: number,
    private readonly keyPackage: Hex,
    readonly behavior: Behavior,
    private readonly message: Uint8Array,
    private readonly master: Uint8Array,
  ) {}

  /** A fresh commitment (its nonces are remembered until used). */
  commit(): Hex {
    const r = signRound1(this.keyPackage, deriveSeed(this.master, `signer/${this.id}/${this.counter++}`));
    this.nonces.set(r.commitments, r.nonces);
    return r.commitments;
  }

  /** The signer's first message: just a commitment. */
  hello(): SignerMessage {
    return { from: this.id, commitments: this.commit() };
  }

  /** Answers a sign request, or returns null if silent or if the request reuses a spent commitment. */
  onRequest(session: number, commitments: ById<Hex>): SignerMessage | null {
    if (this.behavior === "silent") return null;
    const mine = commitments[this.id];
    const nonces = mine === undefined ? undefined : this.nonces.get(mine);
    if (nonces === undefined) return null;
    this.nonces.delete(mine!); // a nonce is never used twice
    const sp = makeSigningPackage(commitments, this.message); // built locally: the signer checks what it signs
    let share = signRound2(sp, nonces, this.keyPackage);
    if (this.behavior === "malicious") {
      const b = hexToBytes(share);
      b[b.length - 1]! ^= 0x01;
      share = bytesToHex(b);
    }
    return { from: this.id, commitments: this.commit(), reply: { session, share } };
  }
}

/** Options for a simulated ROAST run. */
export interface RoastRun {
  readonly t: number;
  readonly keyPackages: ById<Hex>;
  readonly publicKeyPackage: Hex;
  readonly message: Uint8Array;
  /** Behavior per signer; missing ids are honest. */
  readonly behaviors?: Readonly<Record<number, Behavior>>;
  /** Seed for the signers' nonces and for the delivery order. */
  readonly seed: Uint8Array;
}

/** Result of a run, including the event log a demo can replay. */
export interface RoastOutcome {
  readonly signature: Uint8Array | null;
  readonly sessions: readonly SessionRecord[];
  readonly malicious: ReadonlySet<number>;
  readonly events: readonly RoastAction[];
}

/** Small deterministic generator (xorshift32) for the delivery order; not used for any key or nonce. */
function shuffler(seed: Uint8Array): (n: number) => number {
  let x = (((seed[0] ?? 1) << 24) | ((seed[1] ?? 2) << 16) | ((seed[2] ?? 3) << 8) | (seed[3] ?? 4)) >>> 0 || 1;
  return (n: number) => {
    x ^= x << 13;
    x >>>= 0;
    x ^= x >>> 17;
    x ^= x << 5;
    x >>>= 0;
    return x % n;
  };
}

/** Runs ROAST to completion (a signature, or no messages left in flight). */
export function simulateRoast(run: RoastRun): RoastOutcome {
  const ids = Object.keys(run.keyPackages).map(Number).sort((a, b) => a - b);
  const signers = new Map(
    ids.map((id) => [id, new SimSigner(id, run.keyPackages[id]!, run.behaviors?.[id] ?? "honest", run.message, run.seed)]),
  );
  const coord = new RoastCoordinator({ t: run.t, signers: ids, message: run.message, publicKeyPackage: run.publicKeyPackage });
  const pick = shuffler(deriveSeed(run.seed, "delivery"));
  type InFlight = { toCoordinator: SignerMessage } | { toSigner: number; session: number; commitments: ById<Hex> };
  const queue: InFlight[] = ids.map((id) => ({ toCoordinator: signers.get(id)!.hello() }));
  const events: RoastAction[] = [];

  while (queue.length > 0 && !coord.signature) {
    const [next] = queue.splice(pick(queue.length), 1);
    if (!next) break;
    if ("toCoordinator" in next) {
      for (const a of coord.receive(next.toCoordinator)) {
        events.push(a);
        if (a.kind === "sign-request") queue.push({ toSigner: a.to, session: a.session, commitments: a.commitments });
      }
    } else {
      const reply = signers.get(next.toSigner)!.onRequest(next.session, next.commitments);
      if (reply) queue.push({ toCoordinator: reply });
    }
  }
  return { signature: coord.signature, sessions: coord.sessions, malicious: coord.malicious, events };
}

View on GitHub

src/roast/index.ts13 lines
/**
 * ROAST: robust asynchronous threshold signing for the Inspection Council, as a
 * coordinator over the ZF FROST rounds. See SPEC.md.
 */
export {
  RoastCoordinator,
  type RoastAction,
  type RoastConfig,
  type SessionRecord,
  type SignerMessage,
} from "./coordinator";
export { simulateRoast, type Behavior, type RoastOutcome, type RoastRun } from "./simulate";

View on GitHub