Firebreak

Reference implementation

Manifests and loop closure

Job manifests, per-lineage cumulative accounting and the two-signature rule.

Source
8 files, 688 lines
Tests
1 files, 26 cases
Paper
sec:definitions

Job manifests and the loop-closure rule

Purpose

Every job on governed hardware runs under a signed manifest. Before an FGM allocates any budget to a job, it checks the manifest. A weight update that would take a lineage's weight-updating compute in the review period above E_0 needs two enrolled humans to sign it. This is the paper's loop-closure rule (Definition 10, Article IV), and the paper's open-loop theorem rests on it.

verifyManifest(manifest, { registry, lineageCompute }, policy): Verdict
verifyLineage(manifests, registry, policy): Verdict[]   // one lineage, one review period, in order

Data formats

Manifest

Fields follow the paper: Man = (job_id, op_id, lineage_id, type, B_job, w, spec, sigs).

Field Type Meaning
jobId, opId, lineageId non-empty strings
type inference, evaluation or weight-updating
budget bigint, 0 <= B < 2^256 B_job in effective compute
weights 32 bytes w: hash of the fixed weights, or of the starting weights for an update
spec 32 bytes hash of the registered training specification (all zero when there is none)
sigs { keyId, sig }[] BIP340 signatures over the digest

Canonical encoding. Fields are written in table order. Strings are a u32 little-endian byte length followed by UTF-8. The type is one byte (1 inference, 2 evaluation, 3 weight-updating). The budget is one length byte followed by its minimal big-endian magnitude (zero has length 0). Hashes are raw 32 bytes. Signatures are not encoded. Digest: taggedHash("Firebreak/manifest", encoding).

Registry

{ keyId, pubkey, kind: "human" | "service", org, person, accredited, revoked }, built with makeRegistry. It refuses duplicate key ids, duplicate public keys, human keys without a person and service keys that name one.

Policy

{ e0, e1, eMax, closure: "cumulative" | "per-update", independentSigner }.

The check

Step Rule
1 Malformed fields fail at once, with the field named.
2 lineageTotal = lineageCompute + budget for weight-updating jobs. lineageCompute comes from the verifier's ledger records, never from the manifest.
3 The rule applies when the job is weight-updating and lineageTotal > E_0 (cumulative), or budget > E_0 (per-update).
4 Signatures: each is checked once. An unknown key, a revoked key, a repeated public key or a bad signature does not count. A service key counts only as the operator's signature. Each person counts once, whatever number of keys they sign with.
5 When the rule applies: at least 2 distinct persons, and (if independentSigner) at least one with org != opId and accredited. When it does not: at least one valid signature by a key whose org is the operator.
6 Weight-updating compute may not pass E_max, per job (budget) or per lineage (lineageTotal), whatever the signatures.
7 Tier, for weight-updating jobs: 2 if budget > E_1, else 1 if lineageTotal > E_0, else 0; none if prohibited.

The verdict lists every failure reason and how each signature was treated (counted, service, unknown-key, revoked, duplicate-key, duplicate-person, bad-signature).

Security properties and the tests that check them

The tests are in test/manifest/manifest.test.ts.

Property Test
No manifest above E_0 verifies without two distinct, enrolled, unrevoked human persons, one independent and accredited. The test counts persons itself, over arbitrary mixes of genuine, forged, revoked, service, unknown and same-person signatures. "no manifest above E_0 verifies without two distinct..." (property)
The same key twice counts once; two keys of one person count once "counts the same key twice once...", "repeating any signature never changes the outcome" (property)
Revoked, service and unknown keys and forged signatures are not counted "does not count revoked keys, service keys..."
Changing any field after signing invalidates every signature "changing any field after signing invalidates every signature" (property)
A salami sequence of updates, each at or below E_0, passes per-update and fails cumulative at exactly the step that crosses E_0 "a salami sequence..." (property)
E_max is enforced per job and per lineage regardless of signatures "refuses weight-updating compute above E_max..."
Below the threshold, the operator's own signature is required and sufficient "needs only the operator's signature below the threshold"
The encoding is exactly as documented "encodes fields in the documented order and layout"

What code cannot check

"No AI holds signing keys" is not checkable by code. The verifier can only see that a key was enrolled as kind human and bound to a person. Whether a person, and not a software agent, actually operates the key rests on in-person enrollment and on custody hardware that signs only on a physical action by the enrolled person (Definition 10, item 2). Likewise, "one person, one key" can be enforced only within the registry. A person enrolled twice under different names would count twice.

