Firebreak

Reference implementation

Slashing predicates

The five cryptographic predicates and a model of optimistic verification.

Source
10 files, 446 lines
Tests
2 files, 24 cases
Paper
sec:app-protocol

Source

The code

src/predicates/device.ts18 lines
/**
 * The step every device-signed predicate starts with: an enrolled certificate
 * gives the chip's device key, and only data signed under that key counts.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { type ChipCert, verifyCert } from "../fgm";
import type { Authorities } from "./types";

/** pk_dev from a certificate signed by the manufacturer and the enrollment officer, or null. */
export function deviceKey(cert: ChipCert, auth: Authorities): Uint8Array | null {
  return verifyCert(cert, auth.manufacturerKey, auth.enrollmentKey) ? cert.pkDev : null;
}

/** True when a chip_id field names the certified chip. */
export function sameChip(chipId: Uint8Array, cert: ChipCert): boolean {
  return chipId instanceof Uint8Array && equalBytes(chipId, cert.chipId);
}

View on GitHub

src/predicates/equivocation.ts23 lines
/**
 * Equivocation: two reports with the same (chip_id, e), different contents and valid sigma_dev.
 *
 * An honest module signs exactly one report per epoch, so two different ones
 * prove its key was extracted or its firmware subverted.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { type ChipCert, type EpochReport, reportDigest, verifyReport } from "../fgm";
import { deviceKey, sameChip } from "./device";
import type { Authorities } from "./types";

/** True when a and b are different reports for the same chip and epoch, both signed by its device key. */
export function equivocation(a: EpochReport, b: EpochReport, cert: ChipCert, auth: Authorities): boolean {
  try {
    const pk = deviceKey(cert, auth);
    if (!pk || !sameChip(a.chipId, cert) || !sameChip(b.chipId, cert) || a.epoch !== b.epoch) return false;
    if (equalBytes(reportDigest(a), reportDigest(b))) return false;
    return verifyReport(a, pk) && verifyReport(b, pk);
  } catch {
    return false;
  }
}

View on GitHub

src/predicates/leaves.ts27 lines
/**
 * What an operator's epoch tree holds under each chip_id: the chip's signed
 * report, or a declared status explaining why there is none.
 *
 * Interpretation: the paper says omission is absence "without a declared
 * status" but does not say where statuses are declared. Here a declared
 * status is a leaf in the same operator tree, under the same chip_id, so one
 * non-membership proof shows both that the report is missing and that no
 * status was declared.
 */
import { concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
import { type EpochReport, reportDigest } from "../fgm";
import type { Entry } from "../ledger";

/** Reasons an operator may give for a chip with no report in an epoch. Interpretation: an illustrative list. */
export type DeclaredStatus = "maintenance" | "in-transit" | "decommissioned" | "destroyed";

/** Leaf for a chip's report: key chip_id, value 0x01 || H(report body) || sigma_dev. */
export function reportLeaf(r: EpochReport): Entry {
  return { key: r.chipId, value: concatBytes(Uint8Array.of(1), reportDigest(r), r.sig) };
}

/** Leaf for a declared status: key chip_id, value 0x02 || UTF-8 status. */
export function statusLeaf(chipId: Uint8Array, status: DeclaredStatus): Entry {
  return { key: chipId, value: concatBytes(Uint8Array.of(2), utf8ToBytes(status)) };
}

View on GitHub

src/predicates/location.ts57 lines
/**
 * Location: a report with valid sigma_dev whose distance-bounding transcript
 * is inconsistent with the licensed site.
 *
 * A distance-bounding round with a landmark bounds the chip's distance from
 * it from above: d(chip, landmark) <= c * rtt / 2, since no reply travels
 * faster than light. If the chip is within radius r of the site centre, the
 * triangle inequality gives d(site, landmark) <= r + c * rtt / 2. A round that
 * breaks this proves the chip was not at the site. Slow replies prove
 * nothing, since a chip can always add delay; only fast ones convict.
 *
 * All arithmetic is exact: positions in whole meters, rtt in nanoseconds, and
 * the comparison squared in bigints so no square root is taken.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { type ChipCert, type EpochReport, type License, licenseDigest, licenseId, verifyReport, verifySig } from "../fgm";
import { deviceKey, sameChip } from "./device";
import type { Authorities, Geometry, Point, Site } from "./types";

/** The speed of light in meters per second. */
export const C_M_PER_S = 299_792_458n;
const NS_PER_S = 1_000_000_000n;

/** Squared distance between two points, in square meters. */
export function distanceSq(a: Point, b: Point): bigint {
  const dx = BigInt(a.x - b.x);
  const dy = BigInt(a.y - b.y);
  const dz = BigInt(a.z - b.z);
  return dx * dx + dy * dy + dz * dz;
}

/** True when a reply after rttNs from this landmark is too fast for a chip within the site. */
export function tooFastForSite(site: Site, landmark: Point, rttNs: number): boolean {
  // Violation iff d(site, landmark) > r + c * rtt / 2, i.e. 2e9 * d > 2e9 * r + c * rtt (both sides >= 0).
  const rhs = 2n * NS_PER_S * BigInt(site.radiusM) + C_M_PER_S * BigInt(rttNs);
  return 4n * NS_PER_S * NS_PER_S * distanceSq(site.position, landmark) > rhs * rhs;
}

/** True when the report, signed by the chip under the license it names, places the chip outside the licensed site. */
export function locationViolation(report: EpochReport, cert: ChipCert, license: License, geometry: Geometry, auth: Authorities): boolean {
  try {
    const pk = deviceKey(cert, auth);
    if (!pk || !sameChip(report.chipId, cert) || !verifyReport(report, pk)) return false;
    // The license must be the Council-signed license the report names, for this chip.
    if (!equalBytes(report.licId, licenseId(license)) || !sameChip(license.chipId, cert)) return false;
    if (!verifySig(license.sig, () => licenseDigest(license), auth.councilKey)) return false;
    const site = geometry.sites.get(license.siteId);
    if (!site) return false;
    return report.loc.some((round) => {
      const landmark = geometry.landmarks.get(round.landmark);
      return landmark !== undefined && Number.isSafeInteger(round.rttNs) && round.rttNs >= 0 && tooFastForSite(site, landmark, round.rttNs);
    });
  } catch {
    return false;
  }
}

View on GitHub

src/predicates/omission.ts48 lines
/**
 * Omission: a non-membership proof showing that a registered, licensed chip is
 * absent from its operator's anchored tree for epoch e without a declared status.
 *
 * The evidence chains from the anchor down:
 *   1. the global epoch record for e (the caller checks it is the anchored one);
 *   2. the operator's root, included in that record's global tree;
 *   3. the chip_id's absence from the operator's tree, which holds both reports
 *      and declared statuses (see leaves.ts);
 *   4. the chip's certificate (registered) and a Council-signed license naming
 *      this operator whose height window overlaps epoch e (licensed).
 */
import { type ChipCert, type License, licenseDigest, verifySig } from "../fgm";
import { type AbsenceProof, type EpochRecord, globalEntry, type InclusionProof, verifyAbsence, verifyInclusion } from "../ledger";
import { deviceKey, sameChip } from "./device";
import type { Authorities } from "./types";

/** The claim's evidence. */
export interface OmissionEvidence {
  readonly cert: ChipCert;
  readonly license: License;
  /** Epoch e and the block heights it spans. */
  readonly epoch: { readonly number: number; readonly fromHeight: number; readonly toHeight: number };
  /** The anchored global record for epoch e, and the operator leaf's inclusion proof in its tree. */
  readonly global: { readonly record: EpochRecord; readonly proof: InclusionProof };
  /** The operator's tree for epoch e: committed root and size. */
  readonly operator: { readonly opId: string; readonly root: Uint8Array; readonly size: number };
  /** chip_id's absence from the operator's tree. */
  readonly absence: AbsenceProof;
}

/** True when a registered chip, licensed to this operator for epoch e, is provably missing from the operator's tree. */
export function omission(ev: OmissionEvidence, auth: Authorities): boolean {
  try {
    const { cert, license, epoch, global, operator } = ev;
    if (!deviceKey(cert, auth)) return false;
    if (!sameChip(license.chipId, cert) || license.opId !== operator.opId) return false;
    if (!verifySig(license.sig, () => licenseDigest(license), auth.councilKey)) return false;
    if (license.heightFrom > epoch.toHeight || license.heightTo < epoch.fromHeight) return false;
    if (global.record.epoch !== epoch.number) return false;
    const leaf = globalEntry(operator.opId, operator.root, operator.size);
    if (!verifyInclusion(global.record.root, global.record.size, leaf.key, leaf.value, global.proof)) return false;
    return verifyAbsence(operator.root, operator.size, cert.chipId, ev.absence);
  } catch {
    return false;
  }
}

View on GitHub

src/predicates/optimistic.ts149 lines
/**
 * A model of optimistic verification on Bitcoin, in the style of BitVM
 * (the cryptographic slash leaf of the bond output).
 *
 * This is a model, not an implementation: Bitcoin script, the commitment
 * scheme and the transaction graph are abstracted away. What it keeps is the
 * game. A challenger claims that a predicate's verifier, run on public input,
 * ends in an accepting state. The claim stands, and the bond is slashed,
 * unless the operator challenges it within a window. A challenge starts a
 * bisection over the verifier's execution trace: the claimant reveals the
 * hash of the state halfway through the disputed interval, the operator
 * agrees or disagrees, and the interval halves. After at most ceil(log2 n)
 * rounds the dispute is one step wide, and that one step is executed on
 * chain: it decides. Whoever misses a move deadline loses.
 *
 * Invariant during bisection: both sides agree on the state hash at lo and
 * disagree on the one at hi. An honest side therefore always wins the final
 * one-step check, whatever the other side does.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { sha256 } from "@noble/hashes/sha2.js";

/** A deterministic computation, split into steps small enough to execute on chain one at a time. */
export interface Program {
  /** Steps in an execution. */
  readonly length: number;
  /** The state before step 0, from the claim's public input. */
  init(input: Uint8Array): Uint8Array;
  /** The state after step i, from the state before it. */
  step(state: Uint8Array, i: number): Uint8Array;
  /** Whether a final state means "violation proven". */
  accepts(final: Uint8Array): boolean;
}

/** Deadlines, in blocks. */
export interface Timing {
  readonly challengeWindow: number;
  readonly moveWindow: number;
}

/** Who must move next. */
export type Party = "claimant" | "defender";

/** Where the game stands. */
export type Phase =
  | { readonly kind: "claimed"; readonly deadline: number }
  /** midHash null: the claimant owes the midpoint's hash. Set: the defender owes agree or disagree. */
  | { readonly kind: "bisect"; readonly lo: number; readonly hi: number; readonly loHash: Uint8Array; readonly hiHash: Uint8Array; readonly midHash: Uint8Array | null; readonly deadline: number }
  /** The claimant owes the state at lo (its hash is agreed); the step from lo to hi is then run on chain. */
  | { readonly kind: "one-step"; readonly lo: number; readonly loHash: Uint8Array; readonly hiHash: Uint8Array; readonly deadline: number }
  | { readonly kind: "slashed"; readonly how: "unchallenged" | "proved" | "defender-timeout" }
  | { readonly kind: "rejected"; readonly how: "disproved" | "claimant-timeout" };

/** A dispute over one claim. */
export interface Game {
  readonly program: Program;
  readonly input: Uint8Array;
  /** The claimed final state. */
  readonly final: Uint8Array;
  readonly timing: Timing;
  readonly phase: Phase;
  /** Bisection rounds completed. */
  readonly rounds: number;
}

/** Moves, each at a block height. */
export type GameEvent =
  | { readonly type: "challenge"; readonly at: number }
  | { readonly type: "reveal"; readonly hash: Uint8Array; readonly at: number }
  | { readonly type: "respond"; readonly agree: boolean; readonly at: number }
  | { readonly type: "prove"; readonly state: Uint8Array; readonly at: number }
  | { readonly type: "timeout"; readonly at: number };

/** The hash both sides commit to for a state. */
export function stateHash(state: Uint8Array): Uint8Array {
  return sha256(state);
}

/** The honest execution: states s_0 (from init) through s_n. */
export function trace(program: Program, input: Uint8Array): Uint8Array[] {
  const states = [program.init(input)];
  for (let i = 0; i < program.length; i++) states.push(program.step(states[i]!, i));
  return states;
}

/** Posts a claim at height `at`; null unless the claimed final state is accepting and the program has steps. */
export function openGame(program: Program, input: Uint8Array, final: Uint8Array, timing: Timing, at: number): Game | null {
  if (!Number.isSafeInteger(program.length) || program.length < 1 || !program.accepts(final)) return null;
  return { program, input, final, timing, phase: { kind: "claimed", deadline: at + timing.challengeWindow }, rounds: 0 };
}

/** Whose move it is, or null once the game is decided. */
export function awaiting(g: Game): Party | null {
  switch (g.phase.kind) {
    case "claimed":
      return "defender";
    case "bisect":
      return g.phase.midHash === null ? "claimant" : "defender";
    case "one-step":
      return "claimant";
    default:
      return null;
  }
}

/** Applies one move. Moves out of turn, malformed or after their deadline return the same game. */
export function play(g: Game, e: GameEvent): Game {
  const p = g.phase;
  if (p.kind === "slashed" || p.kind === "rejected") return g;
  if (e.type === "timeout") {
    if (!(e.at > p.deadline)) return g;
    const late = awaiting(g);
    if (p.kind === "claimed") return { ...g, phase: { kind: "slashed", how: "unchallenged" } };
    return { ...g, phase: late === "claimant" ? { kind: "rejected", how: "claimant-timeout" } : { kind: "slashed", how: "defender-timeout" } };
  }
  if (!(e.at <= p.deadline)) return g;
  const next = (lo: number, hi: number, loHash: Uint8Array, hiHash: Uint8Array, rounds: number): Game =>
    hi - lo === 1 ? oneStep(g, lo, loHash, hiHash, rounds, e.at) : { ...g, rounds, phase: { kind: "bisect", lo, hi, loHash, hiHash, midHash: null, deadline: e.at + g.timing.moveWindow } };

  if (p.kind === "claimed" && e.type === "challenge") {
    return next(0, g.program.length, stateHash(g.program.init(g.input)), stateHash(g.final), 0);
  }
  if (p.kind === "bisect" && p.midHash === null && e.type === "reveal") {
    if (!(e.hash instanceof Uint8Array) || e.hash.length !== 32) return g;
    return { ...g, phase: { ...p, midHash: e.hash, deadline: e.at + g.timing.moveWindow } };
  }
  if (p.kind === "bisect" && p.midHash !== null && e.type === "respond") {
    const mid = Math.floor((p.lo + p.hi) / 2);
    return e.agree ? next(mid, p.hi, p.midHash, p.hiHash, g.rounds + 1) : next(p.lo, mid, p.loHash, p.midHash, g.rounds + 1);
  }
  if (p.kind === "one-step" && e.type === "prove") {
    if (!(e.state instanceof Uint8Array) || !equalBytes(stateHash(e.state), p.loHash)) return g;
    return decide(g, e.state, p.lo, p.hiHash);
  }
  return g;
}

/** Enters the one-step phase; when lo is 0 the state is the public init(input), so the step is run at once. */
function oneStep(g: Game, lo: number, loHash: Uint8Array, hiHash: Uint8Array, rounds: number, at: number): Game {
  const game: Game = { ...g, rounds, phase: { kind: "one-step", lo, loHash, hiHash, deadline: at + g.timing.moveWindow } };
  return lo === 0 ? decide(game, g.program.init(g.input), 0, hiHash) : game;
}

/** The on-chain step: the claim stands if step(state, lo) hashes to the claimant's hash at lo + 1. */
function decide(g: Game, state: Uint8Array, lo: number, hiHash: Uint8Array): Game {
  const ok = equalBytes(stateHash(g.program.step(state, lo)), hiHash);
  return { ...g, phase: ok ? { kind: "slashed", how: "proved" } : { kind: "rejected", how: "disproved" } };
}

View on GitHub

src/predicates/tamper.ts20 lines
/**
 * Tamper: a tamper alarm with valid sigma_dev.
 *
 * The module signs the alarm, if it can, the moment a sensor fires and
 * before it destroys its keys (fgm, "Tampered").
 */
import { type ChipCert, type TamperAlarm, verifyAlarm } from "../fgm";
import { deviceKey, sameChip } from "./device";
import type { Authorities } from "./types";

/** True when the alarm names the certified chip and is signed by its device key. */
export function tamperProven(alarm: TamperAlarm, cert: ChipCert, auth: Authorities): boolean {
  try {
    const pk = deviceKey(cert, auth);
    return pk !== null && sameChip(alarm.chipId, cert) && verifyAlarm(alarm, pk);
  } catch {
    return false;
  }
}

View on GitHub

src/predicates/types.ts36 lines
/**
 * Shared inputs of the slashing predicates.
 *
 * A predicate is a pure function of anchored and signed data that returns true
 * when a violation is proven (Appendix A, "Cryptographic slashing predicates").
 * Every predicate here returns false, never throws, on malformed input.
 */

/** The public keys that make data authoritative. */
export interface Authorities {
  /** Signs chip certificates, with the enrollment officer. */
  readonly manufacturerKey: Uint8Array;
  readonly enrollmentKey: Uint8Array;
  /** K_C: signs licenses. */
  readonly councilKey: Uint8Array;
}

/** A point in Earth-centred, Earth-fixed coordinates, in whole meters. */
export interface Point {
  readonly x: number;
  readonly y: number;
  readonly z: number;
}

/** A licensed site: a centre and the radius within which the chip may be. */
export interface Site {
  readonly position: Point;
  readonly radiusM: number;
}

/** The anchored geometry the location predicate reads: sites and distance-bounding landmarks. */
export interface Geometry {
  readonly sites: ReadonlyMap<string, Site>;
  readonly landmarks: ReadonlyMap<string, Point>;
}

View on GitHub

src/predicates/unauthorized.ts42 lines
/**
 * Unauthorized update: a log entry with valid sigma_dev recording acceptance
 * of a weight-updating manifest above the threshold whose signatures do not
 * verify against the enrolled-signer registry anchored for that epoch.
 *
 * The log entry is the module's own signed statement that it accepted the
 * manifest as above E_0. If the manifest's signatures fail against the
 * anchored registry, the module was shown a different registry or was
 * subverted, and either way the operator ran an unauthorized update.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { type ChipCert, type ManifestLog, verifyLog } from "../fgm";
import { checkApproval, type Manifest, manifestDigest, type Registry, registryTree } from "../manifest";
import { deviceKey, sameChip } from "./device";
import type { Authorities } from "./types";

/** The claim's evidence. */
export interface UnauthorizedEvidence {
  readonly log: ManifestLog;
  readonly cert: ChipCert;
  /** The manifest the log names, with the signatures the module accepted. */
  readonly manifest: Manifest;
  /** The registry, which must hash to the root anchored for the log's epoch. */
  readonly registry: Registry;
  readonly anchoredRegistryRoot: Uint8Array;
}

/** True when the module logged accepting an above-threshold update that the anchored registry does not authorize. */
export function unauthorizedUpdate(ev: UnauthorizedEvidence, e0: bigint, auth: Authorities): boolean {
  try {
    const { log, cert, manifest } = ev;
    const pk = deviceKey(cert, auth);
    if (!pk || !sameChip(log.chipId, cert) || !verifyLog(log, pk)) return false;
    if (!equalBytes(manifestDigest(manifest), log.manifestHash)) return false;
    if (manifest.type !== "weight-updating" || log.periodTotal <= e0) return false;
    if (!equalBytes(registryTree(ev.registry).root, ev.anchoredRegistryRoot)) return false;
    return !checkApproval(manifest, ev.registry).approved;
  } catch {
    return false;
  }
}

View on GitHub

src/predicates/index.ts26 lines
/**
 * The five cryptographic slashing predicates and a model of the optimistic
 * verification that decides them on Bitcoin. See SPEC.md.
 */
export type { Authorities, Geometry, Point, Site } from "./types";
export { deviceKey, sameChip } from "./device";
export { type DeclaredStatus, reportLeaf, statusLeaf } from "./leaves";
export { equivocation } from "./equivocation";
export { C_M_PER_S, distanceSq, locationViolation, tooFastForSite } from "./location";
export { tamperProven } from "./tamper";
export { omission, type OmissionEvidence } from "./omission";
export { unauthorizedUpdate, type UnauthorizedEvidence } from "./unauthorized";
export {
  awaiting,
  type Game,
  type GameEvent,
  openGame,
  type Party,
  type Phase,
  play,
  type Program,
  stateHash,
  type Timing,
  trace,
} from "./optimistic";

View on GitHub