Firebreak

Reference implementation

License state machine

The guarantee module's states, permitted rates and transitions, with property-based tests.

Source
11 files, 988 lines
Tests
3 files, 44 cases
Paper
sec:app-protocol

FGM license state machine

Purpose

The Firebreak Guarantee Module (FGM) sits on each accelerator's clock, power and interconnect control paths. This module is its licensing logic, written as a pure reducer:

step(state: FgmState, event: FgmEvent): FgmState
allowance(state): Allowance   // the throttle setting after each event
rate(state): number           // allowance(state).rate

It follows the paper's license state machine (Appendix A, "License state machine"). The default state is low capability. Full rate is earned one license at a time, and every lapse falls back toward the Tier 0 rate r_0.

Everything the module trusts from outside arrives already verified. The Bitcoin time beacon module checks header chains (proof of work, the difficulty floor), the distance-bounding protocol checks location, and full-block outage proofs are checked upstream. This reducer only decides what those facts mean for the license.

Data formats

License

Field names follow the paper's tuple (chip, op, tier, B, site, cset, h, H_from, H_to, lambda, d_min, nonce).

Field Type Meaning
chip 32 bytes chip_id = H(pk_dev)
op string operator
tier 0, 1 or 2 licensed tier
budget integer B, in metered work units
site string registered site; must match the latest location proof
cset string cluster set for high-bandwidth collectives
blockHash 32 bytes h, a recent Bitcoin block; must be newer than the chip's recorded tip
heightFrom, heightTo integers H_from, H_to, the valid block-height window
lambda integer maximum local duration, in local seconds
dMin integer lowest header difficulty accepted while the license runs
nonce 32 bytes
sig 64 bytes BIP340 Schnorr signature under the Council key K_C

The signed digest is taggedHash("Firebreak/fgm/license", encoding) (BIP340 tagged hash). The encoding concatenates the fields in table order: integers as u64 little-endian, strings as a u32 little-endian length followed by UTF-8, and hashes as raw 32 bytes. In deployment the signature comes from a FROST signing session of the Council. A FROST signature is an ordinary BIP340 signature, so the module verifies it with schnorr.verify from @noble/curves.

Orders

{ kind: "hold" | "confirm" | "lift", seq, chips[], sig }. The digest is taggedHash("Firebreak/fgm/order", kindByte || u64le(seq) || u32le(count) || chips), with kind bytes 1, 2 and 3. The Council key signs hold and confirm orders; the dispute panel's key signs lift orders. Each signer has its own sequence counter, and an order is accepted only if its seq is higher than every earlier one from that signer.

Events

Event Source Effect
install(license, at) operator, with the beacon's verified position at of block h accept or refuse the license
headers(tip, minDifficulty) beacon adopt a header chain with more work
tick(a, b) the two oscillators advance the local counter by max(a, b), or flag a clock anomaly
meter(work) hardware counters charge work to the budget
location(site) distance-bounding proof record the proven site
order(order) Council or dispute panel hold, confirm or lift
outage full-block proof that no root was anchored enter outage grace
anchor a valid anchored root seen leave outage grace
tamper tamper sensor destroy keys

States and transitions

State Rate (allowance) Training rate Entered when Left when
Unlicensed r_0 r_0 enrollment; any lapse of a non-critical chip; a clock anomaly; grace ends; an outage ends a valid license (to Licensed); an outage proof (to OutageGrace)
Licensed r, for at most the rest of lambda and the rest of B r a valid license is accepted budget spent, lambda local seconds passed, or tip height above H_to (to Grace if critical, else OutageGrace if an outage is proven, else Unlicensed); clock anomaly; hold; tamper
Grace g*r for at most the rest of gamma r_0 a critical-service chip's license lapses renewal (to Licensed); gamma passes (to OutageGrace or Unlicensed); clock anomaly
OutageGrace g*r r_0 an outage proof, with no running license an anchored root (to Unlicensed); a valid license (to Licensed)
Hold r_0 r_0 a valid Council hold naming the chip an unconfirmed hold lapses after holdPeriod; a valid panel lift; tamper
Tampered r_0 r_0 tamper never (re-enrollment is outside this reducer)

Licenses are refused in Hold and Tampered. In every other state a valid license moves the chip to Licensed, which is how a renewal works.

 enrollment
     |
     v                 valid license
 +------------+ -------------------------------> +----------+
 | Unlicensed |                                  | Licensed | <--+ renewal
 +------------+ <------------------------------- +----------+    | (valid license)
   |      ^      lapse of a non-critical chip,     |             |
   |      |      or clock anomaly                  | lapse of a  |
   |      |                                        | critical    |
   |      |                                        v chip        |
   |      |          gamma over, or anomaly    +-------+         |
   |      +----------------------------------- | Grace | --------+
   |      |                                    +-------+
   |      | anchored root
 outage   |
 proof    |
   v      |
 +-------------+
 | OutageGrace | ---- valid license ----> Licensed
 +-------------+

 Any state except Tampered --- valid Council hold ---> Hold
 Hold --- panel lift, or an unconfirmed hold lapses ---> the state the facts imply
 Any state --- tamper ---> Tampered (absorbing)

 While an outage is proven, every arrow above that ends in Unlicensed ends in OutageGrace instead.

How the reducer is built: Hold and Tampered are stored. Every other status is recomputed after each event, in this order: Hold if a hold record exists; Licensed if the license slot has not lapsed; Grace if the chip is critical and gamma has not passed since the lapse; OutageGrace if an outage is proven; otherwise Unlicensed. A lapse is recorded once, with the local time it happened. For a duration lapse that time is acceptedAt + lambda even when one large tick jumps past it, so gamma is measured from the true moment of the lapse.

The throttle (dead-man allowance)

After every event the module loads allowance(state) into the throttle: a rate, plus the local seconds and work units that rate may run for. When either runs out, the throttle drops to r_0 by itself, whether or not another event arrives. This makes the reducer exact in discrete steps. A tick of any length can never carry full rate past lambda or past B, because the throttle stops at the limit within the tick.

Security properties and the tests that check them

All property tests are in test/fgm/properties.test.ts. A test world drives the chip with arbitrary and adversarial events: forged, unsigned and edited licenses; replays; licenses for other chips, other sites, or with lambda above LAMBDA_MAX; stale and low-difficulty header chains; huge ticks of 2^40 seconds; disagreeing and malformed oscillator readings; holds, confirms and lifts from right and wrong signers, with fresh and replayed sequence numbers; outage proofs; tamper. Real time is tracked exactly, in integer microseconds. Oscillator A is always honest: real elapsed time equals a * (1 + q) with |q| <= eps. Oscillator B is honest or adversarial depending on the run. The world also plays the accelerator: during each tick it does as much full-rate work as the throttle allows. A separate test checks that the harness reaches all six states and pushes work and time to within 1% of the bounds, so the properties are not vacuous. Each property was also checked against deliberately broken versions of the reducer.