Interpretations

  • Cumulative is the rule. Definition 10 and Definition 9 state the rule over the lineage's cumulative weight-updating compute in a review period, summed across operators. The per-update mode exists only to demonstrate what that catches.
  • No reset on approval. Within a review period, once the total passes E_0, every further update needs two signatures (Definition 9: "each further such job"). The total resets only at the next review period.
  • The operator signature below the threshold may come from any of the operator's keys (service or human).
  • Tiers and E_max apply to weight-updating jobs. The paper's tier table has no threshold for "large inference services", so inference and evaluation manifests get no tier here.

Open questions for the paper's authors

  • Article IV says "weight-updating manifests above E_0", which reads per manifest. Definition 10 is cumulative. The treaty text should match the definition.
  • Lineage compute must include "every lineage whose weights or outputs are merged or distilled into it". The verifier needs a lineage graph from the ledger to compute that. This module takes the total as an input.
  • The Tier 2 limits (at most J jobs per operator per review period, evaluations filed for at least tau_eval before the next Tier 2 job) need history across manifests and are not modeled.
  • The authorization record (job_id, H(Man), signer_ids, h) that must reach the ledger by the end of the epoch is not modeled.

Source

The code

src/manifest/authorization.ts49 lines
/**
 * Authorization records (Appendix A).
 *
 * For each weight-updating manifest above the threshold, the record
 * (job_id, H(Man), signer_ids, h) must be committed to the ledger no later than
 * the end of the epoch in which the job begins. The record is a leaf of that
 * epoch's sorted tree, keyed by H(Man).
 */
import { concatBytes } from "@noble/hashes/utils.js";
import { type Entry, type EpochRecord, type InclusionProof, verifyInclusion } from "../ledger";
import { hash32, manifestDigest, str, u32 } from "./encoding";
import type { Manifest, Verdict } from "./types";

/** (job_id, H(Man), signer_ids, h). */
export interface AuthorizationRecord {
  readonly jobId: string;
  readonly manifestHash: Uint8Array;
  /** The enrolled human signers counted toward approval. */
  readonly signerIds: readonly string[];
  /** h: a recent block hash, dating the authorization. */
  readonly blockHash: Uint8Array;
}

/** The record for an accepted manifest that needed human approval; null for any other verdict. */
export function authorizationRecord(m: Manifest, v: Verdict, blockHash: Uint8Array): AuthorizationRecord | null {
  if (!v.ok || !v.needsHumanApproval) return null;
  return { jobId: m.jobId, manifestHash: manifestDigest(m), signerIds: v.humanSigners, blockHash };
}

/** Serializes a record canonically. */
export function encodeAuthorization(r: AuthorizationRecord): Uint8Array {
  return concatBytes(str(r.jobId), hash32(r.manifestHash), u32(r.signerIds.length), ...r.signerIds.map(str), hash32(r.blockHash));
}

/** The ledger leaf for a record: key H(Man), value the encoded record. */
export function authorizationEntry(r: AuthorizationRecord): Entry {
  return { key: r.manifestHash, value: encodeAuthorization(r) };
}

/**
 * Whether the record was committed in time: included in the tree of an epoch no later than the one the job
 * began in. The caller must already have checked that the epoch record is the anchored one.
 */
export function committedInTime(r: AuthorizationRecord, jobStartEpoch: number, epoch: EpochRecord, proof: InclusionProof): boolean {
  if (epoch.epoch > jobStartEpoch) return false;
  const e = authorizationEntry(r);
  return verifyInclusion(epoch.root, epoch.size, e.key, e.value, proof);
}

View on GitHub

src/manifest/encoding.ts74 lines
/**
 * Canonical encodings and digests: manifests, training specifications and
 * authorization records.
 *
 * Fields are written in a fixed order: strings as u32 little-endian length then
 * UTF-8; the job type as one byte; amounts as one length byte then their
 * minimal big-endian magnitude (zero is length 0); hashes as raw 32 bytes.
 * Each digest is a BIP340 tagged hash of its encoding. Signatures are not part
 * of the manifest digest; each signer signs the digest.
 */
