Source code / TypeScript
Proof source
The prover and verifier used by The Constellation Proof.
import { ristretto255, ristretto255_hasher } from "@noble/curves/ed25519.js";
type Edge = readonly [number, number];
export const EDGES: readonly Edge[] = [[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 0], [0, 2], [2, 4], [4, 0]];
export const EXTRA: Edge = [1, 3];
export const SAMPLE = [0, 2, 1, 0, 2, 1];
export type Certificate = { version: 1; extra: boolean; transcript: string };
const Point = ristretto255.Point;
type Element = InstanceType<typeof Point>;
const field = Point.Fn;
const domain = new TextEncoder().encode("observatory/graph-coloring/ristretto255/v1");
const H = ristretto255_hasher.hashToCurve(new TextEncoder().encode("observatory/pedersen/H/v1")).precompute(5);
const palette = [0, 1, 2];
const differences = [-2, -1, 1, 2];
const vertexCount = 6;
const offsets = new Map([...palette, ...differences].map(value => [
value, Point.BASE.multiplyUnsafe(field.create(BigInt(value))),
]));
function join(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
const result = new Uint8Array(parts.reduce((length, part) => length + part.length, 0));
let offset = 0;
for (const part of parts) {
result.set(part, offset);
offset += part.length;
}
return result;
}
function integer(bytes: Uint8Array) {
return bytes.reduce((value, byte) => value * BigInt(256) + BigInt(byte), BigInt(0));
}
// Sample uniformly in the scalar field using rejection. Zero is a valid scalar.
function randomScalar() {
const bytes = new Uint8Array(32);
for (;;) {
crypto.getRandomValues(bytes);
bytes[0] &= 31;
const value = integer(bytes);
if (value < field.ORDER) return value;
}
}
function timesH(value: bigint) {
return value === BigInt(0) ? Point.ZERO : H.multiply(value);
}
function edgesFor(extra: boolean) {
return extra ? [...EDGES, EXTRA] : EDGES;
}
function predicates(commitments: Element[], edges: readonly Edge[]) {
return [
...commitments.map(point => ({ point, values: palette })),
...edges.map(([a, b]) => ({ point: commitments[a].subtract(commitments[b]), values: differences })),
];
}
function statement(commitments: Element[], edges: readonly Edge[]) {
const graph = Uint8Array.from([vertexCount, edges.length, ...edges.flat()]);
return join([domain, graph, ...commitments.map(point => point.toBytes())]);
}
async function challenge(context: Uint8Array, index: number, announcements: Element[]) {
const message = join([context, Uint8Array.of(index), ...announcements.map(a => a.toBytes())]);
return field.create(integer(new Uint8Array(await crypto.subtle.digest("SHA-512", message))));
}
// For a candidate opening v, Y = C - vG. Knowledge of log_H(Y)
// establishes an opening of C to v. Simulate all but the known branch.
function recover(point: Element, value: number, e: bigint, z: bigint) {
const publicKey = point.subtract(offsets.get(value)!);
return timesH(z).subtract(publicKey.multiplyUnsafe(e));
}
function encode(bytes: Uint8Array) {
return btoa(String.fromCharCode(...bytes)).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
}
export async function prove(colors: number[], extra: boolean): Promise<Certificate> {
const edges = edgesFor(extra);
if (typeof extra !== "boolean" || colors.length !== vertexCount ||
!Array.from(colors).every(c => palette.includes(c)) || edges.some(([a, b]) => colors[a] === colors[b])) {
throw new Error("Choose three colors so that every connected pair is different.");
}
const blinds = Array.from({ length: vertexCount }, randomScalar);
const commitments = colors.map((color, i) => offsets.get(color)!.add(timesH(blinds[i])));
const values = [...colors, ...edges.map(([a, b]) => colors[a] - colors[b])];
const openings = [...blinds, ...edges.map(([a, b]) => field.sub(blinds[a], blinds[b]))];
const context = statement(commitments, edges);
const payload = commitments.map(c => c.toBytes());
for (const [index, predicate] of predicates(commitments, edges).entries()) {
const known = predicate.values.indexOf(values[index]);
const nonce = randomScalar();
const challenges = predicate.values.map(() => randomScalar());
const responses = predicate.values.map(() => randomScalar());
const announcements = predicate.values.map((v, i) =>
i === known ? timesH(nonce) : recover(predicate.point, v, challenges[i], responses[i]));
challenges[known] = BigInt(0);
const total = await challenge(context, index, announcements);
challenges[known] = field.sub(total, challenges.reduce((sum, e) => field.add(sum, e), BigInt(0)));
responses[known] = field.add(nonce, field.mul(challenges[known], openings[index]));
challenges.forEach((e, i) => payload.push(field.toBytes(e), field.toBytes(responses[i])));
}
return { version: 1, extra, transcript: encode(join(payload)) };
}
export async function verify(proof: Certificate, extra: boolean): Promise<boolean> {
try {
if (typeof extra !== "boolean" || proof.version !== 1 || proof.extra !== extra || typeof proof.transcript !== "string") return false;
const edges = edgesFor(extra);
const size = vertexCount * 32 + (vertexCount * palette.length + edges.length * differences.length) * 64;
if (proof.transcript.length !== Math.ceil(size * 4 / 3)) return false;
const encoded = proof.transcript.replaceAll("-", "+").replaceAll("_", "/");
const bytes = Uint8Array.from(atob(encoded), character => character.charCodeAt(0));
if (bytes.length !== size || encode(bytes) !== proof.transcript) return false;
let offset = 0;
function next() {
const word = bytes.subarray(offset, offset + 32);
offset += 32;
return word;
}
function readScalar() {
const word = next();
const scalar = field.fromBytes(word);
if (!field.toBytes(scalar).every((byte, i) => word[i] === byte)) throw new Error("Noncanonical scalar");
return scalar;
}
const commitments = Array.from({ length: vertexCount }, () => Point.fromBytes(next()));
const context = statement(commitments, edges);
for (const [index, predicate] of predicates(commitments, edges).entries()) {
let sum = BigInt(0);
const announcements = predicate.values.map(value => {
const e = readScalar();
sum = field.add(sum, e);
return recover(predicate.point, value, e, readScalar());
});
if (sum !== await challenge(context, index, announcements)) return false;
}
return true;
} catch {
return false;
}
}