Property Test
(a) Tampered is absorbing: every later event returns the identical state mixed runs, check(); transitions.test.ts "any state -> Tampered"
(b) Full-rate work under any one license is at most min{B, (1+eps) r lambda}, and the real time spent at full rate is at most (1+eps) lambda (the paper's license-window bound) mixed runs, checkAccounts() after every tick
(c) Only a genuine, unedited Council-signed license can become the running license; forged, unsigned and edited licenses never yield full rate mixed runs, check(); "(c) forged, unsigned and edited licenses never yield full rate"
(d) A replayed license or order never changes the state mixed runs (replay and replay-order actions)
(e) Hold is entered only by a valid Council hold, and left only by a valid panel lift, by the lapse of an unconfirmed hold after holdPeriod, or by tamper mixed runs; "(e) holds, confirmations and lifts under dense order traffic"
(f) The local counter and the recorded tip's cumulative work never decrease (the paper's chain-tip invariant); an honest tick never voids a license; readings whose tolerance ranges are disjoint always void it; real time never exceeds local * (1+eps), and with both oscillators honest it also stays at or above local * (1-eps) mixed runs; "(f) with both oscillators honest"
(g) The rate is at most r; at most g*r in Grace and OutageGrace; at most r_0 elsewhere; training above r_0 happens only while Licensed (the paper's rate invariant) mixed runs, check()
Licensed always means a live license: inside lambda, inside [H_from, H_to], budget left mixed runs, check()
While a license runs, a header chain below its d_min never moves the tip mixed runs, check()
Only critical-service chips enter Grace mixed runs, check()

test/fgm/transitions.test.ts has an example test for each transition and for every license refusal reason.

Interpretations

Each of these is a choice the paper leaves open. Each needs the authors to confirm it.

  1. Local time is the larger of the two oscillator readings. The paper says a counter "driven by an oscillator" is compared with a second one. Advancing by max(a, b) means the (1+eps) lambda bound holds as long as either oscillator is honest. The anomaly rule stays as the paper requires.
  2. Clock anomaly test. A tick is anomalous when the real-time ranges [a(1-eps), a(1+eps)] and [b(1-eps), b(1+eps)] do not overlap, checked per tick. A malformed or overflowing reading also counts as an anomaly. An anomaly voids the license ("Tier 0 until a fresh license arrives") and gives no grace, even to a critical chip.
  3. Anti-replay is the chain tip. The paper accepts a license "whose block hash is newer than the module's recorded tip". Accepting it moves the tip to h, so the same license can never be accepted twice. No separate sequence number is needed.
  4. LAMBDA_MAX. The paper puts lambda in the license. The module also refuses any lambda above a constant fixed at manufacture, so a compromised Council key cannot issue a very long license.
  5. Grace starts on any lapse. Budget, duration and height all count, but a clock anomaly does not. The paper says "after expiry".
  6. Hold orders carry a chip list and per-signer sequence numbers. A hold refreshes its start time if it is re-issued. A confirmed hold never lapses; only a lift ends it. The hold period is measured in local time.
  7. Outage. A Licensed chip keeps its license through an outage, and falls to OutageGrace only when the license lapses.
  8. Malformed meter readings spend the whole budget. This fails safe.
  9. Units. Budgets and work are integers. The rates r, g*r and r_0 are work per second of real time, because r is the chip's physical peak rate.

Open questions and gaps for the paper's authors

  • Power loss. The local counter only advances while the module is powered. Real time while the chip is off is not counted. That does not extend full-rate compute, since lambda is local time while running, but it can stretch a license over a longer calendar period. The paper should say whether lambda is meant as calendar time, which would need a battery-backed counter or a resync rule.
  • License tip versus report tip. A renewal must embed a block newer than the module's recorded tip. If the module adopts newer headers between its epoch report and the renewal, the renewal is refused. Issuance must use the tip reported in the epoch report, and the module should not adopt headers in between, or the rule should compare against the reported tip.
  • Header consistency with local time. The paper requires "cumulative work consistent with the local time elapsed", but gives no bound. It is left to the beacon module.
  • Hold lapse in local time can be cut short by a factor of up to (1+eps). A height-based period would avoid that.
  • Tier 2 fields. The job_id and spec hash that Tier 2 licenses carry are not modeled here.
  • Peer licensing is modeled as a predicate, mayLink(state, peerCset), that gates collectives rather than the chip's rate, as the paper describes. Freshness of peer license proofs is not specified.
  • Effective compute. B is in effective compute while the module meters raw operations. The conversion at eta(t) is outside this reducer.

Source

The code

src/fgm/clock.ts25 lines
/**
 * The local clock: two physically different oscillators that must agree.
 *
 * Each oscillator runs within a fractional tolerance epsilon of real time, so a
 * reading of d local seconds means the real elapsed time lies in
 * [d(1-eps), d(1+eps)]. Two honest readings of the same interval therefore give
 * overlapping ranges. Ranges that do not overlap mean at least one oscillator is
 * outside tolerance: a clock anomaly.
 */

const PPM = 1_000_000n;

/** True when readings a and b of one interval are consistent with a single real duration. */
export function oscillatorsAgree(a: number, b: number, epsPpm: number): boolean {
  const lo = BigInt(Math.min(a, b));
  const hi = BigInt(Math.max(a, b));
  const e = BigInt(epsPpm);
  return hi * (PPM - e) <= lo * (PPM + e);
}

/** The local seconds a tick advances the counter by: the larger reading, so licenses run out no later. */
export function localAdvance(a: number, b: number): number {
  return Math.max(a, b);
}

View on GitHub

src/fgm/encoding.ts128 lines
/**
 * Canonical encodings and signatures for the messages the module checks:
 * licenses, orders and chip certificates.
 *
 * Each message is serialized field by field in a fixed order (integers as
 * u64 little-endian, strings as u32 length then UTF-8, hashes as raw 32 bytes)
 * and hashed with a BIP340 tagged hash, so a signature on one message type can
 * never be replayed as another.
 */
import { schnorr } from "@noble/curves/secp256k1.js";
import { equalBytes } from "@noble/curves/utils.js";
import { sha256 } from "@noble/hashes/sha2.js";
import { concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
import type { ChipCert, ChipCertBody, License, LicenseBody, Order, OrderBody, OrderKind } from "./types";

/** BIP340 tag for license digests. */
export const LICENSE_TAG = "Firebreak/fgm/license";
/** BIP340 tag for order digests. */
export const ORDER_TAG = "Firebreak/fgm/order";
/** BIP340 tag for chip certificate digests. */
export const CERT_TAG = "Firebreak/fgm/cert";

const ORDER_KIND_BYTE: Record<OrderKind, number> = { hold: 1, confirm: 2, lift: 3 };

/** u64 little-endian; throws unless n is a safe non-negative integer. */
export function u64(n: number): Uint8Array {
  if (!Number.isSafeInteger(n) || n < 0) throw new RangeError(`not a safe non-negative integer: ${n}`);
  const out = new Uint8Array(8);
  new DataView(out.buffer).setBigUint64(0, BigInt(n), true);
  return out;
}

/** u32 little-endian. */
export function u32(n: number): Uint8Array {
  const out = new Uint8Array(4);
  new DataView(out.buffer).setUint32(0, n, true);
  return out;
}

/** A string as u32 byte length then UTF-8. */
export function str(s: string): Uint8Array {
  const b = utf8ToBytes(s);
  return concatBytes(u32(b.length), b);
}

/** A 32-byte hash, checked for length. */
export function hash32(b: Uint8Array): Uint8Array {
  if (b.length !== 32) throw new RangeError(`expected 32 bytes, got ${b.length}`);
  return b;
}

/** The digest the Council signs for a license; throws on a malformed field. */
export function licenseDigest(l: LicenseBody): Uint8Array {
  return schnorr.utils.taggedHash(
    LICENSE_TAG,
    concatBytes(
      hash32(l.chipId),
      str(l.opId),
      u64(l.tier),
      u64(l.budget),
      str(l.siteId),
      str(l.csetId),
      hash32(l.blockHash),
      u64(l.heightFrom),
      u64(l.heightTo),
      u64(l.lambda),
      u64(l.dMin),
      hash32(l.nonce),
    ),
  );
}

/** The digest the Council or dispute panel signs for an order; throws on a malformed field. */
export function orderDigest(o: OrderBody): Uint8Array {
  return schnorr.utils.taggedHash(
    ORDER_TAG,
    concatBytes(Uint8Array.of(ORDER_KIND_BYTE[o.kind]), u64(o.seq), u32(o.chips.length), ...o.chips.map(hash32)),
  );
}

/** The digest the manufacturer and the enrollment officer each sign for a chip certificate. */
export function certDigest(c: ChipCertBody): Uint8Array {
  return schnorr.utils.taggedHash(
    CERT_TAG,
    concatBytes(hash32(c.chipId), hash32(c.pkDev), str(c.productClass), u64(c.theta), str(c.fabId), u64(c.date)),
  );
}

/** Checks a BIP340 signature over a digest, returning false (never throwing) on malformed input. */
export function verifySig(sig: Uint8Array, digest: () => Uint8Array, pubkey: Uint8Array): boolean {
  try {
    return sig instanceof Uint8Array && sig.length === 64 && schnorr.verify(sig, digest(), pubkey);
  } catch {
    return false;
  }
}

/** Checks a certificate: chip_id = H(pk_dev), and both the manufacturer's and the enrollment officer's signatures. */
export function verifyCert(c: ChipCert, manufacturerKey: Uint8Array, enrollmentKey: Uint8Array): boolean {
  try {
    if (!equalBytes(c.chipId, sha256(c.pkDev))) return false;
  } catch {
    return false;
  }
  return verifySig(c.sigMfr, () => certDigest(c), manufacturerKey) && verifySig(c.sigEnr, () => certDigest(c), enrollmentKey);
}

/** Signs a license body with the Council secret key (in deployment, a FROST signing session). */
export function signLicense(body: LicenseBody, councilSecret: Uint8Array, auxRand?: Uint8Array): License {
  return { ...body, sig: schnorr.sign(licenseDigest(body), councilSecret, auxRand) };
}

/** Signs an order body with the Council or dispute panel secret key. */
export function signOrder(body: OrderBody, secret: Uint8Array, auxRand?: Uint8Array): Order {
  return { ...body, sig: schnorr.sign(orderDigest(body), secret, auxRand) };
}

/** Issues a certificate: signed by the manufacturer, then by the enrollment officer. */
export function signCert(body: ChipCertBody, manufacturerSecret: Uint8Array, enrollmentSecret: Uint8Array, auxRand?: Uint8Array): ChipCert {
  const d = certDigest(body);
  return { ...body, sigMfr: schnorr.sign(d, manufacturerSecret, auxRand), sigEnr: schnorr.sign(d, enrollmentSecret, auxRand) };
}

/** The license identifier used in epoch reports: its signed digest. */
export function licenseId(l: LicenseBody): Uint8Array {
  return licenseDigest(l);
}

View on GitHub

src/fgm/license.ts69 lines
/**
 * The checks a license must pass before the module accepts it (Appendix A,
 * "License state machine": a valid license whose block hash is newer than the
 * module's recorded tip, whose headers meet d_min, and whose site matches the
 * location proof; plus a fresh nonce).
 */
import { equalBytes } from "@noble/curves/utils.js";
import { bytesToHex } from "@noble/hashes/utils.js";
import { licenseDigest, verifySig } from "./encoding";
import type { FgmState, License, Tip } from "./types";
import { isBytes, isCount, isText, isTip } from "./validate";

/** Why a license was refused. */
export type LicenseRejection =
  | "held"
  | "malformed"
  | "wrong-chip"
  | "wrong-block"
  | "not-newer"
  | "below-floor"
  | "outside-height-window"
  | "lambda-too-long"
  | "location-mismatch"
  | "nonce-reused"
  | "bad-signature";

/** The outcome of checking a license. */
export type LicenseVerdict = { readonly ok: true } | { readonly ok: false; readonly reason: LicenseRejection };

/** Decides whether the module accepts a license whose block h the beacon placed at `at`. */
export function checkLicense(s: FgmState, l: License, at: Tip, meetsFloor: boolean, locationOk: boolean): LicenseVerdict {
  const no = (reason: LicenseRejection): LicenseVerdict => ({ ok: false, reason });
  if (s.status === "Hold" || s.status === "Tampered") return no("held");
  if (!wellFormed(l) || !isTip(at)) return no("malformed");
  if (!equalBytes(l.chipId, s.config.chipId)) return no("wrong-chip");
  if (!equalBytes(at.hash, l.blockHash)) return no("wrong-block");
  // Anti-replay by chain work: h must be newer than the recorded tip, and accepting it moves the tip to h.
  if (at.work <= s.tip.work) return no("not-newer");
  if (meetsFloor !== true) return no("below-floor");
  if (at.height < l.heightFrom || at.height > l.heightTo) return no("outside-height-window");
  if (l.lambda > s.config.lambdaMax) return no("lambda-too-long");
  if (locationOk !== true) return no("location-mismatch");
  if (s.nonces.has(bytesToHex(l.nonce))) return no("nonce-reused");
  if (!verifySig(l.sig, () => licenseDigest(l), s.config.councilKey)) return no("bad-signature");
  return { ok: true };
}

function wellFormed(l: License): boolean {
  return (
    isBytes(l.chipId, 32) &&
    isBytes(l.blockHash, 32) &&
    isBytes(l.nonce, 32) &&
    isBytes(l.sig, 64) &&
    isText(l.opId) &&
    isText(l.siteId) &&
    isText(l.csetId) &&
    isCount(l.tier) &&
    l.tier <= 2 &&
    isCount(l.budget) &&
    l.budget > 0 &&
    isCount(l.heightFrom) &&
    isCount(l.heightTo) &&
    l.heightFrom <= l.heightTo &&
    isCount(l.lambda) &&
    l.lambda > 0 &&
    isCount(l.dMin)
  );
}

View on GitHub

src/fgm/limits.ts55 lines
/**
 * What each state lets the accelerator do.
 *
 * The module drives the accelerator's clock and power gating. allowance() is
 * the dead-man setting it loads into the throttle after every event: a rate
 * for each workload type, and the local time and work those rates may run for
 * before the throttle falls back to r_0 on its own, whether or not another
 * event arrives.
 *
 * Permitted rates (the paper's state table):
 *   Licensed      r for jobs with valid manifests, within B and lambda
 *   Grace         g*r for inference only, for gamma after the lapse (critical chips only)
 *   Outage grace  g*r for inference only
 *   otherwise     r_0
 */
import type { JobType } from "../manifest";
import type { Allowance, FgmConfig, FgmState } from "./types";

const uniform = (r: number): Record<JobType, number> => ({ inference: r, evaluation: r, "weight-updating": r });

/** The throttle setting for the current state. */
export function allowance(s: FgmState): Allowance {
  const { fullRate, graceRate, tier0Rate, gamma } = s.config;
  const tier0: Allowance = { rates: uniform(tier0Rate), unmanifested: tier0Rate, localUnits: Infinity, work: Infinity, fallback: tier0Rate };
  const inferenceOnly = { ...uniform(tier0Rate), inference: graceRate };
  const slot = s.slot;
  if (s.status === "Licensed" && slot !== null) {
    return {
      ...tier0,
      rates: uniform(fullRate),
      localUnits: slot.acceptedAt + slot.license.lambda - s.local,
      work: slot.license.budget - slot.used,
    };
  }
  if (s.status === "Grace" && slot?.lapsed) return { ...tier0, rates: inferenceOnly, localUnits: slot.lapsed.at + gamma - s.local };
  if (s.status === "OutageGrace") return { ...tier0, rates: inferenceOnly };
  return tier0;
}

/** The highest rate the accelerator may run a job at in the current state. */
export function rate(s: FgmState, jobType: JobType, manifestOk: boolean): number {
  const a = allowance(s);
  return manifestOk ? a.rates[jobType] : a.unmanifested;
}

/** Whether this chip may run high-bandwidth collectives with a peer whose license names peerCset. */
export function mayLink(s: FgmState, peerCset: string): boolean {
  return s.status === "Licensed" && s.slot !== null && s.slot.license.csetId === peerCset;
}

/** One chip's full-rate term of the license-window bound: min{B, (1+eps) r lambda}. */
export function licenseWindow(config: FgmConfig, budget: number, lambda: number): number {
  return Math.min(budget, (1 + config.epsPpm / 1e6) * config.fullRate * lambda);
}

View on GitHub

src/fgm/machine.ts188 lines
/**
 * The license state machine as a pure reducer: step(state, event) -> state.
 *
 * Hold and Tampered are stored (a hold record, or the Tampered status itself).
 * Every other status is recomputed by settle() after each event from the
 * license slot, the local counter, the recorded tip and the outage flag, so the
 * status can never drift out of step with the facts it summarizes.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { sha256 } from "@noble/hashes/sha2.js";
import { bytesToHex } from "@noble/hashes/utils.js";
import type { JobType } from "../manifest";
import { localAdvance, oscillatorsAgree } from "./clock";
import { verifyCert } from "./encoding";
import { checkLicense } from "./license";
import { checkOrder } from "./orders";
import { provesOutage } from "./outage";
import type { ChipCert, FgmConfig, FgmEvent, FgmState, LicenseSlot, Meters, Order, Status, Tip } from "./types";
import { isCount, isTip } from "./validate";

/** The paper's names for the six states. */
export const STATUS_NAMES: Readonly<Record<Status, string>> = {
  Unlicensed: "Unlicensed or expired",
  Licensed: "Licensed",
  Grace: "Grace",
  OutageGrace: "Outage grace",
  Hold: "Hold",
  Tampered: "Tampered",
};

const NO_METERS: Meters = { inference: 0, evaluation: 0, weightUpdating: 0, unmanifested: 0 };

/** The state of a freshly enrolled module: Unlicensed, local counter at zero, tip as recorded at enrollment. */
export function boot(config: FgmConfig, tip: Tip): FgmState {
  return settle({
    config,
    status: "Unlicensed",
    local: 0,
    tip,
    slot: null,
    hold: null,
    outage: false,
    councilSeq: 0,
    panelSeq: 0,
    nonces: new Set(),
    meters: NO_METERS,
    alarm: null,
  });
}

/** Applies one event. Rejected inputs return the same state object unchanged. */
export function step(s: FgmState, e: FgmEvent): FgmState {
  if (s.status === "Tampered") return e.type === "reenroll" ? reenroll(s, e.cert, e.derivedKey) : s;
  switch (e.type) {
    case "tamper":
      // The alarm body is produced for the device key to sign; then the keys, the license, any hold
      // and every pending timer are gone.
      return {
        ...s,
        status: "Tampered",
        slot: null,
        hold: null,
        outage: false,
        alarm: { chipId: s.config.chipId, local: s.local, tipHash: s.tip.hash },
      };
    case "install":
      if (!checkLicense(s, e.license, e.at, e.meetsFloor, e.locationOk).ok) return s;
      // A license the Council issued is itself a sign the regime is running, so it also ends outage grace.
      return settle({
        ...s,
        tip: e.at,
        outage: false,
        nonces: new Set(s.nonces).add(bytesToHex(e.license.nonce)),
        slot: { license: e.license, acceptedAt: s.local, used: 0, lapsed: null },
      });
    case "headers":
      return acceptsHeaders(s, e.tip, e.meetsFloor) ? settle({ ...s, tip: e.tip }) : s;
    case "tick":
      return tick(s, e.osc1, e.osc2);
    case "meter":
      return meter(s, e.work, e.jobType, e.manifestOk);
    case "order":
      return applyOrder(s, e.order);
    case "outageEvidence":
      // Positive evidence of an outage also ends a running license: the table lists it as a way out of Licensed.
      return provesOutage(s, e.evidence) ? settle({ ...s, outage: true, slot: null }) : s;
    case "anchorSeen":
      // The outage is over; the chip is Unlicensed or expired until it renews.
      return s.outage ? settle({ ...s, outage: false }) : s;
    case "reenroll":
      return s; // only a Tampered module is re-enrolled
  }
}

/**
 * Advances the local counter. Disagreeing or malformed readings are a clock anomaly: the chip drops to
 * Unlicensed or expired, losing its license, its grace timer and any outage grace.
 */
function tick(s: FgmState, osc1: number, osc2: number): FgmState {
  if (!isCount(osc1) || !isCount(osc2) || !Number.isSafeInteger(s.local + localAdvance(osc1, osc2))) {
    return settle({ ...s, slot: null, outage: false });
  }
  const local = s.local + localAdvance(osc1, osc2);
  if (!oscillatorsAgree(osc1, osc2, s.config.epsPpm)) return settle({ ...s, local, slot: null, outage: false });
  return settle({ ...s, local });
}

/**
 * Meters work by workload. Every unit counts against the license budget, whatever the workload
 * (Layer 1, "Peer licensing"). A malformed reading fails safe by spending the whole budget.
 */
function meter(s: FgmState, work: number, jobType: JobType, manifestOk: boolean): FgmState {
  const valid = isCount(work) && (jobType === "inference" || jobType === "evaluation" || jobType === "weight-updating");
  const slot = s.slot;
  if (!valid) return slot === null ? s : settle({ ...s, slot: { ...slot, used: slot.license.budget } });
  const m = s.meters;
  const add = (n: number) => Math.min(n + work, Number.MAX_SAFE_INTEGER);
  const meters: Meters = !manifestOk
    ? { ...m, unmanifested: add(m.unmanifested) }
    : jobType === "inference"
      ? { ...m, inference: add(m.inference) }
      : jobType === "evaluation"
        ? { ...m, evaluation: add(m.evaluation) }
        : { ...m, weightUpdating: add(m.weightUpdating) };
  const used = slot === null ? null : Math.min(slot.used + work, slot.license.budget);
  return settle({ ...s, meters, slot: slot === null || used === null ? slot : { ...slot, used } });
}

/** Adopts a verified header chain only if it has more work and, while a license runs, meets its d_min. */
function acceptsHeaders(s: FgmState, tip: Tip, meetsFloor: boolean): boolean {
  if (!isTip(tip) || tip.work <= s.tip.work) return false;
  const running = s.slot !== null && s.slot.lapsed === null;
  return !running || meetsFloor === true;
}

function applyOrder(s: FgmState, o: Order): FgmState {
  if (!checkOrder(s, o).ok) return s;
  switch (o.kind) {
    case "hold":
      return settle({ ...s, councilSeq: o.seq, hold: { since: s.local, confirmed: s.hold?.confirmed ?? false } });
    case "confirm":
      return settle({ ...s, councilSeq: o.seq, hold: { since: s.hold?.since ?? s.local, confirmed: true } });
    case "lift":
      return settle({ ...s, panelSeq: o.seq, hold: null });
  }
}

/**
 * Re-enrollment at an accredited facility. The certificate must be newer than the chip's current one (so the
 * old, public certificate cannot be replayed) and must name the key the module just derived (so another
 * chip's certificate cannot be borrowed). The chip leaves Tampered with that identity, Unlicensed.
 */
function reenroll(s: FgmState, cert: ChipCert, derivedKey: Uint8Array): FgmState {
  const { manufacturerKey, enrollmentKey, enrolledAt } = s.config;
  if (!(derivedKey instanceof Uint8Array) || !isCount(cert.date) || cert.date <= enrolledAt) return s;
  if (!(cert.pkDev instanceof Uint8Array) || !equalBytes(cert.pkDev, derivedKey)) return s;
  if (!verifyCert(cert, manufacturerKey, enrollmentKey)) return s;
  // The tip, the meters, the nonce record and the order sequence numbers survive: none may move backward.
  const config = { ...s.config, chipId: sha256(cert.pkDev), enrolledAt: cert.date };
  return settle({ ...s, config, status: "Unlicensed", alarm: null, slot: null, hold: null, outage: false });
}

/** Records lapses and hold expiry that the last event caused, then recomputes the status. */
function settle(s: FgmState): FgmState {
  const slot = s.slot !== null && s.slot.lapsed === null ? markLapse(s, s.slot) : s.slot;
  const holdOver = s.hold !== null && !s.hold.confirmed && s.local - s.hold.since >= s.config.holdPeriod;
  const next: FgmState = { ...s, slot, hold: holdOver ? null : s.hold };
  return { ...next, status: classify(next) };
}

/** Marks the slot lapsed, once, with the local time the lapse happened. */
function markLapse(s: FgmState, slot: LicenseSlot): LicenseSlot {
  const l = slot.license;
  if (s.local - slot.acceptedAt >= l.lambda) return { ...slot, lapsed: { cause: "duration", at: slot.acceptedAt + l.lambda } };
  if (s.tip.height > l.heightTo) return { ...slot, lapsed: { cause: "height", at: s.local } };
  if (slot.used >= l.budget) return { ...slot, lapsed: { cause: "budget", at: s.local } };
  return slot;
}

/** The status implied by the facts; Tampered never reaches here. */
function classify(s: FgmState): Status {
  if (s.hold !== null) return "Hold";
  if (s.slot !== null && s.slot.lapsed === null) return "Licensed";
  if (s.config.critical && s.slot?.lapsed && s.local < s.slot.lapsed.at + s.config.gamma) return "Grace";
  if (s.outage) return "OutageGrace";
  return "Unlicensed";
}

View on GitHub

src/fgm/orders.ts41 lines
/**
 * The checks a hold, confirm or lift order must pass.
 *
 * Hold and confirm orders are signed under the Council key; lift orders under
 * the dispute panel's key. Each signer numbers its orders, and the module
 * accepts only a number higher than any it has accepted from that signer, so an
 * old order can never be replayed.
 */
import { equalBytes } from "@noble/curves/utils.js";
import { orderDigest, verifySig } from "./encoding";
import type { FgmState, Order } from "./types";
import { isBytes, isCount } from "./validate";

/** Why an order was refused. */
export type OrderRejection = "malformed" | "not-named" | "stale-seq" | "not-held" | "bad-signature";

/** The outcome of checking an order. */
export type OrderVerdict = { readonly ok: true } | { readonly ok: false; readonly reason: OrderRejection };

/** Decides whether the module obeys an order. */
export function checkOrder(s: FgmState, o: Order): OrderVerdict {
  const no = (reason: OrderRejection): OrderVerdict => ({ ok: false, reason });
  if (!wellFormed(o)) return no("malformed");
  if (!o.chips.some((c) => equalBytes(c, s.config.chipId))) return no("not-named");
  const byPanel = o.kind === "lift";
  if (o.seq <= (byPanel ? s.panelSeq : s.councilSeq)) return no("stale-seq");
  if (o.kind !== "hold" && s.hold === null) return no("not-held");
  if (!verifySig(o.sig, () => orderDigest(o), byPanel ? s.config.panelKey : s.config.councilKey)) return no("bad-signature");
  return { ok: true };
}

function wellFormed(o: Order): boolean {
  return (
    (o.kind === "hold" || o.kind === "confirm" || o.kind === "lift") &&
    isCount(o.seq) &&
    Array.isArray(o.chips) &&
    o.chips.every((c) => isBytes(c, 32)) &&
    isBytes(o.sig, 64)
  );
}

View on GitHub

src/fgm/outage.ts26 lines
/**
 * Outage evidence (Layer 1, "Fail-safe modes").
 *
 * Absence cannot be shown with headers alone: an operator could simply
 * withhold the blocks that carry anchors. So the module enters outage grace
 * only on positive evidence: every full block of a window at least
 * outageWindow blocks long, ending at the module's recorded tip, was shown and
 * checked against its header's Merkle root (upstream), and none held a valid
 * anchored root.
 */
import type { FgmState, OutageEvidence } from "./types";
import { isCount } from "./validate";

/** Whether the evidence proves an outage to this module, given its recorded tip and outage window. */
export function provesOutage(s: FgmState, e: OutageEvidence): boolean {
  if (!isCount(e.fromHeight) || !isCount(e.toHeight) || !isCount(e.fullBlocks) || !isCount(e.anchorsFound)) return false;
  const span = e.toHeight - e.fromHeight + 1;
  return (
    e.meetsFloor === true &&
    e.toHeight === s.tip.height &&
    span >= Math.max(1, s.config.outageWindow) &&
    e.fullBlocks === span &&
    e.anchorsFound === 0
  );
}

View on GitHub

src/fgm/outputs.ts134 lines
/**
 * What the module signs with its device key: epoch reports, tamper alarms and
 * log entries. These are the signed data the slashing predicates read.
 *
 * Epoch report (Appendix A): Rep = (chip_id, e, meters, loc, lic_id, {H(Man)}, l, h_e, state, sigma_dev).
 */
import { schnorr } from "@noble/curves/secp256k1.js";
import { numberToVarBytesBE } from "@noble/curves/utils.js";
import { concatBytes } from "@noble/hashes/utils.js";
import { hash32, str, u32, u64, verifySig } from "./encoding";
import type { Meters, Status, TamperAlarmBody } from "./types";

/** BIP340 tag for epoch reports. */
export const REPORT_TAG = "Firebreak/fgm/report";
/** BIP340 tag for tamper alarms. */
export const ALARM_TAG = "Firebreak/fgm/alarm";
/** BIP340 tag for log entries. */
export const LOG_TAG = "Firebreak/fgm/log";

/** One round of a distance-bounding exchange: a landmark and the measured round-trip time. */
export interface DistanceRound {
  readonly landmark: string;
  readonly rttNs: number;
}

/** The report body the device signs at the end of each epoch. */
export interface EpochReportBody {
  readonly chipId: Uint8Array;
  readonly epoch: number;
  readonly meters: Meters;
  /** loc: the distance-bounding transcript. */
  readonly loc: readonly DistanceRound[];
  /** lic_id: the identifier of the license the chip ran under (32 zero bytes for none). */
  readonly licId: Uint8Array;
  /** {H(Man)}: the hashes of manifests accepted this epoch. */
  readonly manifests: readonly Uint8Array[];
  /** l: the head of the hash-chained log. */
  readonly logHead: Uint8Array;
  /** h_e: the newest block hash the module has verified. */
  readonly tipHash: Uint8Array;
  readonly state: Status;
}

/** A signed epoch report. */
export interface EpochReport extends EpochReportBody {
  readonly sig: Uint8Array;
}

/** A signed tamper alarm. */
export interface TamperAlarm extends TamperAlarmBody {
  readonly sig: Uint8Array;
}

/** A log entry recording that the module accepted a weight-updating manifest. */
export interface ManifestLogBody {
  readonly chipId: Uint8Array;
  readonly epoch: number;
  /** H(Man): the manifest's digest. */
  readonly manifestHash: Uint8Array;
  /** The lineage's weight-updating total in the review period, including this job, as the module applied it. */
  readonly periodTotal: bigint;
}

/** A signed log entry. */
export interface ManifestLog extends ManifestLogBody {
  readonly sig: Uint8Array;
}

/** The digest of an epoch report body. */
export function reportDigest(r: EpochReportBody): Uint8Array {
  const m = r.meters;
  return schnorr.utils.taggedHash(
    REPORT_TAG,
    concatBytes(
      hash32(r.chipId),
      u64(r.epoch),
      u64(m.inference),
      u64(m.evaluation),
      u64(m.weightUpdating),
      u64(m.unmanifested),
      u32(r.loc.length),
      ...r.loc.flatMap((x) => [str(x.landmark), u64(x.rttNs)]),
      hash32(r.licId),
      u32(r.manifests.length),
      ...r.manifests.map(hash32),
      hash32(r.logHead),
      hash32(r.tipHash),
      str(r.state),
    ),
  );
}

/** The digest of a tamper alarm body. */
export function alarmDigest(a: TamperAlarmBody): Uint8Array {
  return schnorr.utils.taggedHash(ALARM_TAG, concatBytes(hash32(a.chipId), u64(a.local), hash32(a.tipHash)));
}

/** The digest of a manifest log entry. */
export function logDigest(l: ManifestLogBody): Uint8Array {
  if (l.periodTotal < 0n) throw new RangeError("periodTotal must be non-negative");
  const mag = l.periodTotal === 0n ? new Uint8Array() : numberToVarBytesBE(l.periodTotal);
  return schnorr.utils.taggedHash(LOG_TAG, concatBytes(hash32(l.chipId), u64(l.epoch), hash32(l.manifestHash), Uint8Array.of(mag.length), mag));
}

/** Signs an epoch report with the device key. */
export function signReport(r: EpochReportBody, devSecret: Uint8Array, auxRand?: Uint8Array): EpochReport {
  return { ...r, sig: schnorr.sign(reportDigest(r), devSecret, auxRand) };
}

/** Signs a tamper alarm with the device key, before the keys are destroyed. */
export function signAlarm(a: TamperAlarmBody, devSecret: Uint8Array, auxRand?: Uint8Array): TamperAlarm {
  return { ...a, sig: schnorr.sign(alarmDigest(a), devSecret, auxRand) };
}

/** Signs a manifest log entry with the device key. */
export function signLog(l: ManifestLogBody, devSecret: Uint8Array, auxRand?: Uint8Array): ManifestLog {
  return { ...l, sig: schnorr.sign(logDigest(l), devSecret, auxRand) };
}

/** Checks an epoch report's device signature. */
export function verifyReport(r: EpochReport, pkDev: Uint8Array): boolean {
  return verifySig(r.sig, () => reportDigest(r), pkDev);
}

/** Checks a tamper alarm's device signature. */
export function verifyAlarm(a: TamperAlarm, pkDev: Uint8Array): boolean {
  return verifySig(a.sig, () => alarmDigest(a), pkDev);
}

/** Checks a manifest log entry's device signature. */
export function verifyLog(l: ManifestLog, pkDev: Uint8Array): boolean {
  return verifySig(l.sig, () => logDigest(l), pkDev);
}

View on GitHub

src/fgm/types.ts230 lines
/**
 * Types for the Firebreak Guarantee Module (FGM) license state machine.
 *
 * Names follow the paper (Appendix A): the license tuple
 * (chip_id, op_id, tier, B, site_id, cset_id, h, H_from, H_to, lambda, d_min, nonce)
 * signed under the Council key K_C, and the six states of its license state machine.
 */
import type { JobType } from "../manifest";

/** The paper's six states. Display names are in STATUS_NAMES. */
export type Status = "Unlicensed" | "Licensed" | "Grace" | "OutageGrace" | "Hold" | "Tampered";

/** A Bitcoin chain position the beacon module has already verified. */
export interface Tip {
  readonly hash: Uint8Array;
  readonly height: number;
  /** Cumulative chain work at this block. The recorded tip's work never decreases. */
  readonly work: bigint;
}

/** The license body: everything the Council signs. */
export interface LicenseBody {
  /** chip_id = H(pk_dev), 32 bytes. */
  readonly chipId: Uint8Array;
  readonly opId: string;
  readonly tier: number;
  /** B: the work budget, in metered work units. */
  readonly budget: number;
  readonly siteId: string;
  /** The cluster set the chip may run high-bandwidth collectives with. */
  readonly csetId: string;
  /** h: the hash of a recent Bitcoin block. It must be newer than the chip's recorded tip. */
  readonly blockHash: Uint8Array;
  readonly heightFrom: number;
  readonly heightTo: number;
  /** lambda: the maximum local duration, in local seconds. */
  readonly lambda: number;
  /** d_min: the difficulty floor for headers while this license runs. */
  readonly dMin: number;
  /** 32 bytes; never accepted twice. */
  readonly nonce: Uint8Array;
}

/** A license: the body plus a BIP340 signature under the Council key K_C (a FROST group key). */
export interface License extends LicenseBody {
  readonly sig: Uint8Array;
}

/** A chip certificate (Appendix A): issued at enrollment and again at re-enrollment. */
export interface ChipCertBody {
  /** chip_id = SHA-256(pk_dev). */
  readonly chipId: Uint8Array;
  /** The device key derived from the chip's physical unclonable function (x-only, 32 bytes). */
  readonly pkDev: Uint8Array;
  readonly productClass: string;
  /** theta: effective throughput. */
  readonly theta: number;
  readonly fabId: string;
  /** Enrollment date, in seconds. */
  readonly date: number;
}

/** A certificate signed by the manufacturer and by the accredited enrollment officer. */
export interface ChipCert extends ChipCertBody {
  readonly sigMfr: Uint8Array;
  readonly sigEnr: Uint8Array;
}

/** Hold and confirm are signed by the Council; lift is signed by the dispute panel. */
export type OrderKind = "hold" | "confirm" | "lift";

/** An order body: its kind, a sequence number for anti-replay and the chip set it names. */
export interface OrderBody {
  readonly kind: OrderKind;
  readonly seq: number;
  readonly chips: readonly Uint8Array[];
}

/** A signed order. */
export interface Order extends OrderBody {
  readonly sig: Uint8Array;
}

/**
 * Positive evidence of a regime outage: every full block in [fromHeight, toHeight] was shown and checked
 * against its header's Merkle root, and the anchored roots found among them were counted.
 */
export interface OutageEvidence {
  readonly fromHeight: number;
  readonly toHeight: number;
  /** Full blocks shown and checked against their headers' Merkle roots. */
  readonly fullBlocks: number;
  /** Valid anchored epoch roots found in those blocks. */
  readonly anchorsFound: number;
  /** Whether the window's headers met the module's difficulty floor (the beacon's checkpoint floor). */
  readonly meetsFloor: boolean;
}

/** Constants fixed into the module at manufacture and enrollment. */
export interface FgmConfig {
  /** This chip's chip_id, 32 bytes. Changes only on re-enrollment. */
  readonly chipId: Uint8Array;
  /** K_C: the Council's x-only BIP340 key. It signs licenses, holds and confirmations. */
  readonly councilKey: Uint8Array;
  /** The dispute panel's x-only BIP340 key. It signs lifts. */
  readonly panelKey: Uint8Array;
  /** Keys that sign chip certificates, checked on re-enrollment. */
  readonly manufacturerKey: Uint8Array;
  readonly enrollmentKey: Uint8Array;
  /** The date on this chip's current certificate. Re-enrollment needs a later one. */
  readonly enrolledAt: number;
  /** True for chips registered to certified critical services, which get Grace after a lapse. */
  readonly critical: boolean;
  /** r: the chip's full rate, in work units per second. */
  readonly fullRate: number;
  /** g*r: the inference-only rate in Grace and OutageGrace. */
  readonly graceRate: number;
  /** r_0: the Tier 0 rate. */
  readonly tier0Rate: number;
  /** epsilon: the oscillators' tolerance, in parts per million. */
  readonly epsPpm: number;
  /** LAMBDA_MAX: the longest lambda the module accepts, in local seconds. */
  readonly lambdaMax: number;
  /** gamma: the grace period, in local seconds. */
  readonly gamma: number;
  /** The fixed period after which an unconfirmed hold lapses, in local seconds. */
  readonly holdPeriod: number;
  /** The outage window: how many consecutive blocks without an anchored root prove an outage. */
  readonly outageWindow: number;
}

/** Why a license stopped granting full rate. */
export type LapseCause = "budget" | "duration" | "height";

/** The installed license and its accounting. */
export interface LicenseSlot {
  readonly license: License;
  /** The local counter when the license was accepted. */
  readonly acceptedAt: number;
  /** Work metered against the budget so far. */
  readonly used: number;
  /** Set once, at the local time the license lapsed. */
  readonly lapsed: { readonly cause: LapseCause; readonly at: number } | null;
}

/** An active inspection hold. */
export interface HoldRecord {
  /** The local counter when the hold began. */
  readonly since: number;
  /** A finding confirmed the hold; it no longer lapses, and only a dispute-panel lift ends it. */
  readonly confirmed: boolean;
}

/** Work metered since enrollment, by workload. These feed the epoch report. */
export interface Meters {
  readonly inference: number;
  readonly evaluation: number;
  readonly weightUpdating: number;
  /** Work by jobs without a valid manifest (allowed only at r_0). */
  readonly unmanifested: number;
}

/** What the module signs, if it still can, the moment a tamper sensor fires. */
export interface TamperAlarmBody {
  readonly chipId: Uint8Array;
  readonly local: number;
  readonly tipHash: Uint8Array;
}

/** The module's whole persistent state. */
export interface FgmState {
  readonly config: FgmConfig;
  readonly status: Status;
  /** Local monotonic counter, in local seconds since enrollment. */
  readonly local: number;
  /** The recorded chain tip: the most cumulative work seen. */
  readonly tip: Tip;
  readonly slot: LicenseSlot | null;
  readonly hold: HoldRecord | null;
  /** True after valid outage evidence, until an anchored root is seen again. */
  readonly outage: boolean;
  /** Highest Council order sequence number accepted. */
  readonly councilSeq: number;
  /** Highest dispute panel order sequence number accepted. */
  readonly panelSeq: number;
  /** Nonces of every license accepted, hex. */
  readonly nonces: ReadonlySet<string>;
  readonly meters: Meters;
  /** The alarm body produced when the tamper sensor fired (Tampered only). */
  readonly alarm: TamperAlarmBody | null;
}

/** Inputs to the state machine. Chain positions, location and outage evidence are verified upstream. */
export type FgmEvent =
  /**
   * A license arrives with the beacon's verified position of its block h, whether the headers to h meet the
   * license's d_min, and whether the latest distance-bounding proof matches the license's site.
   */
  | { readonly type: "install"; readonly license: License; readonly at: Tip; readonly meetsFloor: boolean; readonly locationOk: boolean }
  /** The beacon verified a header chain to a new tip; meetsFloor says whether it met the running license's d_min. */
  | { readonly type: "headers"; readonly tip: Tip; readonly meetsFloor: boolean }
  /** Both oscillators report elapsed local seconds since the last tick. */
  | { readonly type: "tick"; readonly osc1: number; readonly osc2: number }
  /** Work metered since the last meter event, with its workload type and whether its manifest was valid. */
  | { readonly type: "meter"; readonly work: number; readonly jobType: JobType; readonly manifestOk: boolean }
  | { readonly type: "order"; readonly order: Order }
  | { readonly type: "outageEvidence"; readonly evidence: OutageEvidence }
  /** A valid anchored epoch root was seen. */
  | { readonly type: "anchorSeen" }
  | { readonly type: "tamper" }
  /**
   * Re-enrollment at an accredited facility: a new certificate, and the device key the module itself just
   * derived from its physical unclonable function (a hardware input, like the oscillator readings).
   */
  | { readonly type: "reenroll"; readonly cert: ChipCert; readonly derivedKey: Uint8Array };

/** What the throttle enforces until the next event. */
export interface Allowance {
  /** The highest rate for each workload type, for jobs with a valid manifest. */
  readonly rates: Readonly<Record<JobType, number>>;
  /** The highest rate for a job without a valid manifest: r_0. */
  readonly unmanifested: number;
  /** Local seconds these rates may run for (Infinity when the state has no timer). */
  readonly localUnits: number;
  /** Work units left at these rates (Infinity when the state has no budget). */
  readonly work: number;
  /** The rate the throttle drops to on its own when either limit runs out: r_0. */
  readonly fallback: number;
}

View on GitHub

src/fgm/validate.ts27 lines
/**
 * Shape checks for values that cross into the module. Anything that fails is
 * treated as malformed and never reaches the state machine's logic.
 */
import type { Tip } from "./types";

/** A safe non-negative integer: a count of seconds, work units or blocks. */
export function isCount(n: unknown): n is number {
  return typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
}

/** A byte string of exactly len bytes. */
export function isBytes(b: unknown, len: number): b is Uint8Array {
  return b instanceof Uint8Array && b.length === len;
}

/** A non-empty string. */
export function isText(s: unknown): s is string {
  return typeof s === "string" && s.length > 0;
}

/** A chain position with a 32-byte hash, a count height and non-negative bigint work. */
export function isTip(t: unknown): t is Tip {
  const tip = t as Tip;
  return typeof t === "object" && t !== null && isBytes(tip.hash, 32) && isCount(tip.height) && typeof tip.work === "bigint" && tip.work >= 0n;
}

View on GitHub

src/fgm/index.ts65 lines
/**
 * The Firebreak Guarantee Module's license state machine. See SPEC.md.
 */
export type {
  Allowance,
  ChipCert,
  ChipCertBody,
  FgmConfig,
  FgmEvent,
  FgmState,
  HoldRecord,
  LapseCause,
  License,
  LicenseBody,
  LicenseSlot,
  Meters,
  Order,
  OrderBody,
  OrderKind,
  OutageEvidence,
  Status,
  TamperAlarmBody,
  Tip,
} from "./types";
export {
  CERT_TAG,
  certDigest,
  LICENSE_TAG,
  licenseDigest,
  licenseId,
  ORDER_TAG,
  orderDigest,
  signCert,
  signLicense,
  signOrder,
  verifyCert,
  verifySig,
} from "./encoding";
export {
  ALARM_TAG,
  alarmDigest,
  type DistanceRound,
  type EpochReport,
  type EpochReportBody,
  LOG_TAG,
  logDigest,
  type ManifestLog,
  type ManifestLogBody,
  REPORT_TAG,
  reportDigest,
  signAlarm,
  signLog,
  signReport,
  type TamperAlarm,
  verifyAlarm,
  verifyLog,
  verifyReport,
} from "./outputs";
export { localAdvance, oscillatorsAgree } from "./clock";
export { checkLicense, type LicenseRejection, type LicenseVerdict } from "./license";
export { checkOrder, type OrderRejection, type OrderVerdict } from "./orders";
export { provesOutage } from "./outage";
export { boot, STATUS_NAMES, step } from "./machine";
export { allowance, licenseWindow, mayLink, rate } from "./limits";

View on GitHub