Republished from a clean root: the compiled artifact is gone from history, and the local line of work joins the sanitized public line
The public history carried kat/__pycache__/mlkem768_reference.cpython-314.pyc, a compiled Python artifact embedding the operator's absolute local path. Text secret scanners do not read compiled binaries, which is exactly how it slipped through, and removing it from the tip would have left it reachable through the old root commits. So this repository is republished from a single clean root. This root also carries, from the previously unpublished line of work: - corrected LICENSE year, LICENSING.md, VERIFY-POLICY.md, and CITATIONS-UNRESOLVED.md remeasured 2026-08-11 (101 paths, README aligned) - O-018: run_consensus_verification.py ran 19 of 29 models and reported PASS; it now runs all 29, and computemarket_smt.py gains resolveByTimeout / reclaimUnsettled cases plus a negative control - O-006: the word 'audited' removed from next to Bouncy Castle, twice, after a concurrent edit resurrected it - O-014: prior art named and dated - Algorand's native falcon_verify shipped about ten months before AERE's precompiles; the primacy claim is withdrawn where it was implied - bench/ scripts parametrized so they actually run for an outsider (the earlier textual sanitization left $STAGING unexpanded inside Python strings) - AIP-2/AIP-3 errata with measured figures, spec remeasurements at 2026-08-01, and the spec-zk-stack retractions (owner is an operational key, not the Foundation; 'maximally sound' withdrawn; aggregator V1 deprecated) The redacted bench-host environment files from the sanitized line are kept exactly as published; the unredacted local variants are not carried.
This commit is contained in:
commit
6cb0140fae
177 files changed
+33777
No files matched your search
@@ -0,0 +1,479 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
pragma solidity 0.8.23;
|
||||
|
||||
/**
|
||||
* @title AereFalcon512Verifier, spec-complete NIST Falcon-512 signature verifier, on-chain
|
||||
* @notice A REAL, standalone Falcon-512 (FIPS 206 / NIST PQC round-3) signature
|
||||
* verifier that runs entirely on chain 2800. Given a public key, a
|
||||
* message, and a signature, it performs the full Falcon verification:
|
||||
*
|
||||
* 1. HashToPoint: SHAKE256(nonce || message) is streamed and
|
||||
* rejection-sampled into a challenge polynomial c in Z_q[x]/(x^512+1)
|
||||
* (q = 12289), exactly per the reference hash_to_point_vartime.
|
||||
* 2. Public-key decode: the 897-byte NIST public key (0x09 header + 512
|
||||
* coefficients packed at 14 bits each) is decoded to h.
|
||||
* 3. Signature decode: the compressed Gaussian encoding of s2 is decoded
|
||||
* (Falcon comp_decode: sign bit, 7 low bits, unary high bits).
|
||||
* 4. Recompute -s1 = s2*h - c in the ring (negacyclic convolution mod q),
|
||||
* then center coefficients into (-q/2, q/2].
|
||||
* 5. Norm check: accept iff ||(s1, s2)||^2 <= floor(beta^2) = 34034726,
|
||||
* the Falcon-512 acceptance bound.
|
||||
*
|
||||
* This is the actual lattice/hash cryptography, executed on-chain, not a
|
||||
* proof-of-a-proof. It is validated bit-for-bit against the OFFICIAL NIST
|
||||
* Falcon-512 Known-Answer-Test vectors (falcon512-KAT.rsp, SHA-256
|
||||
* dd75c946...b5cd, reproduced byte-for-byte from the round-3 reference):
|
||||
* real (pk, message, signature) triples verify true; tampered signatures
|
||||
* verify false.
|
||||
*
|
||||
* The chain's block gas limit is effectively unlimited, so the full
|
||||
* verification runs as an ordinary transaction; there is no trusted
|
||||
* prover and no off-chain step. Anyone can call verify() and get the same
|
||||
* accept/reject the reference C implementation produces.
|
||||
*/
|
||||
contract AereFalcon512VerifierHTP {
|
||||
// ----- Falcon-512 parameters -----
|
||||
uint256 public constant Q = 12289; // modulus
|
||||
uint256 public constant N = 512; // ring degree
|
||||
uint256 public constant L2BOUND = 34034726; // floor(beta^2), Falcon-512 acceptance bound
|
||||
uint256 internal constant HQ = 6144; // floor(q/2), centering threshold
|
||||
|
||||
// Negacyclic NTT constants for Z_q[x]/(x^512+1), q = 12289:
|
||||
// PSI = primitive 1024th (2n-th) root of unity; W = PSI^2 (512th root)
|
||||
uint256 internal constant PSI = 49;
|
||||
uint256 internal constant PSI_INV = 1254;
|
||||
uint256 internal constant W = 2401; // PSI^2 mod q
|
||||
uint256 internal constant W_INV = 11813;
|
||||
uint256 internal constant N_INV = 12265; // 512^-1 mod q
|
||||
uint8 public constant PK_HEADER = 0x09; // 0x00 + logn, logn = 9
|
||||
uint8 public constant SIG_HEADER = 0x29; // 0x20 + logn, logn = 9 (NIST esig header)
|
||||
uint256 public constant NONCE_LEN = 40;
|
||||
|
||||
// ----- recorded on-chain verification results (for state-changing calls) -----
|
||||
uint256 public verifyCount;
|
||||
bool public lastResult;
|
||||
event Verified(address indexed caller, bool result, uint256 index);
|
||||
|
||||
// ==========================================================================
|
||||
// Keccak-f[1600] / SHAKE256
|
||||
// ==========================================================================
|
||||
|
||||
/// @dev In-place Keccak-f[1600] permutation on a 25-lane state (one lane per
|
||||
/// 32-byte memory word, low 64 bits used). Written in assembly for gas:
|
||||
/// the naive array version cost ~1.26M gas per permutation. Validated
|
||||
/// against the FIPS 202 SHAKE256 KAT and the Falcon HashToPoint oracle.
|
||||
function _keccakf(uint64[25] memory st) internal view {
|
||||
assembly {
|
||||
function rol(x, n) -> r {
|
||||
r := and(0xffffffffffffffff, or(shl(n, x), shr(sub(64, n), x)))
|
||||
}
|
||||
let s := st
|
||||
let b := mload(0x40) // scratch (25 lanes), left above the free pointer
|
||||
let rc := add(b, 0x320) // 24 round constants after the scratch lanes
|
||||
// round constants
|
||||
mstore(add(rc, 0x000), 0x0000000000000001) mstore(add(rc, 0x020), 0x0000000000008082)
|
||||
mstore(add(rc, 0x040), 0x800000000000808a) mstore(add(rc, 0x060), 0x8000000080008000)
|
||||
mstore(add(rc, 0x080), 0x000000000000808b) mstore(add(rc, 0x0a0), 0x0000000080000001)
|
||||
mstore(add(rc, 0x0c0), 0x8000000080008081) mstore(add(rc, 0x0e0), 0x8000000000008009)
|
||||
mstore(add(rc, 0x100), 0x000000000000008a) mstore(add(rc, 0x120), 0x0000000000000088)
|
||||
mstore(add(rc, 0x140), 0x0000000080008009) mstore(add(rc, 0x160), 0x000000008000000a)
|
||||
mstore(add(rc, 0x180), 0x000000008000808b) mstore(add(rc, 0x1a0), 0x800000000000008b)
|
||||
mstore(add(rc, 0x1c0), 0x8000000000008089) mstore(add(rc, 0x1e0), 0x8000000000008003)
|
||||
mstore(add(rc, 0x200), 0x8000000000008002) mstore(add(rc, 0x220), 0x8000000000000080)
|
||||
mstore(add(rc, 0x240), 0x000000000000800a) mstore(add(rc, 0x260), 0x800000008000000a)
|
||||
mstore(add(rc, 0x280), 0x8000000080008081) mstore(add(rc, 0x2a0), 0x8000000000008080)
|
||||
mstore(add(rc, 0x2c0), 0x0000000080000001) mstore(add(rc, 0x2e0), 0x8000000080008008)
|
||||
|
||||
for { let rnd := 0 } lt(rnd, 24) { rnd := add(rnd, 1) } {
|
||||
// ---- theta: column parities C[x] -> b[0..4] ----
|
||||
for { let x := 0 } lt(x, 5) { x := add(x, 1) } {
|
||||
let o := mul(x, 0x20)
|
||||
mstore(add(b, o),
|
||||
xor(xor(xor(xor(
|
||||
mload(add(s, o)),
|
||||
mload(add(s, add(o, 0xa0)))),
|
||||
mload(add(s, add(o, 0x140)))),
|
||||
mload(add(s, add(o, 0x1e0)))),
|
||||
mload(add(s, add(o, 0x280)))))
|
||||
}
|
||||
// D[x] = C[(x+4)%5] ^ rol(C[(x+1)%5],1) -> b[5..9]
|
||||
for { let x := 0 } lt(x, 5) { x := add(x, 1) } {
|
||||
let cm := mload(add(b, mul(mod(add(x, 4), 5), 0x20)))
|
||||
let cp := mload(add(b, mul(mod(add(x, 1), 5), 0x20)))
|
||||
mstore(add(b, add(0xa0, mul(x, 0x20))), xor(cm, rol(cp, 1)))
|
||||
}
|
||||
// apply D to state: lane (x + 5y) ^= D[x]
|
||||
for { let x := 0 } lt(x, 5) { x := add(x, 1) } {
|
||||
let d := mload(add(b, add(0xa0, mul(x, 0x20))))
|
||||
let o := mul(x, 0x20)
|
||||
mstore(add(s, o), xor(mload(add(s, o)), d))
|
||||
mstore(add(s, add(o, 0xa0)), xor(mload(add(s, add(o, 0xa0))), d))
|
||||
mstore(add(s, add(o, 0x140)), xor(mload(add(s, add(o, 0x140))), d))
|
||||
mstore(add(s, add(o, 0x1e0)), xor(mload(add(s, add(o, 0x1e0))), d))
|
||||
mstore(add(s, add(o, 0x280)), xor(mload(add(s, add(o, 0x280))), d))
|
||||
}
|
||||
// ---- rho + pi: b[piDest[i]] = rol(st[i], rho[i]) ----
|
||||
mstore(add(b, 0x000), rol(mload(add(s, 0x000)), 0))
|
||||
mstore(add(b, 0x140), rol(mload(add(s, 0x020)), 1))
|
||||
mstore(add(b, 0x280), rol(mload(add(s, 0x040)), 62))
|
||||
mstore(add(b, 0x0a0), rol(mload(add(s, 0x060)), 28))
|
||||
mstore(add(b, 0x1e0), rol(mload(add(s, 0x080)), 27))
|
||||
mstore(add(b, 0x200), rol(mload(add(s, 0x0a0)), 36))
|
||||
mstore(add(b, 0x020), rol(mload(add(s, 0x0c0)), 44))
|
||||
mstore(add(b, 0x160), rol(mload(add(s, 0x0e0)), 6))
|
||||
mstore(add(b, 0x2a0), rol(mload(add(s, 0x100)), 55))
|
||||
mstore(add(b, 0x0c0), rol(mload(add(s, 0x120)), 20))
|
||||
mstore(add(b, 0x0e0), rol(mload(add(s, 0x140)), 3))
|
||||
mstore(add(b, 0x220), rol(mload(add(s, 0x160)), 10))
|
||||
mstore(add(b, 0x040), rol(mload(add(s, 0x180)), 43))
|
||||
mstore(add(b, 0x180), rol(mload(add(s, 0x1a0)), 25))
|
||||
mstore(add(b, 0x2c0), rol(mload(add(s, 0x1c0)), 39))
|
||||
mstore(add(b, 0x2e0), rol(mload(add(s, 0x1e0)), 41))
|
||||
mstore(add(b, 0x100), rol(mload(add(s, 0x200)), 45))
|
||||
mstore(add(b, 0x240), rol(mload(add(s, 0x220)), 15))
|
||||
mstore(add(b, 0x060), rol(mload(add(s, 0x240)), 21))
|
||||
mstore(add(b, 0x1a0), rol(mload(add(s, 0x260)), 8))
|
||||
mstore(add(b, 0x1c0), rol(mload(add(s, 0x280)), 18))
|
||||
mstore(add(b, 0x300), rol(mload(add(s, 0x2a0)), 2))
|
||||
mstore(add(b, 0x120), rol(mload(add(s, 0x2c0)), 61))
|
||||
mstore(add(b, 0x260), rol(mload(add(s, 0x2e0)), 56))
|
||||
mstore(add(b, 0x080), rol(mload(add(s, 0x300)), 14))
|
||||
// ---- chi: st[y+x] = b[y+x] ^ ((~b[y+(x+1)%5]) & b[y+(x+2)%5]) ----
|
||||
for { let yo := 0 } lt(yo, 0x320) { yo := add(yo, 0xa0) } {
|
||||
let b0 := mload(add(b, yo))
|
||||
let b1 := mload(add(b, add(yo, 0x20)))
|
||||
let b2 := mload(add(b, add(yo, 0x40)))
|
||||
let b3 := mload(add(b, add(yo, 0x60)))
|
||||
let b4 := mload(add(b, add(yo, 0x80)))
|
||||
mstore(add(s, yo), and(0xffffffffffffffff, xor(b0, and(not(b1), b2))))
|
||||
mstore(add(s, add(yo, 0x20)), and(0xffffffffffffffff, xor(b1, and(not(b2), b3))))
|
||||
mstore(add(s, add(yo, 0x40)), and(0xffffffffffffffff, xor(b2, and(not(b3), b4))))
|
||||
mstore(add(s, add(yo, 0x60)), and(0xffffffffffffffff, xor(b3, and(not(b4), b0))))
|
||||
mstore(add(s, add(yo, 0x80)), and(0xffffffffffffffff, xor(b4, and(not(b0), b1))))
|
||||
}
|
||||
// ---- iota ----
|
||||
mstore(add(s, 0), xor(mload(add(s, 0)), mload(add(rc, mul(rnd, 0x20)))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @dev Absorb `input` into a fresh SHAKE256 sponge (rate 136 bytes, domain
|
||||
/// 0x1F, pad10*1) and return the state after the final permutation.
|
||||
function _shakeAbsorb(bytes memory input) internal view returns (uint64[25] memory st) {
|
||||
uint256 len = input.length;
|
||||
uint256 off = 0;
|
||||
// full 136-byte blocks
|
||||
while (len - off >= 136) {
|
||||
for (uint256 j = 0; j < 17; j++) {
|
||||
uint64 lane = 0;
|
||||
uint256 base = off + j * 8;
|
||||
for (uint256 b = 0; b < 8; b++) {
|
||||
lane |= uint64(uint8(input[base + b])) << (8 * b);
|
||||
}
|
||||
st[j] ^= lane;
|
||||
}
|
||||
_keccakf(st);
|
||||
off += 136;
|
||||
}
|
||||
// final (partial) block with padding
|
||||
uint256 rem = len - off;
|
||||
bytes memory blk = new bytes(136);
|
||||
for (uint256 i = 0; i < rem; i++) {
|
||||
blk[i] = input[off + i];
|
||||
}
|
||||
blk[rem] = bytes1(uint8(blk[rem]) ^ 0x1F); // domain separation
|
||||
blk[135] = bytes1(uint8(blk[135]) ^ 0x80); // final bit of pad10*1
|
||||
for (uint256 j = 0; j < 17; j++) {
|
||||
uint64 lane = 0;
|
||||
uint256 base = j * 8;
|
||||
for (uint256 b = 0; b < 8; b++) {
|
||||
lane |= uint64(uint8(blk[base + b])) << (8 * b);
|
||||
}
|
||||
st[j] ^= lane;
|
||||
}
|
||||
_keccakf(st);
|
||||
}
|
||||
|
||||
/// @dev Extract the current 136-byte rate block (little-endian lanes 0..16).
|
||||
function _rateBlock(uint64[25] memory st) internal view returns (bytes memory out) {
|
||||
out = new bytes(136);
|
||||
for (uint256 j = 0; j < 17; j++) {
|
||||
uint64 lane = st[j];
|
||||
for (uint256 b = 0; b < 8; b++) {
|
||||
out[j * 8 + b] = bytes1(uint8(lane >> (8 * b)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @notice Squeeze `outLen` bytes of SHAKE256(input). Exposed for KAT testing.
|
||||
function shake256(bytes memory input, uint256 outLen) public view returns (bytes memory out) {
|
||||
uint64[25] memory st = _shakeAbsorb(input);
|
||||
out = new bytes(outLen);
|
||||
uint256 pos = 0;
|
||||
while (pos < outLen) {
|
||||
bytes memory blk = _rateBlock(st);
|
||||
uint256 take = outLen - pos;
|
||||
if (take > 136) take = 136;
|
||||
for (uint256 i = 0; i < take; i++) {
|
||||
out[pos + i] = blk[i];
|
||||
}
|
||||
pos += take;
|
||||
if (pos < outLen) _keccakf(st);
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// HashToPoint
|
||||
// ==========================================================================
|
||||
|
||||
/// @notice HashToPoint(nonce || message) -> challenge polynomial c (512 coeffs).
|
||||
/// @dev Streams SHAKE256 two bytes at a time; keeps a big-endian 16-bit sample
|
||||
/// when it is < 5*q = 61445, reducing it mod q. Matches the reference
|
||||
/// hash_to_point_vartime exactly.
|
||||
function hashToPoint(bytes memory nonce, bytes memory message) public view returns (uint256[512] memory cc) {
|
||||
// Native AERE Falcon HashToPoint precompile @ 0x0AE7: logn(1)=9 || nonce(40) || message
|
||||
bytes memory input = bytes.concat(bytes1(uint8(9)), nonce, message);
|
||||
(bool okp, bytes memory outp) = address(0x0AE7).staticcall(input);
|
||||
require(okp && outp.length == 1024, "htp precompile failed");
|
||||
for (uint256 i = 0; i < 512; i++) {
|
||||
cc[i] = (uint256(uint8(outp[2 * i])) << 8) | uint256(uint8(outp[2 * i + 1]));
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Public key / signature decode
|
||||
// ==========================================================================
|
||||
|
||||
/// @notice Decode a 897-byte Falcon-512 public key into h (512 coeffs).
|
||||
/// @return h the 512 coefficients, ok false if the encoding is invalid.
|
||||
function decodePublicKey(bytes memory pk) public view returns (uint256[512] memory h, bool ok) {
|
||||
if (pk.length != 897 || uint8(pk[0]) != PK_HEADER) {
|
||||
return (h, false);
|
||||
}
|
||||
uint256 acc = 0;
|
||||
uint256 accLen = 0;
|
||||
uint256 u = 0;
|
||||
// 896 encoded bytes = 512 * 14 bits, exact
|
||||
for (uint256 i = 1; i < 897 && u < 512; i++) {
|
||||
acc = ((acc << 8) | uint256(uint8(pk[i]))) & 0xFFFFFFFF;
|
||||
accLen += 8;
|
||||
if (accLen >= 14) {
|
||||
accLen -= 14;
|
||||
uint256 w = (acc >> accLen) & 0x3FFF;
|
||||
if (w >= Q) return (h, false);
|
||||
h[u] = w;
|
||||
u++;
|
||||
}
|
||||
}
|
||||
if (u != 512) return (h, false);
|
||||
// trailing bits must be zero
|
||||
if ((acc & ((uint256(1) << accLen) - 1)) != 0) return (h, false);
|
||||
return (h, true);
|
||||
}
|
||||
|
||||
/// @notice Decode the compressed Falcon signature bytes into s2 (512 signed coeffs).
|
||||
/// @dev Mirrors the reference comp_decode: for each coefficient read a byte
|
||||
/// giving sign + 7 low bits, then read bits until a 1 for the high part.
|
||||
/// Rejects "-0", overflow (>2047), running off the buffer, or nonzero
|
||||
/// trailing bits. Requires the whole buffer to be consumed.
|
||||
/// @return s2 signed coefficients (centered), ok false if invalid.
|
||||
function decodeSignature(bytes memory sig) public view returns (int256[512] memory s2, bool ok) {
|
||||
uint256 acc = 0;
|
||||
uint256 accLen = 0;
|
||||
uint256 v = 0;
|
||||
uint256 maxLen = sig.length;
|
||||
for (uint256 u = 0; u < 512; u++) {
|
||||
if (v >= maxLen) return (s2, false);
|
||||
acc = ((acc << 8) | uint256(uint8(sig[v]))) & 0xFFFFFFFF;
|
||||
v++;
|
||||
uint256 bb = acc >> accLen;
|
||||
uint256 s = bb & 128;
|
||||
uint256 m = bb & 127;
|
||||
// read high bits until a set bit
|
||||
while (true) {
|
||||
if (accLen == 0) {
|
||||
if (v >= maxLen) return (s2, false);
|
||||
acc = ((acc << 8) | uint256(uint8(sig[v]))) & 0xFFFFFFFF;
|
||||
v++;
|
||||
accLen = 8;
|
||||
}
|
||||
accLen--;
|
||||
if (((acc >> accLen) & 1) != 0) break;
|
||||
m += 128;
|
||||
if (m > 2047) return (s2, false);
|
||||
}
|
||||
if (s != 0 && m == 0) return (s2, false); // "-0" forbidden
|
||||
s2[u] = s != 0 ? -int256(m) : int256(m);
|
||||
}
|
||||
// unused bits in the last consumed byte must be zero
|
||||
if ((acc & ((uint256(1) << accLen) - 1)) != 0) return (s2, false);
|
||||
// the whole signature buffer must be consumed exactly
|
||||
if (v != maxLen) return (s2, false);
|
||||
return (s2, true);
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Ring arithmetic + norm
|
||||
// ==========================================================================
|
||||
|
||||
/// @dev b^e mod q.
|
||||
function _modpow(uint256 b, uint256 e) internal view returns (uint256 r) {
|
||||
r = 1;
|
||||
b %= Q;
|
||||
while (e > 0) {
|
||||
if (e & 1 == 1) r = mulmod(r, b, Q);
|
||||
b = mulmod(b, b, Q);
|
||||
e >>= 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// @dev In-place bit-reversal permutation of a length-512 array.
|
||||
function _bitrev(uint256[512] memory a) internal view {
|
||||
uint256 j = 0;
|
||||
for (uint256 i = 1; i < 512; i++) {
|
||||
uint256 bit = 256; // n >> 1
|
||||
while (j & bit != 0) {
|
||||
j ^= bit;
|
||||
bit >>= 1;
|
||||
}
|
||||
j ^= bit;
|
||||
if (i < j) {
|
||||
uint256 tmp = a[i];
|
||||
a[i] = a[j];
|
||||
a[j] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @dev Iterative in-place NTT (natural order in and out) with the given root.
|
||||
function _ntt(uint256[512] memory a, uint256 root) internal view {
|
||||
_bitrev(a);
|
||||
for (uint256 len = 2; len <= 512; len <<= 1) {
|
||||
uint256 wlen = _modpow(root, 512 / len);
|
||||
uint256 half = len >> 1;
|
||||
for (uint256 i = 0; i < 512; i += len) {
|
||||
uint256 wn = 1;
|
||||
for (uint256 k = i; k < i + half; k++) {
|
||||
uint256 vv = mulmod(a[k + half], wn, Q);
|
||||
uint256 u = a[k];
|
||||
a[k] = addmod(u, vv, Q);
|
||||
a[k + half] = addmod(u, Q - vv, Q);
|
||||
wn = mulmod(wn, wlen, Q);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @dev Negacyclic convolution t = a*b in Z_q[x]/(x^512+1) via NTT.
|
||||
/// Pre-twist by PSI^i, length-512 NTT (root W), pointwise multiply,
|
||||
/// inverse NTT, post-twist by PSI^-i and multiply by n^-1.
|
||||
function _ringMul(uint256[512] memory A, uint256[512] memory B) internal view returns (uint256[512] memory r) {
|
||||
uint256[512] memory a = A;
|
||||
uint256[512] memory b = B;
|
||||
uint256 p = 1;
|
||||
for (uint256 i = 0; i < 512; i++) {
|
||||
a[i] = mulmod(a[i] % Q, p, Q);
|
||||
b[i] = mulmod(b[i] % Q, p, Q);
|
||||
p = mulmod(p, PSI, Q);
|
||||
}
|
||||
_ntt(a, W);
|
||||
_ntt(b, W);
|
||||
for (uint256 i = 0; i < 512; i++) {
|
||||
a[i] = mulmod(a[i], b[i], Q);
|
||||
}
|
||||
_ntt(a, W_INV);
|
||||
// post-twist: r[i] = a[i] * n^-1 * PSI^-i
|
||||
uint256 pinv = N_INV; // n^-1 * PSI^-0
|
||||
for (uint256 i = 0; i < 512; i++) {
|
||||
r[i] = mulmod(a[i], pinv, Q);
|
||||
pinv = mulmod(pinv, PSI_INV, Q);
|
||||
}
|
||||
}
|
||||
|
||||
// ==========================================================================
|
||||
// Verification
|
||||
// ==========================================================================
|
||||
|
||||
/// @notice Verify a Falcon-512 signature given decomposed inputs.
|
||||
/// @param pk 897-byte NIST public key (0x09 header + packed h).
|
||||
/// @param message the signed message bytes.
|
||||
/// @param nonce 40-byte salt r.
|
||||
/// @param compSig compressed encoding of s2 (comp_encode output).
|
||||
/// @return ok true iff the signature is a valid Falcon-512 signature.
|
||||
function verify(
|
||||
bytes memory pk,
|
||||
bytes memory message,
|
||||
bytes memory nonce,
|
||||
bytes memory compSig
|
||||
) public view returns (bool ok) {
|
||||
if (nonce.length != NONCE_LEN) return false;
|
||||
|
||||
(uint256[512] memory h, bool okPk) = decodePublicKey(pk);
|
||||
if (!okPk) return false;
|
||||
|
||||
(int256[512] memory s2, bool okSig) = decodeSignature(compSig);
|
||||
if (!okSig) return false;
|
||||
|
||||
uint256[512] memory cc = hashToPoint(nonce, message);
|
||||
|
||||
// s2 reduced into [0, q)
|
||||
uint256[512] memory s2m;
|
||||
for (uint256 i = 0; i < 512; i++) {
|
||||
int256 x = s2[i] % int256(Q);
|
||||
if (x < 0) x += int256(Q);
|
||||
s2m[i] = uint256(x);
|
||||
}
|
||||
|
||||
// t = s2 * h (mod q, ring)
|
||||
uint256[512] memory t = _ringMul(s2m, h);
|
||||
|
||||
// s1 = c - t, centered into (-q/2, q/2]; accumulate squared norm
|
||||
uint256 norm = 0;
|
||||
for (uint256 i = 0; i < 512; i++) {
|
||||
uint256 val = addmod(cc[i], Q - t[i], Q); // (c - t) mod q, in [0,q)
|
||||
int256 s1 = val > HQ ? int256(val) - int256(Q) : int256(val);
|
||||
norm += uint256(s1 * s1);
|
||||
int256 z = s2[i];
|
||||
norm += uint256(z * z);
|
||||
if (norm > L2BOUND) return false; // early out (also guards accumulation)
|
||||
}
|
||||
return norm <= L2BOUND;
|
||||
}
|
||||
|
||||
/// @notice Verify a Falcon-512 signature from a raw NIST "signed message" (sm)
|
||||
/// blob plus the public key. This consumes the exact bytes found in
|
||||
/// the official KAT: sm = sigLen(2, big-endian) || nonce(40) ||
|
||||
/// message || esig, where esig = 0x29 || compSig.
|
||||
function verifySignedMessage(bytes memory pk, bytes memory sm) public view returns (bool ok) {
|
||||
uint256 smlen = sm.length;
|
||||
if (smlen < 2 + NONCE_LEN) return false;
|
||||
uint256 sigLen = (uint256(uint8(sm[0])) << 8) | uint256(uint8(sm[1]));
|
||||
if (sigLen > smlen - 2 - NONCE_LEN) return false;
|
||||
uint256 msgLen = smlen - 2 - NONCE_LEN - sigLen;
|
||||
if (sigLen < 1) return false;
|
||||
|
||||
// esig begins at 2 + NONCE_LEN + msgLen; its first byte is the header
|
||||
uint256 esigStart = 2 + NONCE_LEN + msgLen;
|
||||
if (uint8(sm[esigStart]) != SIG_HEADER) return false;
|
||||
|
||||
bytes memory nonce = new bytes(NONCE_LEN);
|
||||
for (uint256 i = 0; i < NONCE_LEN; i++) nonce[i] = sm[2 + i];
|
||||
|
||||
bytes memory message = new bytes(msgLen);
|
||||
for (uint256 i = 0; i < msgLen; i++) message[i] = sm[2 + NONCE_LEN + i];
|
||||
|
||||
bytes memory compSig = new bytes(sigLen - 1);
|
||||
for (uint256 i = 0; i < sigLen - 1; i++) compSig[i] = sm[esigStart + 1 + i];
|
||||
|
||||
return verify(pk, message, nonce, compSig);
|
||||
}
|
||||
|
||||
/// @notice State-changing wrapper: verify and record the result on-chain.
|
||||
function verifyAndRecord(bytes memory pk, bytes memory sm) external returns (bool result) {
|
||||
result = verifySignedMessage(pk, sm);
|
||||
lastResult = result;
|
||||
uint256 idx = verifyCount;
|
||||
verifyCount = idx + 1;
|
||||
emit Verified(msg.sender, result, idx);
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
#!/usr/bin/env python3
|
||||
# Falcon-512 verify gas benchmark: WITH vs WITHOUT the native HashToPoint precompile.
|
||||
# Deploys the stock in-EVM verifier (V0) and the precompile-backed variant (V1) on
|
||||
# the isolated fork node, runs identical real Falcon-512 KAT vectors through both,
|
||||
# and reports receipt gasUsed. Also confirms genuine sigs accept / tampered reject
|
||||
# on BOTH (integration KAT for the precompile).
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
# Repository root, resolved from this file's location, so the script runs as-is in
|
||||
# a clean checkout. Override with AERE_STAGING. These paths were previously
|
||||
# hardcoded to a build operator's home directory, which disclosed an internal
|
||||
# layout and made the benchmark unrunnable for anyone else without editing it.
|
||||
STAGING = os.environ.get(
|
||||
"AERE_STAGING", os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
|
||||
)
|
||||
|
||||
from web3 import Web3
|
||||
from eth_account import Account
|
||||
|
||||
RPC = "http://127.0.0.1:8545"
|
||||
KEY = "0x0000000000000000000000000000000000000000000000000000000000000001"
|
||||
acct = Account.from_key(KEY)
|
||||
|
||||
w3 = Web3(Web3.HTTPProvider(RPC))
|
||||
# QBFT is proof-of-authority: extraData > 32 bytes, needs the POA middleware.
|
||||
try:
|
||||
from web3.middleware import ExtraDataToPOAMiddleware
|
||||
w3.middleware_onion.inject(ExtraDataToPOAMiddleware, layer=0)
|
||||
except Exception:
|
||||
from web3.middleware import geth_poa_middleware # older web3
|
||||
w3.middleware_onion.inject(geth_poa_middleware, layer=0)
|
||||
assert w3.is_connected(), "no RPC"
|
||||
CHAIN = w3.eth.chain_id
|
||||
|
||||
|
||||
def compile_all():
|
||||
out = subprocess.check_output([
|
||||
"solc", "--combined-json", "abi,bin", "--optimize", "--optimize-runs", "200",
|
||||
os.path.join(STAGING, "bench", "AereFalcon512Verifier.sol"),
|
||||
os.path.join(STAGING, "bench", "AereFalcon512VerifierHTP.sol"),
|
||||
])
|
||||
j = json.loads(out)
|
||||
res = {}
|
||||
for name, c in j["contracts"].items():
|
||||
short = name.split(":")[-1]
|
||||
res[short] = {"abi": c["abi"] if isinstance(c["abi"], list) else json.loads(c["abi"]), "bin": c["bin"]}
|
||||
return res
|
||||
|
||||
|
||||
def gas_price():
|
||||
blk = w3.eth.get_block("latest")
|
||||
base = blk.get("baseFeePerGas", 0) or 0
|
||||
return int(base) * 2 + 10 ** 9
|
||||
|
||||
|
||||
def send(tx):
|
||||
tx.setdefault("chainId", CHAIN)
|
||||
tx.setdefault("nonce", w3.eth.get_transaction_count(acct.address))
|
||||
tx.setdefault("gas", 40_000_000)
|
||||
tx.setdefault("gasPrice", gas_price())
|
||||
signed = acct.sign_transaction(tx)
|
||||
raw = getattr(signed, "raw_transaction", None) or signed.rawTransaction
|
||||
h = w3.eth.send_raw_transaction(raw)
|
||||
return w3.eth.wait_for_transaction_receipt(h, timeout=120)
|
||||
|
||||
|
||||
def deploy(art):
|
||||
c = w3.eth.contract(abi=art["abi"], bytecode=art["bin"])
|
||||
tx = c.constructor().build_transaction({"from": acct.address, "gas": 12_000_000,
|
||||
"gasPrice": gas_price(), "nonce": w3.eth.get_transaction_count(acct.address),
|
||||
"chainId": CHAIN})
|
||||
r = send(tx)
|
||||
assert r.status == 1, "deploy failed"
|
||||
return w3.eth.contract(address=r.contractAddress, abi=art["abi"]), r.gasUsed
|
||||
|
||||
|
||||
def parse_sm(sm: bytes):
|
||||
siglen = (sm[0] << 8) | sm[1]
|
||||
nonce = sm[2:42]
|
||||
msglen = len(sm) - 2 - 40 - siglen
|
||||
message = sm[42:42 + msglen]
|
||||
return nonce, message
|
||||
|
||||
|
||||
def main():
|
||||
vec_path = sys.argv[1] if len(sys.argv) > 1 else os.path.join(STAGING, "kat", "falcon512_bench_vectors.txt")
|
||||
out_path = sys.argv[2] if len(sys.argv) > 2 else os.path.join(STAGING, "bench", "bench-results.json")
|
||||
|
||||
# --- precompile liveness sanity ---
|
||||
sample = (bytes([9]) + b"\x00" * 40 + b"abc")
|
||||
htp_out = w3.eth.call({"to": "0x0000000000000000000000000000000000000AE7", "data": "0x" + sample.hex()})
|
||||
assert len(htp_out) == 1024, f"0x0AE7 not active (got {len(htp_out)} bytes)"
|
||||
print(f"precompile 0x0AE7 live: returned {len(htp_out)} bytes for logn=9")
|
||||
|
||||
arts = compile_all()
|
||||
v0, g0_deploy = deploy(arts["AereFalcon512Verifier"])
|
||||
v1, g1_deploy = deploy(arts["AereFalcon512VerifierHTP"])
|
||||
print(f"deployed V0(in-EVM)={v0.address} gas={g0_deploy} V1(precompile)={v1.address} gas={g1_deploy}")
|
||||
|
||||
rows = []
|
||||
for line in open(vec_path):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
tc, pk_hex, sm_hex = line.split("|")
|
||||
pk = bytes.fromhex(pk_hex)
|
||||
sm = bytes.fromhex(sm_hex)
|
||||
nonce, message = parse_sm(sm)
|
||||
|
||||
# correctness (eth_call) — genuine must accept on both
|
||||
ok0 = v0.functions.verifySignedMessage(pk, sm).call()
|
||||
ok1 = v1.functions.verifySignedMessage(pk, sm).call()
|
||||
# tampered must reject on both
|
||||
bad = bytearray(sm); bad[-1] ^= 0x01
|
||||
bad0 = v0.functions.verifySignedMessage(pk, bytes(bad)).call()
|
||||
bad1 = v1.functions.verifySignedMessage(pk, bytes(bad)).call()
|
||||
|
||||
# gas via state-changing verifyAndRecord (identical calldata both sides)
|
||||
r0 = send(v0.functions.verifyAndRecord(pk, sm).build_transaction(
|
||||
{"from": acct.address, "gas": 40_000_000, "gasPrice": gas_price(),
|
||||
"nonce": w3.eth.get_transaction_count(acct.address), "chainId": CHAIN}))
|
||||
r1 = send(v1.functions.verifyAndRecord(pk, sm).build_transaction(
|
||||
{"from": acct.address, "gas": 40_000_000, "gasPrice": gas_price(),
|
||||
"nonce": w3.eth.get_transaction_count(acct.address), "chainId": CHAIN}))
|
||||
|
||||
# component gas: standalone hashToPoint estimate on each
|
||||
htp0 = v0.functions.hashToPoint(nonce, message).estimate_gas({"from": acct.address})
|
||||
htp1 = v1.functions.hashToPoint(nonce, message).estimate_gas({"from": acct.address})
|
||||
|
||||
row = {"tc": tc, "accept_v0": ok0, "accept_v1": ok1, "reject_tampered_v0": not bad0,
|
||||
"reject_tampered_v1": not bad1, "verify_gas_in_evm": r0.gasUsed,
|
||||
"verify_gas_precompile": r1.gasUsed, "verify_gas_drop": r0.gasUsed - r1.gasUsed,
|
||||
"hashToPoint_gas_in_evm": htp0, "hashToPoint_gas_precompile": htp1}
|
||||
rows.append(row)
|
||||
print(f"tc{tc} accept v0={ok0} v1={ok1} tamperReject v0={not bad0} v1={not bad1} "
|
||||
f"| verify gas {r0.gasUsed} -> {r1.gasUsed} (drop {r0.gasUsed - r1.gasUsed}) "
|
||||
f"| HTP {htp0} -> {htp1}")
|
||||
|
||||
n = len(rows)
|
||||
avg = lambda k: sum(r[k] for r in rows) // n
|
||||
all_ok = all(r["accept_v0"] and r["accept_v1"] and r["reject_tampered_v0"] and r["reject_tampered_v1"] for r in rows)
|
||||
summary = {
|
||||
"chainId": CHAIN, "vectors": n, "integration_all_pass": all_ok,
|
||||
"avg_verify_gas_in_evm": avg("verify_gas_in_evm"),
|
||||
"avg_verify_gas_precompile": avg("verify_gas_precompile"),
|
||||
"avg_verify_gas_drop": avg("verify_gas_drop"),
|
||||
"avg_verify_pct_drop": round(100 * avg("verify_gas_drop") / avg("verify_gas_in_evm"), 1),
|
||||
"avg_hashToPoint_gas_in_evm": avg("hashToPoint_gas_in_evm"),
|
||||
"avg_hashToPoint_gas_precompile": avg("hashToPoint_gas_precompile"),
|
||||
"deploy_gas_in_evm": g0_deploy, "deploy_gas_precompile": g1_deploy,
|
||||
"rows": rows,
|
||||
}
|
||||
json.dump(summary, open(out_path, "w"), indent=2)
|
||||
print("\n=== SUMMARY ===")
|
||||
print(json.dumps({k: v for k, v in summary.items() if k != "rows"}, indent=2))
|
||||
if not all_ok:
|
||||
print("INTEGRATION_FAILED"); sys.exit(3)
|
||||
print("BENCH_DONE")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"config": {
|
||||
"chainId": 28777,
|
||||
"ethash": {},
|
||||
"londonBlock": 0,
|
||||
"shanghaiTime": 0,
|
||||
"cancunTime": 0,
|
||||
"pragueTime": 0,
|
||||
"osakaTime": 0,
|
||||
"futureEipsTime": 0
|
||||
},
|
||||
"nonce": "0x0",
|
||||
"timestamp": "0x0",
|
||||
"extraData": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"gasLimit": "0x1fffffffffffff",
|
||||
"difficulty": "0x1",
|
||||
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
|
||||
"coinbase": "0x0000000000000000000000000000000000000000",
|
||||
"alloc": {
|
||||
"7E5F4552091A69125d5DfCb7b8C2659029395Bdf": {
|
||||
"balance": "0x200000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
# Derive AereFalcon512VerifierHTP.sol from AereFalcon512Verifier.sol by replacing
|
||||
# ONLY the in-EVM hashToPoint with a call to the native 0x0AE7 precompile. Every
|
||||
# other step (SHAKE helpers, decode, ring mul, norm check) is byte-identical, so a
|
||||
# WITH-vs-WITHOUT gas comparison isolates exactly the HashToPoint cost.
|
||||
import re
|
||||
import sys
|
||||
|
||||
src_path = sys.argv[1]
|
||||
out_path = sys.argv[2]
|
||||
s = open(src_path).read()
|
||||
|
||||
# 1. rename the contract
|
||||
s = s.replace("contract AereFalcon512Verifier {", "contract AereFalcon512VerifierHTP {")
|
||||
|
||||
# 2. relax `pure` -> `view` on function declarations (the precompile call is a staticcall = view)
|
||||
s = re.sub(r"\)(\s*)(public|internal|external|private)(\s+)pure", r")\1\2\3view", s)
|
||||
|
||||
# 3. replace the whole hashToPoint function body with a precompile-backed one (brace-matched)
|
||||
start = s.index("function hashToPoint(")
|
||||
# walk to the opening brace of the body
|
||||
brace = s.index("{", start)
|
||||
depth = 0
|
||||
i = brace
|
||||
while i < len(s):
|
||||
if s[i] == "{":
|
||||
depth += 1
|
||||
elif s[i] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
break
|
||||
i += 1
|
||||
end = i + 1 # inclusive of closing brace
|
||||
|
||||
replacement = (
|
||||
"function hashToPoint(bytes memory nonce, bytes memory message) public view returns (uint256[512] memory cc) {\n"
|
||||
" // Native AERE Falcon HashToPoint precompile @ 0x0AE7: logn(1)=9 || nonce(40) || message\n"
|
||||
" bytes memory input = bytes.concat(bytes1(uint8(9)), nonce, message);\n"
|
||||
" (bool okp, bytes memory outp) = address(0x0AE7).staticcall(input);\n"
|
||||
" require(okp && outp.length == 1024, \"htp precompile failed\");\n"
|
||||
" for (uint256 i = 0; i < 512; i++) {\n"
|
||||
" cc[i] = (uint256(uint8(outp[2 * i])) << 8) | uint256(uint8(outp[2 * i + 1]));\n"
|
||||
" }\n"
|
||||
" }"
|
||||
)
|
||||
s = s[:start] + replacement + s[end:]
|
||||
|
||||
open(out_path, "w").write(s)
|
||||
print("wrote", out_path)
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"genesis": {
|
||||
"config": {
|
||||
"chainId": 28777,
|
||||
"londonBlock": 0,
|
||||
"shanghaiTime": 0,
|
||||
"cancunTime": 0,
|
||||
"pragueTime": 0,
|
||||
"osakaTime": 0,
|
||||
"futureEipsTime": 0,
|
||||
"zeroBaseFee": true,
|
||||
"qbft": { "blockperiodseconds": 1, "epochlength": 30000, "requesttimeoutseconds": 4 }
|
||||
},
|
||||
"gasLimit": "0x1fffffffffffff",
|
||||
"difficulty": "0x1",
|
||||
"alloc": {
|
||||
"7E5F4552091A69125d5DfCb7b8C2659029395Bdf": { "balance": "0x200000000000000000000000000000000000000000000000000000000000000" }
|
||||
}
|
||||
},
|
||||
"blockchain": { "nodes": { "generate": true, "count": 1 } }
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
# Start an isolated single-node fork chain with the AERE future-EIP precompiles
|
||||
# (0x0AE1-0x0AE7) active from genesis. Ethash + instant low-difficulty mining.
|
||||
set -uo pipefail
|
||||
|
||||
# Paths are parameterized so this script runs as-is in a clean checkout. Override
|
||||
# any of them in the environment. Previously these were hardcoded to a build
|
||||
# operator's home directory, which both disclosed an internal layout and made the
|
||||
# script unrunnable for anyone else without editing it.
|
||||
# AERE_BESU_BIN path to the built besu launcher
|
||||
# AERE_WORK_DIR scratch directory for node data and logs (WILL BE DELETED)
|
||||
# AERE_STAGING directory holding bench/genesis.json and the KAT vectors
|
||||
BESU="${AERE_BESU_BIN:-${HOME}/besu/build/install/besu/bin/besu}"
|
||||
WORK_DIR="${AERE_WORK_DIR:-/tmp/aere-bench}"
|
||||
STAGING="${AERE_STAGING:-$(cd "$(dirname "$0")/.." && pwd)}"
|
||||
|
||||
NODE_DIR="${WORK_DIR}/node"
|
||||
NODE_LOG="${WORK_DIR}/node.log"
|
||||
mkdir -p "${WORK_DIR}"
|
||||
rm -rf "${NODE_DIR}"
|
||||
nohup "$BESU" \
|
||||
--data-path="${NODE_DIR}" \
|
||||
--genesis-file="${STAGING}/bench/genesis.json" \
|
||||
--network-id=28777 \
|
||||
--miner-enabled --miner-coinbase=0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf \
|
||||
--min-gas-price=0 \
|
||||
--rpc-http-enabled --rpc-http-host=127.0.0.1 --rpc-http-port=8545 \
|
||||
--rpc-http-api=ETH,NET,WEB3,DEBUG,TXPOOL \
|
||||
--host-allowlist='*' \
|
||||
> "${NODE_LOG}" 2>&1 &
|
||||
echo "besu pid $!"
|
||||
echo "waiting for RPC..."
|
||||
for i in $(seq 1 60); do
|
||||
bn=$(curl -s -X POST http://127.0.0.1:8545 -H 'Content-Type: application/json' \
|
||||
--data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' 2>/dev/null | grep -o '"result":"[^"]*"')
|
||||
if [ -n "$bn" ]; then echo "RPC up: $bn"; break; fi
|
||||
sleep 2
|
||||
done
|
||||
tail -5 "${NODE_LOG}"
|
||||
Reference in new issue
Block a user