import { schnorr } from "@noble/curves/secp256k1.js";
import { numberToVarBytesBE } from "@noble/curves/utils.js";
import { concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
import type { JobType, ManifestBody, ManifestSignature, TrainingSpec } from "./types";

/** BIP340 tag for manifest digests. */
export const MANIFEST_TAG = "Firebreak/manifest";
/** BIP340 tag for training specification digests. */
export const SPEC_TAG = "Firebreak/manifest/spec";

const TYPE_BYTE: Record<JobType, number> = { inference: 1, evaluation: 2, "weight-updating": 3 };
const SOURCE_BYTE = { merge: 1, distill: 2 } as const;

/** 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 non-negative amount below 2^256 as a length byte then its minimal big-endian magnitude. */
export function amount(n: bigint): Uint8Array {
  if (n < 0n || n >= 1n << 256n) throw new RangeError(`amount out of range: ${n}`);
  const mag = n === 0n ? new Uint8Array() : numberToVarBytesBE(n);
  return concatBytes(Uint8Array.of(mag.length), mag);
}

/** 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;
}

/** Serializes a manifest body canonically; throws on a malformed field. */
export function encodeManifest(m: ManifestBody): Uint8Array {
  const typeByte = TYPE_BYTE[m.type];
  if (typeByte === undefined) throw new RangeError(`unknown job type: ${String(m.type)}`);
  return concatBytes(str(m.jobId), str(m.opId), str(m.lineageId), Uint8Array.of(typeByte), amount(m.budget), hash32(m.weights), hash32(m.spec));
}

/** H(Man): the digest every signer signs, taggedHash("Firebreak/manifest", encodeManifest(body)). */
export function manifestDigest(m: ManifestBody): Uint8Array {
  return schnorr.utils.taggedHash(MANIFEST_TAG, encodeManifest(m));
}

/** The hash a manifest's spec field must equal for this training specification. */
export function specDigest(s: TrainingSpec): Uint8Array {
  return schnorr.utils.taggedHash(
    SPEC_TAG,
    concatBytes(u32(s.sources.length), ...s.sources.map((x) => concatBytes(Uint8Array.of(SOURCE_BYTE[x.kind]), str(x.lineageId))), u32(s.details.length), s.details),
  );
}

/** Signs a manifest body with an enrolled key. */
export function signManifest(m: ManifestBody, keyId: string, secretKey: Uint8Array, auxRand?: Uint8Array): ManifestSignature {
  return { keyId, sig: schnorr.sign(manifestDigest(m), secretKey, auxRand) };
}

View on GitHub

src/manifest/lineage.ts122 lines
/**
 * The lineage ledger: what the regime has recorded about each lineage's
 * weight-updating compute.
 *
 * Definition 9 counts toward a lineage its own weight-updating compute (summed
 * across all operators and sites), the compute of every lineage merged or
 * distilled into it, and the panel's estimate for weights of unrecorded
 * provenance. E_0 applies to that total within one review period; E_max caps
 * it over the lineage's whole history.
 *
 * Each lineage keeps a table of the compute counted toward it, keyed by the
 * source lineage the compute was done in and the review period it was done in.
 * A source's own entries only grow, so when lineages combine, the child takes
 * the larger entry for each (source, period). That counts a shared ancestor
 * once, and never counts compute a parent does after the child split from it.
 */
import { bytesToHex } from "@noble/hashes/utils.js";

/** How a lineage came to count another's compute. */
export type EdgeKind = "fork" | "merge" | "distill" | "provenance";

/** One recorded inheritance: the parent, how, and in which review period. */
export interface Edge {
  readonly parent: string;
  readonly kind: EdgeKind;
  readonly period: number;
}

/** source lineage -> review period -> compute counted. */
export type Counted = ReadonlyMap<string, ReadonlyMap<number, bigint>>;

/** One lineage's accounting. */
export interface LineageAccount {
  readonly id: string;
  readonly counted: Counted;
  readonly edges: readonly Edge[];
}

/** The ledger's lineage records. */
export interface LineageLedger {
  readonly lineages: ReadonlyMap<string, LineageAccount>;
  /** The lineage (or provenance record) each recorded weights hash belongs to, keyed by hex. */
  readonly weights: ReadonlyMap<string, string>;
}

/** Prefix of the pseudo-lineages that hold provenance charges. Manifests may not use it. */
export const PROVENANCE_PREFIX = "provenance:";

/** A ledger with no lineages and no recorded weights. */
export function emptyLedger(): LineageLedger {
  return { lineages: new Map(), weights: new Map() };
}

/** The lineage's compute over its whole history, inherited compute and provenance charges included. */
export function cumulative(ledger: LineageLedger, id: string): bigint {
  let total = 0n;
  for (const byPeriod of ledger.lineages.get(id)?.counted.values() ?? []) for (const v of byPeriod.values()) total += v;
  return total;
}

/** The lineage's compute in one review period, across every source counted toward it. */
export function periodTotal(ledger: LineageLedger, id: string, period: number): bigint {
  let total = 0n;
  for (const byPeriod of ledger.lineages.get(id)?.counted.values() ?? []) total += byPeriod.get(period) ?? 0n;
  return total;
}

/** Adds compute done in lineage `id` during `period` (creating the lineage if it is new). */
export function recordCompute(ledger: LineageLedger, id: string, period: number, amount: bigint): LineageLedger {
  if (amount < 0n) throw new RangeError("compute must be non-negative");
  const acct = account(ledger, id);
  const own = new Map(acct.counted.get(id) ?? []);
  own.set(period, (own.get(period) ?? 0n) + amount);
  return put(ledger, { ...acct, counted: new Map(acct.counted).set(id, own) });
}

/** Makes `child` count everything `parent` counts now (fork, merge or distillation in `period`). */
export function inherit(ledger: LineageLedger, child: string, parent: string, kind: EdgeKind, period: number): LineageLedger {
  if (child === parent) return ledger;
  const c = account(ledger, child);
  const p = account(ledger, parent);
  const counted = new Map(c.counted);
  for (const [source, byPeriod] of p.counted) {
    const mine = new Map(counted.get(source) ?? []);
    for (const [per, v] of byPeriod) if (v > (mine.get(per) ?? 0n)) mine.set(per, v);
    counted.set(source, mine);
  }
  const known = c.edges.some((e) => e.parent === parent && e.kind === kind);
  return put(ledger, { ...c, counted, edges: known ? c.edges : [...c.edges, { parent, kind, period }] });
}

/** Records that weights w belong to lineage `id`; a hash already recorded keeps its first owner. */
export function recordWeights(ledger: LineageLedger, w: Uint8Array, id: string): LineageLedger {
  const hex = bytesToHex(w);
  if (ledger.weights.has(hex)) return ledger;
  return { ...withLineage(ledger, id), weights: new Map(ledger.weights).set(hex, id) };
}

/** Charges unrecorded weights at the panel's estimate: a provenance record that owns w, dated `period`. */
export function chargeProvenance(ledger: LineageLedger, w: Uint8Array, estimate: bigint, period: number): { ledger: LineageLedger; id: string } {
  const id = PROVENANCE_PREFIX + bytesToHex(w);
  return { ledger: recordWeights(recordCompute(ledger, id, period, estimate), w, id), id };
}

/** The lineage a weights hash belongs to, or undefined if the ledger has not seen it. */
export function ownerOf(ledger: LineageLedger, w: Uint8Array): string | undefined {
  return ledger.weights.get(bytesToHex(w));
}

function account(ledger: LineageLedger, id: string): LineageAccount {
  return ledger.lineages.get(id) ?? { id, counted: new Map(), edges: [] };
}

/** The ledger with lineage `id` present (empty if new). */
function withLineage(ledger: LineageLedger, id: string): LineageLedger {
  return ledger.lineages.has(id) ? ledger : put(ledger, account(ledger, id));
}

function put(ledger: LineageLedger, a: LineageAccount): LineageLedger {
  return { ...ledger, lineages: new Map(ledger.lineages).set(a.id, a) };
}

View on GitHub

src/manifest/registry.ts51 lines
/**
 * The enrolled-signer registry.
 *
 * The registry is where "no AI holds signing keys" becomes checkable at all:
 * code can only see that a key was enrolled as kind "human" and bound to a
 * person. Whether a person, and not software, operates it rests on in-person
 * enrollment and on hardware that signs only on a physical action.
 *
 * The registry for each epoch is anchored as a sorted tree, so a slashing
 * claim can name exactly the registry a manifest was checked against.
 */
import { sha256 } from "@noble/hashes/sha2.js";
import { bytesToHex, concatBytes, utf8ToBytes } from "@noble/hashes/utils.js";
import { buildTree, type EpochTree } from "../ledger";
import { hash32, str } from "./encoding";
import type { EnrolledKey, Registry } from "./types";

/** Builds a registry, refusing duplicate keyIds, duplicate public keys and human keys without a person. */
export function makeRegistry(keys: readonly EnrolledKey[]): Registry {
  const byId = new Map<string, EnrolledKey>();
  const pubkeys = new Set<string>();
  for (const k of keys) {
    if (k.pubkey.length !== 32) throw new RangeError(`key ${k.keyId}: pubkey must be 32 bytes`);
    if (byId.has(k.keyId)) throw new RangeError(`duplicate keyId ${k.keyId}`);
    const hex = bytesToHex(k.pubkey);
    if (pubkeys.has(hex)) throw new RangeError(`key ${k.keyId}: public key already enrolled`);
    if (k.kind === "human" && !k.person) throw new RangeError(`human key ${k.keyId} has no person`);
    if (k.kind === "service" && k.person !== null) throw new RangeError(`service key ${k.keyId} names a person`);
    byId.set(k.keyId, k);
    pubkeys.add(hex);
  }
  return byId;
}

/** Serializes one enrolled key canonically. */
export function encodeEnrolledKey(k: EnrolledKey): Uint8Array {
  return concatBytes(
    str(k.keyId),
    hash32(k.pubkey),
    Uint8Array.of(k.kind === "human" ? 1 : 2),
    str(k.org),
    str(k.person ?? ""),
    Uint8Array.of(k.accredited ? 1 : 0, k.revoked ? 1 : 0),
  );
}

/** The registry as a sorted tree: one leaf per key, keyed by SHA-256(keyId). Its root is what gets anchored. */
export function registryTree(registry: Registry): EpochTree {
  return buildTree([...registry.values()].map((k) => ({ key: sha256(utf8ToBytes(k.keyId)), value: encodeEnrolledKey(k) })));
}

View on GitHub

src/manifest/types.ts150 lines
/**
 * Types for job manifests, the enrolled-signer registry and the loop-closure check.
 *
 * Manifest fields follow the paper (Appendix A, "Message formats"):
 * Man = (job_id, op_id, lineage_id, type, B_job, w, spec, sigs).
 */
import type { LineageLedger } from "./lineage";

/** The three workload types a manifest can declare. */
export type JobType = "inference" | "evaluation" | "weight-updating";

/** Everything a manifest's signers sign. */
export interface ManifestBody {
  readonly jobId: string;
  readonly opId: string;
  readonly lineageId: string;
  readonly type: JobType;
  /** B_job: the job's budget in effective compute. */
  readonly budget: bigint;
  /** w: hash of the fixed weights (inference, evaluation) or of the starting weights (weight-updating), 32 bytes. */
  readonly weights: Uint8Array;
  /** spec: hash of the training specification (weight-updating), 32 zero bytes otherwise. */
  readonly spec: Uint8Array;
}

/** One signature on a manifest, naming the enrolled key that made it. */
export interface ManifestSignature {
  readonly keyId: string;
  readonly sig: Uint8Array;
}

/** A signed manifest. */
export interface Manifest extends ManifestBody {
  readonly sigs: readonly ManifestSignature[];
}

/** A lineage whose weights or outputs a weight-updating job takes in. */
export interface SpecSource {
  readonly lineageId: string;
  readonly kind: "merge" | "distill";
}

/**
 * The training specification that spec hashes. Only the part the accounting needs is structured:
 * the lineages merged or distilled into this job. Everything else (data, recipe) is opaque here.
 */
export interface TrainingSpec {
  readonly sources: readonly SpecSource[];
  readonly details: Uint8Array;
}

/** An entry in the enrolled-signer registry anchored for an epoch. */
export interface EnrolledKey {
  readonly keyId: string;
  /** x-only BIP340 public key, 32 bytes. */
  readonly pubkey: Uint8Array;
  /** "human": bound to a natural person by in-person enrollment. "service": an operator's automated key. */
  readonly kind: "human" | "service";
  /** The operator or body the key belongs to. */
  readonly org: string;
  /** The natural person a human key is bound to; null for service keys. */
  readonly person: string | null;
  /** Accredited by the regime as an independent signer. */
  readonly accredited: boolean;
  readonly revoked: boolean;
}

/** The registry, keyed by keyId. Build it with makeRegistry so duplicates are refused. */
export type Registry = ReadonlyMap<string, EnrolledKey>;

/** Parameters of the check, from the Technical Annex. */
export interface Policy {
  /** E_0: the loop-closure threshold on a lineage's weight-updating compute per review period. */
  readonly e0: bigint;
  /** E_1: the largest single run in Tier 1. */
  readonly e1: bigint;
  /** E_max: the prohibited ceiling, per run and on a lineage's cumulative compute over its whole history. */
  readonly eMax: bigint;
}

/** The panel's estimate of the training compute behind weights the ledger has not seen (Definition 9). */
export type ProvenanceEstimate = (weights: Uint8Array) => bigint;

/** What the verifier knows besides the manifest. */
export interface Context {
  /** The enrolled-signer registry anchored for this epoch. */
  readonly registry: Registry;
  /** The ledger's lineage records, before this manifest. */
  readonly ledger: LineageLedger;
  /** The current review period. */
  readonly period: number;
  readonly estimate: ProvenanceEstimate;
  /** The training specification whose hash is the manifest's spec (weight-updating jobs only). */
  readonly spec?: TrainingSpec;
}

/** How each listed signature was treated. */
export type SignatureStatus =
  | "counted"
  | "service"
  | "unknown-key"
  | "revoked"
  | "duplicate-key"
  | "duplicate-person"
  | "bad-signature";

/** How the manifest's w tied the job to the ledger. */
export type Binding =
  /** w belongs to this lineage already. */
  | "continuation"
  /** w belongs to another lineage, whose compute this lineage now counts. */
  | "fork"
  /** The ledger had not seen w; it was charged at the panel's estimate. */
  | "provenance"
  /** w was charged at the panel's estimate earlier, as a provenance record. */
  | "recorded-provenance";

/** Why a manifest failed. */
export type Reason =
  | { readonly code: "malformed"; readonly field: string }
  | { readonly code: "spec-mismatch" }
  | { readonly code: "unknown-source"; readonly lineageId: string }
  | { readonly code: "prohibited-run"; readonly budget: bigint }
  | { readonly code: "prohibited-lineage"; readonly cumulative: bigint }
  | { readonly code: "no-operator-signature" }
  | { readonly code: "too-few-human-signers"; readonly have: number }
  | { readonly code: "no-independent-signer" };

/** The full outcome: pass or fail, with every reason and how each signature counted. */
export interface Verdict {
  readonly ok: boolean;
  readonly reasons: readonly Reason[];
  readonly binding: Binding | null;
  /** The panel's estimate charged for unseen w (0 when w was already recorded). */
  readonly provenanceCharge: bigint;
  /** True when the loop-closure rule applies to this manifest. */
  readonly needsHumanApproval: boolean;
  /** The lineage's compute in this review period, including this job if weight-updating. */
  readonly periodTotal: bigint;
  /** The lineage's compute over its whole history, including this job if weight-updating. */
  readonly cumulative: bigint;
  /** For weight-updating jobs: the tier by compute (null when prohibited or not weight-updating). */
  readonly tier: 0 | 1 | 2 | null;
  /** keyIds of the distinct human signers counted toward approval. */
  readonly humanSigners: readonly string[];
  readonly signatures: readonly { readonly keyId: string; readonly status: SignatureStatus }[];
  /** The ledger after accepting this manifest; null when it is rejected. */
  readonly next: LineageLedger | null;
}

View on GitHub

src/manifest/verify.ts167 lines
/**
 * The manifest check a guarantee module runs before allocating budget to a job.
 *
 * 1. Bind w to the ledger. Weights the ledger has recorded tie the job to their
 *    lineage; weights it has not seen are charged at the panel's estimate
 *    (Definition 9).
 * 2. For a weight-updating job, check the training specification against spec
 *    and count every lineage it merges or distills.
 * 3. The loop-closure rule (Definition 10): a weight-updating job that takes
 *    the lineage's compute in this review period, summed across all operators
 *    and sites, above E_0 needs signatures from two enrolled natural persons,
 *    at least one independent of the operator and accredited. Every other
 *    manifest needs the operator's signature.
 * 4. E_max: no single run above it, and no lineage whose cumulative compute
 *    over its whole history (ancestors, merges, distillation and provenance
 *    charges included) would pass it.
 */
import { schnorr } from "@noble/curves/secp256k1.js";
import { equalBytes } from "@noble/curves/utils.js";
import { bytesToHex } from "@noble/hashes/utils.js";
import { manifestDigest, specDigest } from "./encoding";
import { chargeProvenance, cumulative, inherit, type LineageLedger, ownerOf, periodTotal, PROVENANCE_PREFIX, recordCompute } from "./lineage";
import type { Binding, Context, Manifest, Policy, ProvenanceEstimate, Reason, Registry, SignatureStatus, Verdict } from "./types";

/** Checks a manifest against the registry, the lineage ledger and the policy. */
export function verifyManifest(m: Manifest, ctx: Context, policy: Policy): Verdict {
  const malformed = findMalformed(m);
  if (malformed) {
    return {
      ok: false,
      reasons: [{ code: "malformed", field: malformed }],
      binding: null,
      provenanceCharge: 0n,
      needsHumanApproval: false,
      periodTotal: 0n,
      cumulative: 0n,
      tier: null,
      humanSigners: [],
      signatures: [],
      next: null,
    };
  }
  const updating = m.type === "weight-updating";
  const reasons: Reason[] = [];

  const bound = bindWeights(ctx.ledger, m, ctx.period, ctx.estimate);
  let ledger = bound.ledger;
  if (updating) {
    if (!ctx.spec || !equalBytes(specDigest(ctx.spec), m.spec)) reasons.push({ code: "spec-mismatch" });
    else
      for (const src of ctx.spec.sources) {
        if (!ledger.lineages.has(src.lineageId)) reasons.push({ code: "unknown-source", lineageId: src.lineageId });
        else ledger = inherit(ledger, m.lineageId, src.lineageId, src.kind, ctx.period);
      }
  }

  const job = updating ? m.budget : 0n;
  const inPeriod = periodTotal(ledger, m.lineageId, ctx.period) + job;
  const total = cumulative(ledger, m.lineageId) + job;
  const needsHumanApproval = updating && inPeriod > policy.e0;
  if (updating && m.budget > policy.eMax) reasons.push({ code: "prohibited-run", budget: m.budget });
  if (updating && total > policy.eMax) reasons.push({ code: "prohibited-lineage", cumulative: total });

  const { signatures, humans, operatorSigned, independent } = checkApproval(m, ctx.registry);
  if (needsHumanApproval) {
    if (humans.length < 2) reasons.push({ code: "too-few-human-signers", have: humans.length });
    if (!independent) reasons.push({ code: "no-independent-signer" });
  } else if (!operatorSigned) {
    reasons.push({ code: "no-operator-signature" });
  }

  const ok = reasons.length === 0;
  const prohibited = reasons.some((r) => r.code === "prohibited-run" || r.code === "prohibited-lineage");
  const tier = !updating || prohibited ? null : m.budget > policy.e1 ? 2 : inPeriod > policy.e0 ? 1 : 0;
  return {
    ok,
    reasons,
    binding: bound.binding,
    provenanceCharge: bound.charge,
    needsHumanApproval,
    periodTotal: inPeriod,
    cumulative: total,
    tier,
    humanSigners: humans.map((h) => h.keyId),
    signatures,
    next: !ok ? null : updating ? recordCompute(ledger, m.lineageId, ctx.period, m.budget) : ledger,
  };
}

/** Ties the manifest's lineage to whatever produced w, charging unseen weights at the panel's estimate. */
function bindWeights(ledger: LineageLedger, m: Manifest, period: number, estimate: ProvenanceEstimate): { ledger: LineageLedger; binding: Binding; charge: bigint } {
  const owner = ownerOf(ledger, m.weights);
  if (owner === undefined) {
    const charge = estimate(m.weights);
    const p = chargeProvenance(ledger, m.weights, charge, period);
    return { ledger: inherit(p.ledger, m.lineageId, p.id, "provenance", period), binding: "provenance", charge };
  }
  if (owner === m.lineageId) return { ledger, binding: "continuation", charge: 0n };
  const recorded = owner.startsWith(PROVENANCE_PREFIX);
  return { ledger: inherit(ledger, m.lineageId, owner, recorded ? "provenance" : "fork", period), binding: recorded ? "recorded-provenance" : "fork", charge: 0n };
}

/** How a manifest's signatures count under the loop-closure rule, against one registry. */
export interface Approval {
  readonly signatures: readonly { readonly keyId: string; readonly status: SignatureStatus }[];
  /** Distinct enrolled persons with valid signatures. */
  readonly humans: readonly { readonly keyId: string; readonly org: string; readonly accredited: boolean }[];
  /** Some valid signature is by a key of the operator itself. */
  readonly operatorSigned: boolean;
  /** Some counted person is independent of the operator and accredited. */
  readonly independent: boolean;
  /** The loop-closure rule's signature requirement is met: two persons, one independent and accredited. */
  readonly approved: boolean;
}

/** Verifies each listed signature once against the registry, counting each key and each person at most once. */
export function checkApproval(m: Manifest, registry: Registry): Approval {
  const digest = manifestDigest(m);
  const seenKeys = new Set<string>();
  const seenPeople = new Set<string>();
  const humans: { keyId: string; org: string; accredited: boolean }[] = [];
  let operatorSigned = false;
  const signatures = m.sigs.map(({ keyId, sig }) => {
    const status = ((): SignatureStatus => {
      const key = registry.get(keyId);
      if (!key) return "unknown-key";
      if (key.revoked) return "revoked";
      const pub = bytesToHex(key.pubkey);
      if (seenKeys.has(pub)) return "duplicate-key";
      if (!verifies(sig, digest, key.pubkey)) return "bad-signature";
      seenKeys.add(pub);
      if (key.org === m.opId) operatorSigned = true;
      if (key.kind === "service") return "service";
      if (seenPeople.has(key.person as string)) return "duplicate-person";
      seenPeople.add(key.person as string);
      humans.push({ keyId, org: key.org, accredited: key.accredited });
      return "counted";
    })();
    return { keyId, status };
  });
  const independent = humans.some((h) => h.org !== m.opId && h.accredited);
  return { signatures, humans, operatorSigned, independent, approved: humans.length >= 2 && independent };
}

function verifies(sig: Uint8Array, digest: Uint8Array, pubkey: Uint8Array): boolean {
  try {
    return sig instanceof Uint8Array && sig.length === 64 && schnorr.verify(sig, digest, pubkey);
  } catch {
    return false;
  }
}

/** Names the first malformed field, or returns null. */
function findMalformed(m: Manifest): string | null {
  const text = (s: unknown) => typeof s === "string" && s.length > 0;
  const hash = (b: unknown) => b instanceof Uint8Array && b.length === 32;
  if (!text(m.jobId)) return "jobId";
  if (!text(m.opId)) return "opId";
  if (!text(m.lineageId) || m.lineageId.startsWith(PROVENANCE_PREFIX)) return "lineageId";
  if (!["inference", "evaluation", "weight-updating"].includes(m.type)) return "type";
  if (typeof m.budget !== "bigint" || m.budget < 0n || m.budget >= 1n << 256n) return "budget";
  if (!hash(m.weights)) return "weights";
  if (!hash(m.spec)) return "spec";
  if (!Array.isArray(m.sigs) || !m.sigs.every((s) => text(s?.keyId))) return "sigs";
  return null;
}

View on GitHub

src/manifest/workload.ts27 lines
/**
 * Which manifest type a workload must run under (Definition 9).
 *
 * Every change to a model's weights on governed hardware is a metered update,
 * including the training of adapters or other added parameters, whether it
 * happens in a scheduled training job, in fine-tuning or during deployment.
 * So the setting never matters, and adapter training is weight-updating like
 * any other update.
 */
import type { JobType } from "./types";

/** What a job does to the model's parameters, and where it runs. */
export interface Workload {
  /** Which parameters the job changes: none, the base weights, an adapter (such as low-rank), or other added parameters. */
  readonly updates: "none" | "base" | "adapter" | "added";
  /** Where it runs. Recorded only to show it changes nothing. */
  readonly setting: "training" | "fine-tuning" | "deployment";
  /** For a job that changes no parameters: true when it only measures the model. */
  readonly measuresOnly: boolean;
}

/** The manifest type a workload must declare. */
export function requiredType(w: Workload): JobType {
  if (w.updates !== "none") return "weight-updating";
  return w.measuresOnly ? "evaluation" : "inference";
}

View on GitHub

src/manifest/index.ts48 lines
/**
 * Job manifests, lineage accounting and the loop-closure check. See SPEC.md.
 */
export type {
  Binding,
  Context,
  EnrolledKey,
  JobType,
  Manifest,
  ManifestBody,
  ManifestSignature,
  Policy,
  ProvenanceEstimate,
  Reason,
  Registry,
  SignatureStatus,
  SpecSource,
  TrainingSpec,
  Verdict,
} from "./types";
export { encodeManifest, MANIFEST_TAG, manifestDigest, signManifest, SPEC_TAG, specDigest } from "./encoding";
export { encodeEnrolledKey, makeRegistry, registryTree } from "./registry";
export {
  chargeProvenance,
  type Counted,
  cumulative,
  type Edge,
  type EdgeKind,
  emptyLedger,
  inherit,
  type LineageAccount,
  type LineageLedger,
  ownerOf,
  periodTotal,
  PROVENANCE_PREFIX,
  recordCompute,
  recordWeights,
} from "./lineage";
export { type Approval, checkApproval, verifyManifest } from "./verify";
export { requiredType, type Workload } from "./workload";
export {
  type AuthorizationRecord,
  authorizationEntry,
  authorizationRecord,
  committedInTime,
  encodeAuthorization,
} from "./authorization";

View on GitHub