Source code for fleetmesh_core.crypto.zk

"""Pure-Python BN254 (alt_bn128) pairing cryptography and Groth16 verifier.

Implements pairing-friendly elliptic curve arithmetic over BN254 for off-chain
zero-knowledge proof verification without external C dependencies:
- Base field FQ (mod P)
- Quadratic extension FQ2 = FQ[u] / (u^2 + 1)
- Degree-12 extension FQ12 = FQ[w] / (w^12 - 18*w^6 + 82)
- G1 curve over FQ: y^2 = x^3 + 3
- G2 twist curve over FQ2: y^2 = x^3 + 3 / (9 + u)
- Optimal Ate pairing and multi-Miller loop
- Groth16 zk-SNARK verification conforming to compute:zk-verify-groth16/1.0

Portable (fleetmesh_core): a ZK receipt is part of the wire contract, so a
second implementation verifies exactly this. Pinned to vectors/groth16.json.
"""
from __future__ import annotations

import hashlib
import json
from typing import Any, Callable, Mapping, Optional, Sequence, TypedDict


[docs]class VerificationKeyDict(TypedDict): alpha: list[str] beta: list[list[str]] gamma: list[list[str]] delta: list[list[str]] ic: list[list[str]]
[docs]class Groth16JobResult(TypedDict): valid: bool pairing_count: int curve: str
# --------------------------------------------------------------------------- # BN254 Field & Group Parameters # --------------------------------------------------------------------------- P: int = 21888242871839275222246405745257275088696311157297823662689037894645226208583 R: int = 21888242871839275222246405745257275088548364400416034343698204186575808495617 ATE_LOOP_COUNT: int = 29793968203157093288 LOG_ATE_LOOP_COUNT: int = 63 PSEUDO_BINARY_ENCODING: list[int] = [ 0, 0, 0, 1, 0, 1, 0, -1, 0, 0, 1, -1, 0, 0, 1, 0, 0, 1, 1, 0, -1, 0, 0, 1, 0, -1, 0, 0, 0, 0, 1, 1, 1, 0, 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, -1, 0, 0, 1, 1, 0, 0, -1, 0, 0, 0, 1, 1, 0, -1, 0, 0, 1, 0, 1, 1 ]
[docs]def inv_mod(a: int, m: int = P) -> int: """Modular inverse via Fermat's little theorem.""" a = a % m if a == 0: return 0 return pow(a, m - 2, m)
def _deg(p: Sequence[int]) -> int: d = len(p) - 1 while p[d] == 0 and d: d -= 1 return d def _poly_rounded_div(a: Sequence[int], b: Sequence[int]) -> list[int]: dega = _deg(a) degb = _deg(b) temp = list(a) o = [0] * len(a) inv_b = inv_mod(b[degb], P) for i in range(dega - degb, -1, -1): o[i] = (temp[degb + i] * inv_b) % P for c in range(degb + 1): temp[c + i] = (temp[c + i] - o[c] * b[c]) % P return [x % P for x in o[: _deg(o) + 1]] # --------------------------------------------------------------------------- # Finite Fields # ---------------------------------------------------------------------------
[docs]class FQ: """Base field F_p.""" __slots__ = ('n',) field_modulus: int = P n: int
[docs] def __init__(self, val: Any) -> None: self.n = (val.n if isinstance(val, FQ) else int(val)) % P
def __add__(self, other: Any) -> FQ: on = other.n if isinstance(other, FQ) else (int(other) % P) return FQ((self.n + on) % P) def __sub__(self, other: Any) -> FQ: on = other.n if isinstance(other, FQ) else (int(other) % P) return FQ((self.n - on) % P) def __mul__(self, other: Any) -> FQ: on = other.n if isinstance(other, FQ) else (int(other) % P) return FQ((self.n * on) % P) def __neg__(self) -> FQ: return FQ(-self.n)
[docs] def inv(self) -> FQ: return FQ(inv_mod(self.n, P))
def __truediv__(self, other: Any) -> FQ: on = other.n if isinstance(other, FQ) else int(other) return FQ((self.n * inv_mod(on, P)) % P) def __pow__(self, exp: int) -> FQ: return FQ(pow(self.n, exp, P)) def __eq__(self, other: Any) -> bool: if isinstance(other, FQ): return self.n == other.n if isinstance(other, int): return self.n == (other % P) return False
[docs] def is_zero(self) -> bool: return self.n == 0
[docs] @classmethod def one(cls) -> FQ: return cls(1)
[docs] @classmethod def zero(cls) -> FQ: return cls(0)
def __repr__(self) -> str: return f"FQ({self.n})"
[docs]class FQ2: """Quadratic extension field F_p[u] / (u^2 + 1).""" __slots__ = ('c0', 'c1') field_modulus: int = P
[docs] def __init__(self, c0: Any, c1: Any = 0) -> None: self.c0 = (c0.n if isinstance(c0, FQ) else int(c0)) % P self.c1 = (c1.n if isinstance(c1, FQ) else int(c1)) % P
def __add__(self, other: Any) -> FQ2: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) return FQ2(self.c0 + on, self.c1) return FQ2(self.c0 + other.c0, self.c1 + other.c1) def __sub__(self, other: Any) -> FQ2: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) return FQ2(self.c0 - on, self.c1) return FQ2(self.c0 - other.c0, self.c1 - other.c1) def __mul__(self, other: Any) -> FQ2: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) return FQ2(self.c0 * on, self.c1 * on) return FQ2( self.c0 * other.c0 - self.c1 * other.c1, self.c0 * other.c1 + self.c1 * other.c0 ) def __neg__(self) -> FQ2: return FQ2(-self.c0, -self.c1)
[docs] def inv(self) -> FQ2: denom = (self.c0 * self.c0 + self.c1 * self.c1) % P inv_d = inv_mod(denom, P) return FQ2(self.c0 * inv_d, -self.c1 * inv_d)
def __truediv__(self, other: Any) -> FQ2: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) inv_o = inv_mod(on, P) return FQ2(self.c0 * inv_o, self.c1 * inv_o) return self * other.inv() def __eq__(self, other: Any) -> bool: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) return self.c0 == (on % P) and self.c1 == 0 if isinstance(other, FQ2): return self.c0 == other.c0 and self.c1 == other.c1 return False
[docs] def is_zero(self) -> bool: return self.c0 == 0 and self.c1 == 0
[docs] @classmethod def one(cls) -> FQ2: return cls(1, 0)
[docs] @classmethod def zero(cls) -> FQ2: return cls(0, 0)
def __repr__(self) -> str: return f"FQ2([{self.c0}, {self.c1}])"
[docs]class FQ12: """Degree-12 extension field F_p[w] / (w^12 - 18*w^6 + 82).""" __slots__ = ('coeffs',) field_modulus: int = P degree: int = 12 modulus_coeffs: tuple[int, ...] = (82, 0, 0, 0, 0, 0, -18, 0, 0, 0, 0, 0)
[docs] def __init__(self, coeffs: Sequence[Any] | int | FQ) -> None: if isinstance(coeffs, (list, tuple)): c_ints = tuple(int(c.n if isinstance(c, FQ) else c) % P for c in coeffs) if len(c_ints) < 12: self.coeffs = c_ints + (0,) * (12 - len(c_ints)) elif len(c_ints) > 12: self.coeffs = c_ints[:12] else: self.coeffs = c_ints elif isinstance(coeffs, (int, FQ)): cn = coeffs.n if isinstance(coeffs, FQ) else int(coeffs) self.coeffs = (cn % P,) + (0,) * 11 else: self.coeffs = (0,) * 12
[docs] @classmethod def one(cls) -> FQ12: return cls((1,) + (0,) * 11)
[docs] @classmethod def zero(cls) -> FQ12: return cls((0,) * 12)
[docs] def is_zero(self) -> bool: return all(c == 0 for c in self.coeffs)
def __add__(self, other: Any) -> FQ12: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) r = list(self.coeffs) r[0] = (r[0] + on) % P return FQ12(r) return FQ12([(a + b) % P for a, b in zip(self.coeffs, other.coeffs)]) def __sub__(self, other: Any) -> FQ12: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) r = list(self.coeffs) r[0] = (r[0] - on) % P return FQ12(r) return FQ12([(a - b) % P for a, b in zip(self.coeffs, other.coeffs)]) def __neg__(self) -> FQ12: return FQ12([(-c) % P for c in self.coeffs]) def __mul__(self, other: Any) -> FQ12: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) return FQ12([(c * on) % P for c in self.coeffs]) # Polynomial multiplication b = [0] * 23 sc = self.coeffs oc = other.coeffs for i in range(12): si = sc[i] if not si: continue for j in range(12): oj = oc[j] if oj: b[i + j] += si * oj # Modulo reduction mod X^12 - 18*X^6 + 82 for exp in range(10, -1, -1): top = b.pop() if top: b[exp + 0] = (b[exp + 0] - top * 82) % P b[exp + 6] = (b[exp + 6] + top * 18) % P return FQ12([x % P for x in b])
[docs] def inv(self) -> FQ12: lm = [1] + [0] * 12 hm = [0] * 13 low = list(self.coeffs) + [0] high = list(self.modulus_coeffs) + [1] while _deg(low): r = _poly_rounded_div(high, low) r += [0] * (13 - len(r)) nm = list(hm) new = list(high) for i in range(13): ri = r[i] if not ri: continue for j in range(13 - i): nm[i + j] = (nm[i + j] - lm[j] * ri) % P new[i + j] = (new[i + j] - low[j] * ri) % P lm, low, hm, high = nm, new, lm, low inv_low0 = inv_mod(low[0], P) return FQ12([(c * inv_low0) % P for c in lm[:12]])
def __truediv__(self, other: Any) -> FQ12: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) return self * inv_mod(on, P) return self * other.inv() def __pow__(self, exp: int) -> FQ12: res = FQ12.one() base = self while exp > 0: if exp & 1: res = res * base base = base * base exp >>= 1 return res def __eq__(self, other: Any) -> bool: if isinstance(other, (int, FQ)): on = other.n if isinstance(other, FQ) else int(other) return self.coeffs[0] == (on % P) and all(c == 0 for c in self.coeffs[1:]) if isinstance(other, FQ12): return self.coeffs == other.coeffs return False def __repr__(self) -> str: return f"FQ12({list(self.coeffs)})"
# Generator helpers for FQ12 W: FQ12 = FQ12([0, 1] + [0] * 10) W2: FQ12 = W * W W3: FQ12 = W2 * W # Curve equation parameters: y^2 = x^3 + b B: FQ = FQ(3) B2: FQ2 = FQ2(3, 0) / FQ2(9, 1) # Canonical generators in projective (x, y, z) G1_AFFINE: tuple[int, int] = (1, 2) G1: tuple[FQ, FQ, FQ] = (FQ(1), FQ(2), FQ(1)) G2: tuple[FQ2, FQ2, FQ2] = ( FQ2(10857046999023057135944570762232829481370756359578518086990519993285655852781, 11559732032986387107991004021392285783925812861821192530917403151452391805634), FQ2(8495653923123431417604973247489272438418190587263600148770280649306958101930, 4082367875863433681332203403145435568316851327593401208105741076214120093531), FQ2.one() ) # --------------------------------------------------------------------------- # Projective Elliptic Curve Arithmetic # ---------------------------------------------------------------------------
[docs]def double_pt(pt: tuple[Any, Any, Any]) -> tuple[Any, Any, Any]: """Homogeneous projective point doubling.""" x, y, z = pt if y.is_zero(): return (x.one(), x.one(), x.zero()) w = x * x * 3 s = y * z b = x * y * s h = w * w - b * 8 s_sq = s * s newx = h * s * 2 newy = w * (b * 4 - h) - y * y * s_sq * 8 newz = s * s_sq * 8 return (newx, newy, newz)
[docs]def add_pt(p1: tuple[Any, Any, Any], p2: tuple[Any, Any, Any]) -> tuple[Any, Any, Any]: """Homogeneous projective point addition.""" one, zero = p1[0].one(), p1[0].zero() if p1[2].is_zero() or p2[2].is_zero(): return p1 if p2[2].is_zero() else p2 x1, y1, z1 = p1 x2, y2, z2 = p2 u1 = y2 * z1 u2 = y1 * z2 v1 = x2 * z1 v2 = x1 * z2 if v1 == v2 and u1 == u2: return double_pt(p1) elif v1 == v2: return (one, one, zero) u = u1 - u2 v = v1 - v2 v_sq = v * v v_sq_v2 = v_sq * v2 v_cubed = v * v_sq w = z1 * z2 a = u * u * w - v_cubed - v_sq_v2 * 2 newx = v * a newy = u * (v_sq_v2 - a) - v_cubed * u2 newz = v_cubed * w return (newx, newy, newz)
[docs]def mul_pt(pt: tuple[Any, Any, Any], n: int) -> tuple[Any, Any, Any]: """Scalar multiplication via double-and-add.""" if n == 0 or pt[2].is_zero(): return (pt[0].one(), pt[0].one(), pt[0].zero()) res = (pt[0].one(), pt[0].one(), pt[0].zero()) cur = pt while n > 0: if n & 1: res = add_pt(res, cur) cur = double_pt(cur) n >>= 1 return res
[docs]def neg_g12(pt: tuple[FQ12, FQ12, FQ12]) -> tuple[FQ12, FQ12, FQ12]: return (pt[0], -pt[1], pt[2])
[docs]def to_affine(pt: tuple[Any, Any, Any]) -> Optional[tuple[Any, Any]]: x, y, z = pt if z.is_zero(): return None inv_z = z.inv() return (x * inv_z, y * inv_z)
[docs]def normalize_pt(pt: tuple[Any, Any, Any]) -> tuple[Any, Any, Any]: """Normalize a projective point to affine with Z=1.""" if pt[2].is_zero(): return (pt[0].one(), pt[0].one(), pt[0].zero()) inv_z = pt[2].inv() return (pt[0] * inv_z, pt[1] * inv_z, pt[2].one())
[docs]def eq_pt(p1: tuple[Any, Any, Any], p2: tuple[Any, Any, Any]) -> bool: """Check projective point equivalence: P1 == P2.""" if p1[2].is_zero(): return p2[2].is_zero() if p2[2].is_zero(): return False return (p1[0] * p2[2] == p2[0] * p1[2]) and (p1[1] * p2[2] == p2[1] * p1[2])
# Aliases double_g1 = double_pt add_g1 = add_pt mul_g1 = mul_pt double_g2 = double_pt add_g2 = add_pt mul_g2 = mul_pt double_g12 = double_pt add_g12 = add_pt # --------------------------------------------------------------------------- # Pairing & Miller Loop # ---------------------------------------------------------------------------
[docs]def twist(pt: tuple[FQ2, FQ2, FQ2]) -> tuple[FQ12, FQ12, FQ12]: """Twist isomorphism mapping G2 from FQ2 into FQ12.""" x, y, z = pt if z.is_zero(): return (FQ12.zero(), FQ12.one(), FQ12.zero()) xc0 = (x.c0 - x.c1 * 9) % P yc0 = (y.c0 - y.c1 * 9) % P nx = FQ12((xc0,) + (0,) * 5 + (x.c1,) + (0,) * 5) ny = FQ12((yc0,) + (0,) * 5 + (y.c1,) + (0,) * 5) nz = FQ12((z.c0 - z.c1 * 9,) + (0,) * 5 + (z.c1,) + (0,) * 5) return (nx * W2, ny * W3, nz)
[docs]def cast_to_fq12(pt: tuple[FQ, FQ, FQ]) -> tuple[FQ12, FQ12, FQ12]: """Cast point in G1 from FQ into FQ12.""" x, y, z = pt return (FQ12(x), FQ12(y), FQ12(z))
[docs]def linefunc( p1: tuple[FQ12, FQ12, FQ12], p2: tuple[FQ12, FQ12, FQ12], t: tuple[FQ12, FQ12, FQ12] ) -> tuple[FQ12, FQ12]: """Evaluate line between P1 and P2 at point T in projective coords.""" x1, y1, z1 = p1 x2, y2, z2 = p2 xt, yt, zt = t m_num = y2 * z1 - y1 * z2 m_den = x2 * z1 - x1 * z2 if not m_den.is_zero(): return ( m_num * (xt * z1 - x1 * zt) - m_den * (yt * z1 - y1 * zt), m_den * zt * z1 ) elif m_num.is_zero(): m_num = x1 * x1 * 3 m_den = y1 * z1 * 2 return ( m_num * (xt * z1 - x1 * zt) - m_den * (yt * z1 - y1 * zt), m_den * zt * z1 ) else: return (xt * z1 - x1 * zt, z1 * zt)
[docs]def multi_miller_loop(pairs: Sequence[tuple[tuple[FQ12, FQ12, FQ12], tuple[FQ12, FQ12, FQ12]]]) -> FQ12: """Accumulated multi-Miller loop over multiple G2/G1 pairs.""" r_pts = [p[0] for p in pairs] p_pts = [p[1] for p in pairs] q_pts = list(r_pts) n_pairs = len(pairs) f_num, f_den = FQ12.one(), FQ12.one() for v in PSEUDO_BINARY_ENCODING[63::-1]: f_num = f_num * f_num f_den = f_den * f_den for k in range(n_pairs): n, d = linefunc(r_pts[k], r_pts[k], p_pts[k]) f_num = f_num * n f_den = f_den * d r_pts[k] = double_g12(r_pts[k]) if v == 1: for k in range(n_pairs): n, d = linefunc(r_pts[k], q_pts[k], p_pts[k]) f_num = f_num * n f_den = f_den * d r_pts[k] = add_g12(r_pts[k], q_pts[k]) elif v == -1: for k in range(n_pairs): nq = neg_g12(q_pts[k]) n, d = linefunc(r_pts[k], nq, p_pts[k]) f_num = f_num * n f_den = f_den * d r_pts[k] = add_g12(r_pts[k], nq) for k in range(n_pairs): q1 = (q_pts[k][0] ** P, q_pts[k][1] ** P, q_pts[k][2] ** P) nq2 = (q1[0] ** P, -q1[1] ** P, q1[2] ** P) n1, d1 = linefunc(r_pts[k], q1, p_pts[k]) r_pts[k] = add_g12(r_pts[k], q1) n2, d2 = linefunc(r_pts[k], nq2, p_pts[k]) f_num = f_num * n1 * n2 f_den = f_den * d1 * d2 return f_num / f_den
[docs]def final_exponentiate(f: FQ12) -> FQ12: """Final exponentiation f^((P^12 - 1) / R).""" return f ** ((P**12 - 1) // R)
# --------------------------------------------------------------------------- # Pairing & Groth16 Acceleration Hooks # --------------------------------------------------------------------------- _ACCELERATED_PAIRING_FN: Optional[Callable[[Sequence[tuple[tuple[FQ2, FQ2, FQ2], tuple[FQ, FQ, FQ]]]], FQ12]] = None _ACCELERATED_GROTH16_FN: Optional[Callable[[VerificationKey, Sequence[Any], Mapping[str, Any]], bool]] = None
[docs]def set_pairing_accelerator(fn: Optional[Callable[..., FQ12]]) -> None: """Register native/accelerated multi-pairing backend function.""" global _ACCELERATED_PAIRING_FN _ACCELERATED_PAIRING_FN = fn
[docs]def set_groth16_accelerator(fn: Optional[Callable[[VerificationKey, Sequence[Any], Mapping[str, Any]], bool]]) -> None: """Register native/accelerated Groth16 verification backend function.""" global _ACCELERATED_GROTH16_FN _ACCELERATED_GROTH16_FN = fn
[docs]def is_pairing_accelerated() -> bool: """Check if an accelerated multi-pairing backend is currently active.""" return _ACCELERATED_PAIRING_FN is not None
[docs]def is_groth16_accelerated() -> bool: """Check if an accelerated Groth16 verifier backend is currently active.""" return _ACCELERATED_GROTH16_FN is not None
[docs]def multi_pairing(pairs: Sequence[tuple[tuple[FQ2, FQ2, FQ2], tuple[FQ, FQ, FQ]]]) -> FQ12: """Evaluate product of pairings: prod_k e(Q_k, P_k).""" if _ACCELERATED_PAIRING_FN is not None: try: return _ACCELERATED_PAIRING_FN(pairs) except (ValueError, ZeroDivisionError, KeyError, IndexError, TypeError): pass twisted_pairs = [(twist(q), cast_to_fq12(p)) for q, p in pairs] ml = multi_miller_loop(twisted_pairs) return final_exponentiate(ml)
[docs]def pairing(q: tuple[FQ2, FQ2, FQ2], p: tuple[FQ, FQ, FQ]) -> FQ12: """Single Ate pairing e(Q, P).""" return multi_pairing([(q, p)])
# --------------------------------------------------------------------------- # Point Serialization & Parsing (Hex Strings) # ---------------------------------------------------------------------------
[docs]def parse_scalar(hex_str: str) -> int: """Parse 0x-prefixed hex string into integer modulo R.""" val = int(hex_str, 16) if hex_str.startswith(('0x', '0X')) else int(hex_str, 16) if val < 0 or val >= R: raise ValueError(f'scalar out of field range: {val}') return val
[docs]def parse_g1(pt_coords: Sequence[str]) -> tuple[FQ, FQ, FQ]: """Parse [x_hex, y_hex] into projective G1 point.""" if len(pt_coords) < 2: raise ValueError("G1 point requires [x, y]") x = int(pt_coords[0], 16) y = int(pt_coords[1], 16) return (FQ(x), FQ(y), FQ(1))
[docs]def parse_g2(pt_coords: Sequence[Sequence[str]]) -> tuple[FQ2, FQ2, FQ2]: """Parse [[x0, x1], [y0, y1]] into projective G2 point.""" if len(pt_coords) < 2 or len(pt_coords[0]) < 2 or len(pt_coords[1]) < 2: raise ValueError("G2 point requires [[x0, x1], [y0, y1]]") x0 = int(pt_coords[0][0], 16) x1 = int(pt_coords[0][1], 16) y0 = int(pt_coords[1][0], 16) y1 = int(pt_coords[1][1], 16) return (FQ2(x0, x1), FQ2(y0, y1), FQ2.one())
[docs]def format_hex32(val: int) -> str: """Format scalar as 0x-prefixed 64-hex string.""" return '0x' + f"{val:064x}"
# --------------------------------------------------------------------------- # Verification Key Registry & Groth16 Verifier # ---------------------------------------------------------------------------
[docs]class VerificationKey: """Represents a Groth16 verification key circuit."""
[docs] def __init__( self, alpha: tuple[FQ, FQ, FQ], beta: tuple[FQ2, FQ2, FQ2], gamma: tuple[FQ2, FQ2, FQ2], delta: tuple[FQ2, FQ2, FQ2], ic: Sequence[tuple[FQ, FQ, FQ]], ) -> None: self.alpha = normalize_pt(alpha) self.beta = normalize_pt(beta) self.gamma = normalize_pt(gamma) self.delta = normalize_pt(delta) self.ic = [normalize_pt(p) for p in ic]
[docs] @classmethod def from_dict(cls, data: Mapping[str, Any]) -> VerificationKey: alpha = parse_g1(data['alpha']) beta = parse_g2(data['beta']) gamma = parse_g2(data['gamma']) delta = parse_g2(data['delta']) ic = [parse_g1(p) for p in data['ic']] return cls(alpha=alpha, beta=beta, gamma=gamma, delta=delta, ic=ic)
[docs] def to_dict(self) -> VerificationKeyDict: """Convert verification key elements to serializable dictionary.""" return { 'alpha': [format_hex32(self.alpha[0].n), format_hex32(self.alpha[1].n)], 'beta': [ [format_hex32(self.beta[0].c0), format_hex32(self.beta[0].c1)], [format_hex32(self.beta[1].c0), format_hex32(self.beta[1].c1)], ], 'gamma': [ [format_hex32(self.gamma[0].c0), format_hex32(self.gamma[0].c1)], [format_hex32(self.gamma[1].c0), format_hex32(self.gamma[1].c1)], ], 'delta': [ [format_hex32(self.delta[0].c0), format_hex32(self.delta[0].c1)], [format_hex32(self.delta[1].c0), format_hex32(self.delta[1].c1)], ], 'ic': [[format_hex32(p[0].n), format_hex32(p[1].n)] for p in self.ic], }
[docs] def digest(self) -> str: """Compute SHA-256 canonical digest of verification key elements.""" canon = json.dumps({ 'alpha': [str(self.alpha[0].n), str(self.alpha[1].n)], 'beta': [[str(self.beta[0].c0), str(self.beta[0].c1)], [str(self.beta[1].c0), str(self.beta[1].c1)]], 'gamma': [[str(self.gamma[0].c0), str(self.gamma[0].c1)], [str(self.gamma[1].c0), str(self.gamma[1].c1)]], 'delta': [[str(self.delta[0].c0), str(self.delta[0].c1)], [str(self.delta[1].c0), str(self.delta[1].c1)]], 'ic': [[str(p[0].n), str(p[1].n)] for p in self.ic], }, sort_keys=True) return hashlib.sha256(canon.encode('utf-8')).hexdigest()
# Known registered verification keys VK_REGISTRY: dict[str, VerificationKey] = {}
[docs]def register_verification_key(vk: VerificationKey) -> str: h = vk.digest() VK_REGISTRY[h] = vk return h
[docs]def is_on_curve_g1(pt: tuple[FQ, FQ, FQ]) -> bool: """y^2 == x^3 + 3 in affine coordinates; the point at infinity counts.""" aff = to_affine(pt) if aff is None: return True x, y = aff return y * y == x * x * x + B
[docs]def is_on_curve_g2(pt: tuple[FQ2, FQ2, FQ2]) -> bool: """y^2 == x^3 + b/xi on the twist; the point at infinity counts.""" aff = to_affine(pt) if aff is None: return True x, y = aff return y * y == x * x * x + B2
[docs]def in_g2_subgroup(pt: tuple[FQ2, FQ2, FQ2]) -> bool: """[r]Q == O. BN254's G1 has prime order r so on-curve is enough there, but the twist has a large cofactor: a point outside G2 satisfies the curve equation yet breaks the pairing's bilinearity assumptions, and a prover can use one to smuggle a proof that verifies for the wrong statement. One scalar multiplication costs far less than a pairing.""" return mul_pt(pt, R)[2].is_zero()
[docs]def verify_groth16( vk: VerificationKey, public_inputs: Sequence[str | int], proof: Mapping[str, Any] ) -> bool: """Verify a Groth16 proof against public inputs and verification key. Evaluates the 4-pairing equation: e(-A, B) * e(alpha, beta) * e(vk_x, gamma) * e(C, delta) == 1 where vk_x = IC[0] + sum_i (x_i * IC[i+1]). Malformed input (unparseable coordinates, points off the curve or, for B, outside G2) is an invalid proof, never an exception: the caller is settling a payment on this answer and must not confuse a prover's garbage with its own failure. """ if _ACCELERATED_GROTH16_FN is not None: try: return _ACCELERATED_GROTH16_FN(vk, public_inputs, proof) except (ValueError, ZeroDivisionError, KeyError, IndexError, TypeError): pass if len(public_inputs) + 1 != len(vk.ic): return False try: a_pt = parse_g1(proof['a']) b_pt = parse_g2(proof['b']) c_pt = parse_g1(proof['c']) except (KeyError, TypeError, ValueError, IndexError): return False if not (is_on_curve_g1(a_pt) and is_on_curve_g1(c_pt) and is_on_curve_g2(b_pt)): return False if not in_g2_subgroup(b_pt): return False # Compute vk_x = IC[0] + sum(inputs[i] * IC[i+1]) vk_x = vk.ic[0] try: for i, s_val in enumerate(public_inputs): scalar = parse_scalar(str(s_val)) term = mul_g1(vk.ic[i + 1], scalar) vk_x = add_g1(vk_x, term) except (TypeError, ValueError): return False neg_a = (a_pt[0], -a_pt[1], a_pt[2]) pairs = [ (b_pt, neg_a), (vk.beta, vk.alpha), (vk.gamma, vk_x), (vk.delta, c_pt), ] try: check = multi_pairing(pairs) return check == FQ12.one() except (ValueError, ZeroDivisionError, KeyError, IndexError, TypeError): return False
[docs]def verify_groth16_job( job_input: Mapping[str, Any], custom_vk: Optional[VerificationKey] = None ) -> Groth16JobResult: """Execute a compute:zk-verify-groth16/1.0 job and return schema-valid output.""" curve = job_input.get('curve', 'bn254') if curve != 'bn254': raise ValueError(f"Unsupported curve: {curve}") vk_sha = job_input.get('vk_sha256', '') vk = custom_vk or VK_REGISTRY.get(vk_sha) if not vk: raise ValueError(f"Verification key not found for digest: {vk_sha}") public_inputs = job_input.get('public_inputs', []) proof = job_input.get('proof', {}) is_valid = verify_groth16(vk, public_inputs, proof) return { 'valid': bool(is_valid), 'pairing_count': 4, 'curve': 'bn254', }