Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

bls254.gno

// Package bls254 implements BLS signature verification over BN254, plus the
// hash-to-G1 construction and message encoding used by the SPLASH beacon.
//
// Curve: alt_bn128 / BN254. G1: y^2 = x^3 + 3 over Fp. Points are encoded as
// 64 bytes (x|y), each coordinate 32-byte big-endian. G2 points (as used for
// the publisher's public key and the fixed generator) are 128 bytes,
// EIP-197 wire order: x_imag | x_real | y_imag | y_real.
//
// There is no big-integer type in Gno, so field arithmetic goes through
// crypto/modexp (EIP-198 modular exponentiation) plus hand-rolled 4-limb
// compare/subtract/add for the one modular addition hash-to-G1 needs.
package bls254

import (
	"crypto/bn254"
	"crypto/modexp"
	"crypto/sha256"
	"encoding/hex"
	"math/bits"
	"strconv"
)

// DOMAIN is the hash-to-G1 domain separation tag for the SPLASH beacon.
const DOMAIN = "SPLASH-BEACON-BN254-G1-v1"

const (
	// pHex is the BN254 base field modulus, big-endian.
	pHex = "30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"
	// sqrtExpHex is (P+1)/4, a valid modular square-root exponent because
	// P % 4 == 3.
	sqrtExpHex = "0c19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52"
	// g2GenHex is the canonical G2 generator, EIP-197 wire order
	// (x_imag | x_real | y_imag | y_real).
	g2GenHex = "198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c21800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
)

var (
	pBytes       = mustDecodeHex(pHex)
	pLimbs       = toLimbs(pBytes)
	sqrtExpBytes = mustDecodeHex(sqrtExpHex)
	g2GenBytes   = mustDecodeHex(g2GenHex)
)

func mustDecodeHex(s string) []byte {
	b, err := hex.DecodeString(s)
	if err != nil {
		panic("bls254: bad constant hex")
	}
	return b
}

// ---- 4-limb (256-bit) field helpers. Inputs/outputs are 32-byte big-endian. ----
//
// Every function in this block is hand-unrolled over the four limbs rather than
// written as a `for i := 0; i < 4; i++` loop. That is not style, it is the second
// largest gas item in the drand path after the field multiply itself. Measured on
// this toolchain, 100 calls with the harness baseline subtracted:
//
//	              looped    unrolled   saved
//	toLimbs       52,705      39,328     25%
//	fromLimbs     58,961      42,308     28%
//	addModP       56,287      49,420     12%
//
// The gno VM charges per interpreted operation, so the loop counter, the bound
// test and the i*8 and 3-i index arithmetic cost real gas on top of the eight
// shift-ors they schedule. halveModP in fieldmul.gno was already unrolled and
// measured 21,035 against addModP's looped 56,287 for strictly more work, which
// is what prompted this.
//
// The saving is smaller than that comparison suggested -- addModP gave back 12%,
// not the 2.5x the halveModP contrast implied, because most of its cost is the
// four bits.Add64 calls and the cmp, not the loop scaffolding. The numbers above
// are measured on this toolchain, not predicted.
//
// The unrolled bodies are mechanical transcriptions of the loops they replace;
// TestLimbHelpersUnrolledMatchLooped in bls254_test.gno keeps a copy of each
// original loop and asserts the two agree on a large operand set, so the
// transcription is checked rather than eyeballed.

func toLimbs(b []byte) [4]uint64 {
	var l [4]uint64
	l[3] = uint64(b[0])<<56 | uint64(b[1])<<48 | uint64(b[2])<<40 | uint64(b[3])<<32 |
		uint64(b[4])<<24 | uint64(b[5])<<16 | uint64(b[6])<<8 | uint64(b[7])
	l[2] = uint64(b[8])<<56 | uint64(b[9])<<48 | uint64(b[10])<<40 | uint64(b[11])<<32 |
		uint64(b[12])<<24 | uint64(b[13])<<16 | uint64(b[14])<<8 | uint64(b[15])
	l[1] = uint64(b[16])<<56 | uint64(b[17])<<48 | uint64(b[18])<<40 | uint64(b[19])<<32 |
		uint64(b[20])<<24 | uint64(b[21])<<16 | uint64(b[22])<<8 | uint64(b[23])
	l[0] = uint64(b[24])<<56 | uint64(b[25])<<48 | uint64(b[26])<<40 | uint64(b[27])<<32 |
		uint64(b[28])<<24 | uint64(b[29])<<16 | uint64(b[30])<<8 | uint64(b[31])
	return l
}

func fromLimbs(l [4]uint64) []byte {
	b := make([]byte, 32)
	v := l[3]
	b[0], b[1], b[2], b[3] = byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32)
	b[4], b[5], b[6], b[7] = byte(v>>24), byte(v>>16), byte(v>>8), byte(v)
	v = l[2]
	b[8], b[9], b[10], b[11] = byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32)
	b[12], b[13], b[14], b[15] = byte(v>>24), byte(v>>16), byte(v>>8), byte(v)
	v = l[1]
	b[16], b[17], b[18], b[19] = byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32)
	b[20], b[21], b[22], b[23] = byte(v>>24), byte(v>>16), byte(v>>8), byte(v)
	v = l[0]
	b[24], b[25], b[26], b[27] = byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32)
	b[28], b[29], b[30], b[31] = byte(v>>24), byte(v>>16), byte(v>>8), byte(v)
	return b
}

// cmp returns -1, 0, 1 for a<b, a==b, a>b. Most-significant limb first, so the
// common case of a difference in the top limb returns after one comparison.
func cmp(a, b [4]uint64) int {
	if a[3] != b[3] {
		if a[3] < b[3] {
			return -1
		}
		return 1
	}
	if a[2] != b[2] {
		if a[2] < b[2] {
			return -1
		}
		return 1
	}
	if a[1] != b[1] {
		if a[1] < b[1] {
			return -1
		}
		return 1
	}
	if a[0] != b[0] {
		if a[0] < b[0] {
			return -1
		}
		return 1
	}
	return 0
}

func sub(a, b [4]uint64) [4]uint64 {
	var r [4]uint64
	var borrow uint64
	r[0], borrow = bits.Sub64(a[0], b[0], 0)
	r[1], borrow = bits.Sub64(a[1], b[1], borrow)
	r[2], borrow = bits.Sub64(a[2], b[2], borrow)
	r[3], _ = bits.Sub64(a[3], b[3], borrow)
	return r
}

func add(a, b [4]uint64) ([4]uint64, uint64) {
	var r [4]uint64
	var carry uint64
	r[0], carry = bits.Add64(a[0], b[0], 0)
	r[1], carry = bits.Add64(a[1], b[1], carry)
	r[2], carry = bits.Add64(a[2], b[2], carry)
	r[3], carry = bits.Add64(a[3], b[3], carry)
	return r, carry
}

// addModP computes (a + b) mod P for a, b already reduced mod P.
func addModP(a, b, p [4]uint64) [4]uint64 {
	s, carry := add(a, b)
	if carry != 0 || cmp(s, p) >= 0 {
		s = sub(s, p)
	}
	return s
}

// ---- hash-to-G1 ----

// hashToG1 is the non-panicking core of HashToG1. ok is false only if the
// try-and-increment loop exhausts its bound, which does not happen for any
// message with a well-formed hash (probability of exhaustion is ~2^-64).
func hashToG1(msg []byte) (pt []byte, ok bool) {
	pt, _, ok = hashToG1WithCounter(msg)
	return pt, ok
}

// hashToG1WithCounter is hashToG1 plus the retry counter it stopped at,
// exposed for tests that check the counter against testdata/vectors.json.
func hashToG1WithCounter(msg []byte) (pt []byte, ctr int, ok bool) {
	three := [4]uint64{3, 0, 0, 0}
	for ctr := 0; ctr < 64; ctr++ {
		buf := make([]byte, 0, len(DOMAIN)+len(msg)+1)
		buf = append(buf, DOMAIN...)
		buf = append(buf, msg...)
		buf = append(buf, byte(ctr))
		h := sha256.Sum256(buf)

		x := modexp.ModExp(h[:], []byte{1}, pBytes) // reduce mod P
		x3 := modexp.ModExp(x, []byte{3}, pBytes)    // x^3 mod P
		rhs := fromLimbs(addModP(toLimbs(x3), three, pLimbs))

		y := modexp.ModExp(rhs, sqrtExpBytes, pBytes) // candidate sqrt
		y2 := modexp.ModExp(y, []byte{2}, pBytes)
		if !bytesEqual(y2, rhs) {
			continue // not a quadratic residue
		}

		yl := toLimbs(y)
		if negy := sub(pLimbs, yl); cmp(negy, yl) < 0 {
			y = fromLimbs(negy) // canonical branch: numerically smaller root
		}
		out := make([]byte, 0, 64)
		out = append(out, x...)
		out = append(out, y...)
		return out, ctr, true
	}
	return nil, 64, false
}

func bytesEqual(a, b []byte) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

// HashToG1 maps msg to a G1 point via try-and-increment. Returns 64 bytes
// (x|y). Panics if the loop exhausts its 64-attempt bound.
func HashToG1(msg []byte) []byte {
	pt, ok := hashToG1(msg)
	if !ok {
		panic("bls254: hash_to_g1 exhausted")
	}
	return pt
}

// NegateG1 returns (x, P-y) for a 64-byte G1 point. Returns nil on bad input.
func NegateG1(pt []byte) []byte {
	return negateG1(pt)
}

func negateG1(pt []byte) []byte {
	if len(pt) != 64 {
		return nil
	}
	yl := toLimbs(pt[32:64])
	var zero [4]uint64
	out := make([]byte, 64)
	copy(out[:32], pt[:32])
	if cmp(yl, zero) == 0 {
		// y == 0 has no distinct negation; leave as-is.
		copy(out[32:], pt[32:64])
		return out
	}
	copy(out[32:], fromLimbs(sub(pLimbs, yl)))
	return out
}

// Verify reports whether sig is the BLS signature over msg under pubkey.
// pubkey is 128 bytes (G2, imaginary-first), sig is 64 bytes (G1). Verify is
// total: wrong lengths, unreduced coordinates, off-curve points and an
// invalid precompile result all yield false. It never panics.
func Verify(pubkey, msg, sig []byte) bool {
	if len(pubkey) != 128 || len(sig) != 64 {
		return false
	}
	h, ok := hashToG1(msg)
	if !ok {
		return false
	}
	negH := negateG1(h)
	if negH == nil {
		return false
	}

	in := make([]byte, 0, 384)
	in = append(in, sig...)
	in = append(in, g2GenBytes...)
	in = append(in, negH...)
	in = append(in, pubkey...)
	if len(in) != 384 {
		return false
	}

	out := bn254.PairingCheck(in)
	// PairingCheck returns an empty NON-NIL slice on an invalid point or an
	// unreduced coordinate; checking length (not nilness) is load-bearing.
	if len(out) != bn254.PairingOutputSize {
		return false
	}
	return out[len(out)-1] == 1
}

// RoundMessage builds the canonical message for a beacon round:
// chainID || "|" || decimal(round).
func RoundMessage(chainID string, round int64) []byte {
	return []byte(chainID + "|" + strconv.FormatInt(round, 10))
}

drandchain.gno

package bls254

// The drand "evmnet" chain's identity: the four facts about the beacon that are
// properties of the CHAIN rather than of any code here.
//
// THIS IS THE ONE PLACE THE GROUP PUBLIC KEY IS WRITTEN DOWN. Before this file it
// appeared only in test files, duplicated across drandvectors_test.gno and
// drandgas_test.gno; both now read it from here, and r/splash/beacon decodes it
// once at init. A second copy of a verification key is a second thing to get
// wrong, and the wrong one would reject every real signature or -- far worse in a
// different scheme -- accept a forged one.
//
// IT LIVES IN THIS PURE PACKAGE, NOT IN THE REALM, because it describes drand,
// not SPLASH. The realm that consumes it is one consumer; the tests are another;
// r/splash/arcade/raffle needs PeriodSeconds for a build-time guard and must not
// have to import a realm to get it.
//
// PROVENANCE, AND IT IS NOT DOCUMENTATION. Every value below was read from
// drand's own /info endpoint and is byte-identical from three independent relays
// -- api.drand.sh, api2.drand.sh and drand.cloudflare.com. The verbatim curl
// commands and responses are recorded twice, in testdata/drand/rounds.raw.txt
// here and in r/splash/beacon/testdata/drand-rounds.raw.txt.
const (
	// DrandEvmnetChainHash identifies the chain. It is not used in verification
	// -- the signed message is keccak256(uint64 round) and nothing else -- so it
	// is here to name what a signature belongs to, and to make a wrong-chain
	// fixture obvious to a reader rather than only to the pairing check.
	DrandEvmnetChainHash = "04f1e9062b8a81f848fded9c12306733282b2727ecced50032187751166ec8c3"

	// DrandEvmnetScheme is the scheme ID, and it is the reason drandcurve.gno
	// uses SVDW and not SSWU. See DrandDST.
	DrandEvmnetScheme = "bls-bn254-unchained-on-g1"

	// DrandEvmnetPeriodSeconds is the cadence: ONE ROUND EVERY THREE SECONDS.
	//
	// THIS NUMBER IS THE ONE THAT BREAKS THINGS. The SPLASH beacon it replaces
	// ran at five minutes, so every round-denominated duration anywhere in this
	// repository was 100x wrong the moment the key changed, while still being
	// dimensionally consistent and therefore invisible to the build guards that
	// compared rounds to rounds. Any realm expressing a DURATION in rounds must
	// multiply by this constant and compare against seconds. See
	// r/splash/beacon/DRAND-MIGRATION.md section 6.
	DrandEvmnetPeriodSeconds = 3

	// DrandEvmnetGenesisTime is round 1's unix timestamp, so round r is signed at
	// DrandEvmnetGenesisTime + DrandEvmnetPeriodSeconds*(r-1).
	//
	// NO REALM ON THIS TOOLCHAIN CAN USE THIS FOR ANYTHING, and that is worth
	// saying where someone will look for it: there is no block-timestamp getter,
	// so a realm cannot compare a round to the wall clock. It is here so that a
	// human or a test harness can, and so that the round <-> time mapping the
	// whole pin argument rests on is written down next to the period.
	DrandEvmnetGenesisTime = 1727521075

	// DrandEvmnetPubKeyHex is the 128-byte G2 group public key in EIP-197 wire
	// order (x_imag|x_real|y_imag|y_real) -- exactly the byte string /info serves
	// as "public_key", which is why it needs no reordering here.
	//
	// It is the DKG's collective key, held by no single party. That is the point
	// of the migration: under the SPLASH beacon one key holder knew every future
	// round's randomness, and under this one nobody below the threshold does.
	DrandEvmnetPubKeyHex = "07e1d1d335df83fa98462005690372c643340060d205306a9aa8106b6bd0b3820557ec32c2ad488e4d4f6008f89a346f18492092ccc0d594610de2732c8b808f0095685ae3a85ba243747b1b2f426049010f6b73a0cf1d389351d5aaaa1047f6297d3a4f9749b33eb2d904c9d9ebf17224150ddd7abd7567a9bec6c74480ee0b"
)

drandcurve.gno

package bls254

// RFC 9380 hash_to_field and the Shallue-van de Woestijne map to BN254 G1, as
// used by drand's bls-bn254-unchained-on-g1 scheme.
//
// This is the part of the drand path that differs most from the existing SPLASH
// beacon. SPLASH maps to G1 by try-and-increment: hash, treat the digest as x,
// bump a counter until x^3+3 is a square. drand uses RFC 9380 properly --
// expand_message_xmd to 96 bytes, split into two 48-byte field elements, SVDW
// each onto the curve, add the two points. The two constructions produce
// completely different points for the same message and are not interchangeable.
//
// BN254 G1 is y^2 = x^3 + 3 over Fp, so A = 0 and B = 3. The cofactor is 1, so
// there is no cofactor clearing: every point on the curve is in G1.

import (
	"crypto/bn254"
	"crypto/modexp"
)

// ---- SVDW constants ----
//
// RFC 9380 section 6.6.1 defines, for the curve y^2 = x^3 + A*x + B and a
// non-square-ish parameter Z:
//
//	c1 = g(Z)
//	c2 = -Z / 2
//	c3 = sqrt(-g(Z) * (3*Z^2 + 4*A))     with sgn0(c3) == 0
//	c4 = -4 * g(Z) / (3*Z^2 + 4*A)
//
// With A = 0, B = 3, Z = 1 that collapses to
//
//	g(Z) = Z^3 + A*Z + B = 1 + 3 = 4
//	c1   = 4
//	c2   = -1/2 mod p, which is (p-1)/2 because p is odd
//	c3   = sqrt(-4 * 3) = sqrt(-12) mod p, negated if odd so that sgn0(c3) == 0
//	c4   = -16/3 mod p
//
// I derived the four values from p with python3 rather than copying them:
//
//	p  = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
//	Z, A, B = 1, 0, 3
//	gZ = (Z**3 + A*Z + B) % p
//	c1 = gZ
//	c2 = (-Z * pow(2, -1, p)) % p
//	d  = (-gZ * (3*Z*Z + 4*A)) % p          # = -12 mod p
//	c3 = pow(d, (p+1)//4, p)                # p % 4 == 3, so this is a sqrt
//	assert c3*c3 % p == d
//	if c3 % 2 == 1: c3 = p - c3             # enforce sgn0(c3) == 0
//	c4 = (-4*gZ * pow(3*Z*Z + 4*A, -1, p)) % p
//
// and then checked them two ways before writing them down:
//
//   - against drand/kyber v1.3.2 pairing/bn254/constants.go, whose c1..c4 are
//     stored in Montgomery form; decoding them by multiplying by R^-1 mod p
//     (R = 2^256) reproduced all four exactly.
//   - against the Solidity reference randa-mu/bls-solidity src/libraries/BLS.sol,
//     whose C1/C2/C3/C4 literals are textually identical to the hex below.
//
// TestSVDWConstants re-derives all four inside the VM from pBytes alone, using
// only modexp and the limb helpers, so none of the above has to be trusted at
// read time.
const (
	// c1 = g(Z) = 4
	c1Hex = "0000000000000000000000000000000000000000000000000000000000000004"
	// c2 = -Z/2 = (p-1)/2
	c2Hex = "183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3"
	// c3 = sqrt(-12) mod p, the even root
	c3Hex = "00000000000000016789af3a83522eb353c98fc6b36d713d5d8d1cc5dffffffa"
	// c4 = -16/3 mod p
	c4Hex = "10216f7ba065e00de81ac1e7808072c9dd2b2385cd7b438469602eb24829a9bd"

	// invExpHex is p-2, the exponent for a modular inverse by Fermat. modexp
	// with this exponent is also RFC 9380's inv0: it maps 0 to 0, because
	// 0^(p-2) mod p is 0.
	invExpHex = "30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd45"
	// legExpHex is (p-1)/2, the Legendre symbol exponent. Numerically equal to
	// c2Hex; kept separate because the two mean different things and a future
	// edit to one must not silently change the other.
	legExpHex = "183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3"
)

var (
	c1Bytes = mustDecodeHex(c1Hex)
	c2Bytes = mustDecodeHex(c2Hex)
	c3Bytes = mustDecodeHex(c3Hex)
	c4Bytes = mustDecodeHex(c4Hex)

	invExpBytes = mustDecodeHex(invExpHex)
	legExpBytes = mustDecodeHex(legExpHex)

	fpOne   = mustDecodeHex("0000000000000000000000000000000000000000000000000000000000000001")
	fpThree = mustDecodeHex("0000000000000000000000000000000000000000000000000000000000000003")
)

// ---- Fp helpers, all on 32-byte big-endian values reduced mod p ----

func fpAdd(a, b []byte) []byte { return fromLimbs(addModP(toLimbs(a), toLimbs(b), pLimbs)) }
func fpSub(a, b []byte) []byte { return fromLimbs(subModP(toLimbs(a), toLimbs(b))) }
func fpNeg(a []byte) []byte    { return fromLimbs(negModP(toLimbs(a))) }

// fpMul and fpSqr are THE field multiply and square for the drand path. Every
// product in the SVDW map below goes through these two names and nowhere else, so
// the Montgomery-versus-modexp choice is made once, here, with the measurements
// that decided it recorded at the bottom of fieldmul.gno.
//
// Measured on this toolchain, per operation, harness baseline subtracted:
//
//	mulModP        (4-limb Montgomery)     2,200,369 gas
//	mulModPIdentity(squaring identity)       519,791 gas   <- 4.23x cheaper
//	sqrModP        (Montgomery a*a)        2,200,184 gas
//	sqrModPNative  (one native modexp)        69,602 gas   <- 31.6x cheaper
//
// (mulModPIdentity was 511,291 until 2026-09-29; the 8,500 is finding 21's
// unreduced-operand guard inside mulModPLimbs. The ranking is untouched.)
//
// so both names bind to the identity/native pair. mulModP and sqrModP are kept in
// fieldmul.gno as the independent oracle the equivalence test compares against,
// not as dead code.
func fpMul(a, b []byte) []byte { return mulModPIdentity(a, b) }
func fpSqr(a []byte) []byte    { return sqrModPNative(a) }

// fpInv0 is RFC 9380's inv0: the multiplicative inverse, with inv0(0) == 0.
// Fermat's little theorem gives a^(p-2) == a^-1 for a != 0, and modexp maps a
// zero base to zero, which is exactly inv0's extra clause.
func fpInv0(a []byte) []byte { return modexp.ModExp(a, invExpBytes, pBytes) }

// fpSqrt returns a square root of a when one exists. p % 4 == 3, so a^((p+1)/4)
// is a root; callers must have established that a is a square, or check the
// result by squaring it.
func fpSqrt(a []byte) []byte { return modexp.ModExp(a, sqrtExpBytes, pBytes) }

// fpIsSquareNonZero reports whether the Legendre symbol of a is exactly +1, i.e.
// a is a non-zero quadratic residue.
//
// RFC 9380's step 15 uses is_square, which is true for 0 as well. This uses
// "Legendre == 1", which is false for 0, because that is what both reference
// implementations of this exact ciphersuite do: drand/kyber v1.3.2's mapToPoint
// branches on `legendre(g(x1)) == 1`, and randa-mu/bls-solidity's BLS.sol on
// `legendre(g(x1)) == 1`. The two differ only when g(x) == 0, which happens for
// no u any adversary can reach in practice -- but the signers run kyber, so
// matching kyber is what makes signatures verify, and matching the RFC letter
// here would be a consensus bug rather than a fix.
func fpIsSquareNonZero(a []byte) bool {
	return bytesEqual(modexp.ModExp(a, legExpBytes, pBytes), fpOne)
}

// fpCurveRHS evaluates g(x) = x^3 + 3, the right-hand side of the BN254 G1
// equation. Returns nil if x is not a reduced 32-byte field element.
func fpCurveRHS(x []byte) []byte {
	x2 := fpSqr(x)
	if x2 == nil {
		return nil
	}
	x3 := fpMul(x2, x)
	if x3 == nil {
		return nil
	}
	return fpAdd(x3, fpThree)
}

// fpSgn0 is RFC 9380's sgn0 for m == 1: the low bit of the integer
// representation.
func fpSgn0(a []byte) byte { return a[31] & 1 }

// ---- hash_to_field ----

// hashToFieldDST is RFC 9380 hash_to_field with m = 1, count = 2 and L = 48: it
// expands msg to 96 bytes and reduces each 48-byte half mod p.
//
// The mod-p reduction needs no new code: modexp.ModExp(chunk, 1, p) is
// OS2IP(chunk) mod p and returns exactly len(p) == 32 bytes, left-padded.
//
// ok is false only if expandMessageXMD rejects its input, i.e. a DST longer than
// 255 bytes. It cannot be false for DrandDST.
func hashToFieldDST(msg, dst []byte) (u0, u1 [32]byte, ok bool) {
	b := expandMessageXMD(msg, dst, 96)
	if len(b) != 96 {
		return u0, u1, false
	}
	copy(u0[:], modexp.ModExp(b[0:48], []byte{1}, pBytes))
	copy(u1[:], modexp.ModExp(b[48:96], []byte{1}, pBytes))
	return u0, u1, true
}

// hashToFieldDrand is hash_to_field for drand's bn254 G1 ciphersuite: two field
// elements, expand_message_xmd with H = legacy Keccak-256, DST = DrandDST.
//
// Panics only on an unreachable branch: DrandDST is a fixed 43-byte constant and
// the output length is a fixed 96, so expandMessageXMD cannot reject. The panic
// is there so that a future edit which breaks that invariant fails loudly
// instead of returning two zero field elements, which would map to a valid-looking
// point and silently accept the wrong signatures. VerifyDrand does not go through
// this function; it uses hashToFieldDST and stays total.
func hashToFieldDrand(msg []byte) (u0, u1 [32]byte) {
	u0, u1, ok := hashToFieldDST(msg, []byte(DrandDST))
	if !ok {
		panic("bls254: hashToFieldDrand: expand_message_xmd rejected a fixed-size input")
	}
	return u0, u1
}

// ---- map_to_curve ----

// mapToPointSVDW maps one field element to a point on BN254 G1 by the
// Shallue-van de Woestijne method, RFC 9380 section 6.6.1 with Z = 1.
//
// Returns 64 bytes, x|y, each 32-byte big-endian. Returns nil if u is not a
// reduced field element (u >= p), or -- and this should be unreachable -- if the
// result fails the curve equation. The cofactor of BN254 G1 is 1, so the output
// needs no cofactor clearing and is already in the prime-order subgroup.
//
// The step numbering in the comments is RFC 9380's.
func mapToPointSVDW(u [32]byte) []byte {
	ub := u[:]
	if cmp(toLimbs(ub), pLimbs) >= 0 {
		return nil // field element >= p
	}

	// 1-2. tv1 = u^2 * c1
	tv1 := fpMul(fpSqr(ub), c1Bytes)
	if tv1 == nil {
		return nil
	}
	// 3. tv2 = 1 + tv1
	tv2 := fpAdd(fpOne, tv1)
	// 4. tv1 = 1 - tv1
	tv1 = fpSub(fpOne, tv1)
	// 5-6. tv3 = inv0(tv1 * tv2)
	tv3 := fpInv0(fpMul(tv1, tv2))
	// 7-9. tv4 = u * tv1 * tv3 * c3
	tv4 := fpMul(fpMul(fpMul(ub, tv1), tv3), c3Bytes)
	if tv4 == nil {
		return nil
	}
	// 10. x1 = c2 - tv4
	x1 := fpSub(c2Bytes, tv4)
	// 16. x2 = c2 + tv4
	x2 := fpAdd(c2Bytes, tv4)
	// 22-26. x3 = c4 * (tv2^2 * tv3)^2 + Z, with Z = 1
	tv8 := fpMul(fpSqr(tv2), tv3)
	x3 := fpAdd(fpMul(c4Bytes, fpSqr(tv8)), fpOne)

	// 11-21, 27-28. The first of x1, x2, x3 whose g(x) is a non-zero square
	// wins. See fpIsSquareNonZero for why this is Legendre == 1 rather than the
	// RFC's is_square.
	var x, gx []byte
	if g := fpCurveRHS(x1); fpIsSquareNonZero(g) {
		x, gx = x1, g
	} else if g := fpCurveRHS(x2); fpIsSquareNonZero(g) {
		x, gx = x2, g
	} else {
		x, gx = x3, fpCurveRHS(x3)
	}
	if gx == nil {
		return nil
	}

	// 29-33. y = sqrt(g(x))
	y := fpSqrt(gx)
	// 34-35. y gets u's sign.
	if fpSgn0(ub) != fpSgn0(y) {
		y = fpNeg(y)
	}

	// Postcondition. SVDW is supposed to land on the curve unconditionally; if
	// it has not, something above is wrong and returning the point would hand a
	// caller an off-curve "G1 element". Two extra multiplications to never do
	// that. This also catches the g(x3) branch being reached with a non-square,
	// which would make fpSqrt return a non-root.
	if !bytesEqual(fpSqr(y), gx) {
		return nil
	}

	out := make([]byte, 0, 64)
	out = append(out, x...)
	out = append(out, y...)
	return out
}

// ---- hash_to_curve ----

// HashToG1Drand maps msg to a G1 point the way drand's
// bls-bn254-unchained-on-g1 scheme does: RFC 9380 hash_to_curve, SVDW map,
// expand_message_xmd with H = legacy Keccak-256 and
// DST = BLS_SIG_BN254G1_XMD:KECCAK-256_SVDW_RO_NUL_.
//
// Returns 64 bytes, x|y. Returns nil if anything in the construction fails,
// which for a fixed DST means only that the native G1 addition rejected its
// input -- it never should.
//
// This is NOT HashToG1. HashToG1 is the existing SPLASH beacon's
// try-and-increment construction over a different domain tag, and the two return
// different points for the same message. Callers must not mix them.
func HashToG1Drand(msg []byte) []byte {
	u0, u1, ok := hashToFieldDST(msg, []byte(DrandDST))
	if !ok {
		return nil
	}
	p0 := mapToPointSVDW(u0)
	p1 := mapToPointSVDW(u1)
	if p0 == nil || p1 == nil {
		return nil
	}
	in := make([]byte, 0, bn254.G1AddInputSize)
	in = append(in, p0...)
	in = append(in, p1...)
	sum := bn254.G1Add(in)
	if len(sum) != bn254.G1OutputSize {
		return nil
	}
	return sum
}

drandmsg.gno

package bls254

// RFC 9380 expand_message_xmd, and drand's round-message encoding.
//
// These are the first two pieces of the drand verification path. They are
// separate from the SPLASH beacon's own encoding on purpose: the SPLASH scheme
// hashes chainID || "|" || decimal(round) with SHA-256 and maps to G1 by
// try-and-increment, and drand's evmnet chain does neither of those things. Two
// schemes, two names, no shared helpers that could be pointed at the wrong one.
//
// Everything here is verified against drand's own source rather than against
// documentation:
//
//	drand v2.1.7 crypto/schemes.go, NewPedersenBLSBN254UnchainedOnG1Scheme:
//	  Pairing.SetDomainG1([]byte("BLS_SIG_BN254G1_XMD:KECCAK-256_SVDW_RO_NUL_"))
//	  DigestFunc = keccak256(binary.BigEndian uint64 round)
//
// drand/kyber's *default* BN254 G1 DST is "BN254G1_XMD:KECCAK-256_SSWU_RO_" --
// SSWU, a different map and a different string. It is not what this chain signs
// under, and using it makes every signature fail.

import (
	"crypto/keccak256"
	"crypto/sha256"
)

// DrandDST is the hash-to-curve domain separation tag for drand's
// bls-bn254-unchained-on-g1 scheme (the "evmnet" beacon, chain hash
// 04f1e9062b8a81f848fded9c12306733282b2727ecced50032187751166ec8c3).
const DrandDST = "BLS_SIG_BN254G1_XMD:KECCAK-256_SVDW_RO_NUL_"

// keccakBlockSize is Keccak-256's input block size, i.e. its sponge rate:
// 1600 bits of state minus 2*256 bits of capacity = 1088 bits = 136 bytes.
// RFC 9380's Z_pad is I2OSP(0, s_in_bytes) with s_in_bytes = this value.
//
// 136, not 64. SHA-2's 64-byte block is the number most expand_message_xmd
// implementations are written against, and drand/kyber, the randa-mu Solidity
// reference and gnark all use the hash's own BlockSize() here, which for
// Keccak-256 is 136.
const keccakBlockSize = 136

// sha256BlockSize is SHA-256's input block size, used only by the tests that
// replay RFC 9380's published SHA-256 expand_message_xmd vectors.
const sha256BlockSize = 64

// expandMessageXMDWith implements expand_message_xmd from RFC 9380 section
// 5.3.1, parameterised on the hash and on that hash's input block size.
//
// The parameterisation exists for one reason: RFC 9380 publishes
// expand_message_xmd test vectors for SHA-256 and SHA-512 but not for
// Keccak-256, so the only way to check this construction against the RFC's own
// numbers is to run it with SHA-256. TestExpandMessageXMDRFC9380 does exactly
// that. Production callers go through expandMessageXMD, which fixes the hash to
// Keccak-256.
//
// Returns nil rather than a short or wrong answer on any input the RFC forbids:
// n outside [1, 65535], ell above 255, or a DST longer than 255 bytes.
func expandMessageXMDWith(sum func([]byte) [32]byte, sInBytes int, msg, dst []byte, n int) []byte {
	if n <= 0 || n > 65535 || len(dst) > 255 || sInBytes <= 0 {
		return nil
	}
	const bInBytes = 32 // both SHA-256 and Keccak-256 produce 32 bytes
	ell := (n + bInBytes - 1) / bInBytes
	if ell > 255 {
		return nil
	}

	// DST_prime = DST || I2OSP(len(DST), 1)
	dstPrime := make([]byte, 0, len(dst)+1)
	dstPrime = append(dstPrime, dst...)
	dstPrime = append(dstPrime, byte(len(dst)))

	// b_0 = H(Z_pad || msg || I2OSP(n, 2) || I2OSP(0, 1) || DST_prime)
	buf := make([]byte, 0, sInBytes+len(msg)+3+len(dstPrime))
	buf = append(buf, make([]byte, sInBytes)...) // Z_pad
	buf = append(buf, msg...)
	buf = append(buf, byte(n>>8), byte(n)) // l_i_b_str = I2OSP(n, 2)
	buf = append(buf, 0)                   // I2OSP(0, 1)
	buf = append(buf, dstPrime...)
	b0 := sum(buf)

	// b_1 = H(b_0 || I2OSP(1, 1) || DST_prime)
	buf = make([]byte, 0, bInBytes+1+len(dstPrime))
	buf = append(buf, b0[:]...)
	buf = append(buf, 1)
	buf = append(buf, dstPrime...)
	bi := sum(buf)

	out := make([]byte, 0, ell*bInBytes)
	out = append(out, bi[:]...)

	// b_i = H(strxor(b_0, b_(i-1)) || I2OSP(i, 1) || DST_prime)
	for i := 2; i <= ell; i++ {
		var x [bInBytes]byte
		for j := 0; j < bInBytes; j++ {
			x[j] = b0[j] ^ bi[j]
		}
		buf = make([]byte, 0, bInBytes+1+len(dstPrime))
		buf = append(buf, x[:]...)
		buf = append(buf, byte(i))
		buf = append(buf, dstPrime...)
		bi = sum(buf)
		out = append(out, bi[:]...)
	}
	return out[:n]
}

// expandMessageXMD is expand_message_xmd with H = legacy Keccak-256, which is
// what drand's bn254 scheme uses. Returns n pseudorandom bytes, or nil on input
// the RFC forbids (see expandMessageXMDWith).
//
// Legacy Keccak-256, NOT NIST SHA3-256: the padding differs, and crypto/keccak256
// exists as its own package in the gno stdlib for exactly that reason.
func expandMessageXMD(msg, dst []byte, n int) []byte {
	return expandMessageXMDWith(keccak256.Sum256, keccakBlockSize, msg, dst, n)
}

// expandMessageXMDSHA256 is expand_message_xmd with H = SHA-256. It exists so
// the tests can replay RFC 9380 appendix K.1, and is deliberately not used by
// any verification path.
func expandMessageXMDSHA256(msg, dst []byte, n int) []byte {
	return expandMessageXMDWith(sha256.Sum256, sha256BlockSize, msg, dst, n)
}

// DrandRoundMessage returns the message drand's bls-bn254-unchained-on-g1
// scheme signs for a round: keccak256 of the round number as a big-endian
// uint64. That is drand v2.1.7's DigestBeacon for this scheme, verbatim.
//
// The chain is *unchained*: the previous round's signature is not part of the
// message, so any round can be verified on its own.
//
// Returns nil for a negative round. drand round numbers are uint64 and start at
// 1; a negative value is a caller bug, and silently reinterpreting it as a huge
// unsigned round would produce a message for a round nobody will ever sign.
// Round 0 is encoded normally -- it is a well-defined byte string -- but no
// signature exists for it, so verification will simply fail.
func DrandRoundMessage(round int64) []byte {
	if round < 0 {
		return nil
	}
	u := uint64(round)
	b := []byte{
		byte(u >> 56), byte(u >> 48), byte(u >> 40), byte(u >> 32),
		byte(u >> 24), byte(u >> 16), byte(u >> 8), byte(u),
	}
	h := keccak256.Sum256(b)
	return h[:]
}

drandverify.gno

package bls254

// BLS verification for drand's bls-bn254-unchained-on-g1 beacon.
//
// The pairing equation is the same one the existing SPLASH Verify uses --
// signatures in G1, public keys in G2, e(sig, G2gen) * e(-H(m), pk) == 1 -- so
// the only thing that differs is how H(m) is built. That is not a small
// difference: see drandcurve.gno.
//
// The G2 generator is shared, and that is not an assumption. drand/kyber
// v1.3.2's twistGen, decoded from its Montgomery form and written in EIP-197
// imaginary-first order (x_imag|x_real|y_imag|y_real), is byte-for-byte the
// g2GenHex constant already in bls254.gno. The published evmnet group key is
// sk*twistGen for the DKG's collective secret, so pairing against g2GenBytes is
// correct for this chain.

import "crypto/bn254"

// verifyPairingG1SigG2Key reports whether e(sig, G2gen) == e(h, pubkey), for a
// 64-byte G1 signature, a 64-byte G1 message point and a 128-byte G2 key in
// EIP-197 wire order.
//
// This DUPLICATES the tail of Verify rather than refactoring Verify to call it.
// The brief allowed either and asked which and why: the live SPLASH beacon
// depends on Verify, the instruction I was given was not to alter an existing
// exported function, and a behaviour-preserving refactor is still an edit to
// code that is in production. Twelve duplicated lines are the cheaper risk.
//
// The duplication is pinned against drift by
// TestVerifyPairingHelperMatchesVerify, which asserts this helper and Verify
// return the same answer for every vector and every reject-vector of the
// existing SPLASH suite. If someone edits one and not the other, that test
// fails.
func verifyPairingG1SigG2Key(pubkey, h, sig []byte) bool {
	if len(pubkey) != 128 || len(sig) != 64 || len(h) != 64 {
		return false
	}
	negH := negateG1(h)
	if negH == nil {
		return false
	}

	in := make([]byte, 0, 2*bn254.PairingChunkSize)
	in = append(in, sig...)
	in = append(in, g2GenBytes...)
	in = append(in, negH...)
	in = append(in, pubkey...)
	if len(in) != 2*bn254.PairingChunkSize {
		return false
	}

	out := bn254.PairingCheck(in)
	// PairingCheck returns an empty NON-NIL slice on an invalid point or an
	// unreduced coordinate; checking length (not nilness) is load-bearing.
	if len(out) != bn254.PairingOutputSize {
		return false
	}
	return out[len(out)-1] == 1
}

// VerifyDrand reports whether sig is the drand beacon signature for round under
// pubKey, for the bls-bn254-unchained-on-g1 scheme (drand's "evmnet" chain,
// hash 04f1e9062b8a81f848fded9c12306733282b2727ecced50032187751166ec8c3).
//
// pubKey is the 128-byte G2 group public key in EIP-197 wire order
// (x_imag|x_real|y_imag|y_real), which is exactly the byte string the drand
// /info endpoint serves as "public_key". sig is the 64-byte G1 signature from
// /public/<round>. The chain is unchained, so no previous signature is needed.
//
// The randomness for a verified round is sha256(sig) -- the same derivation
// r/splash/beacon already uses. This function deliberately does not compute it:
// verifying and deriving are separate steps and a caller that conflates them
// tends to derive from an unverified signature.
//
// VerifyDrand is total. It never panics, and returns false for every malformed
// input: wrong pubKey or sig length, a negative round, a signature coordinate at
// or above p, an off-curve point, and an invalid precompile result.
//
// This is NOT Verify. Verify implements the SPLASH beacon's own scheme
// (chainID || "|" || decimal(round), SHA-256, try-and-increment hash-to-G1) and
// will reject every real drand signature; VerifyDrand will reject every SPLASH
// one. Pick by which beacon produced the signature, never by which is to hand.
func VerifyDrand(pubKey []byte, round int64, sig []byte) bool {
	if len(pubKey) != 128 || len(sig) != 64 {
		return false
	}
	// Reject unreduced signature coordinates explicitly. bn254.PairingCheck
	// would also reject them, but relying on a native's error behaviour for a
	// validity rule the caller can violate is how that rule stops being checked.
	if cmp(toLimbs(sig[0:32]), pLimbs) >= 0 || cmp(toLimbs(sig[32:64]), pLimbs) >= 0 {
		return false
	}

	msg := DrandRoundMessage(round)
	if msg == nil {
		return false // negative round
	}
	h := HashToG1Drand(msg)
	if h == nil {
		return false
	}
	return verifyPairingG1SigG2Key(pubKey, h, sig)
}

fieldmul.gno

package bls254

// Field multiplication mod P. TWO implementations, and this header records which
// one the drand path uses and the measurement that decided it. PHASE 2 SETTLED
// THIS; please do not re-litigate it from a gas table that came from somewhere
// else, because that is exactly how it went wrong the first time.
//
// The rest of this package gets away with crypto/modexp for every field
// operation it needs, because try-and-increment hash-to-G1 only ever needs
// powers (x^3, sqrt) and one addition. The RFC 9380 SVDW map that the drand
// path needs (see drandcurve.gno) is different: it needs about a dozen general
// products a*b per field element mapped, and modexp cannot multiply two
// distinct operands.
//
// Two ways out:
//
//  1. The identity a*b == ((a+b)^2 - (a-b)^2) / 4, which crypto/modexp can do
//     because it can square. Two native modexp calls, one modular subtraction and
//     a division by 4, which mod P is two halvings and not a third multiply.
//     Implemented below as mulModPIdentity / mulModPLimbs.
//  2. A hand-rolled 4-limb Montgomery multiply over math/bits.Mul64. No native
//     call, 32 64x64 multiplies per montMul. Implemented below as mulModP.
//
// (1) WINS, AND IT IS WHAT drandcurve.gno's fpMul AND fpSqr BIND TO.
//
// Measured on this toolchain (/home/johnny/go/bin/gno, gno v1.2.0 stdlibs) from
// gno test's own per-test GAS line, 100 iterations per test with the 349,766-gas
// empty-test baseline subtracted. The tests are in drandgas_test.gno; re-run them
// rather than trusting these numbers.
//
//	operation                                    gas each
//	mulModP          4-limb Montgomery          2,200,369
//	mulModPIdentity  identity, byte domain        519,791   <- 4.23x cheaper
//	mulModPLimbs     identity, limb domain        387,943
//	sqrModP          Montgomery a*a             2,200,184
//	sqrModPNative    one native modexp             69,602   <- 31.6x cheaper
//	modexp.ModExp(x, 2, P) bare                    23,145
//	modexp.ModExp(x, (P+1)/4, P) bare             134,372
//	toLimbs / fromLimbs                    39,328 / 42,308
//	halveModP                                      21,035
//
// End to end, net of the same baseline:
//
//	                        Montgomery      identity      factor
//	VerifyDrandOnce         63,846,571    13,396,451       4.77x
//	VerifyDrandFour / 4     68,401,101    15,106,773       4.53x
//	HashToG1DrandOnce       62,394,145    12,004,207       5.20x
//	MapToPointSVDWOnce      35,797,798     6,657,484       5.38x
//	r/splash/beacon Publish 74,891,351    16,671,000*      4.49x
//
// THE IDENTITY COLUMN ROSE ON 2026-09-29 AND THE REASON IS ONE LINE OF CODE, NOT DRIFT.
// mulModPLimbs gained the input guard AUDIT-2026-09-28.md finding 21 asked for -- two
// cmp calls against pLimbs, measured at 8,500 gas the pair -- so every multiply costs
// 8,500 more and the end-to-end figures rise by 8,500 times the number of multiplies
// they perform (16 in VerifyDrandOnce, 9 in the SVDW map). VerifyDrand is up 1.0 %.
// The previous figures were 511,291 / 379,443 / 13,260,451 / 14,964,398 / 11,868,207 /
// 6,580,984, and they are recorded here rather than silently replaced so that a reader
// who remembers them learns why they moved. mulModP, sqrModP and sqrModPNative are
// unchanged because the guard is not on their path.
//
// *THE Publish ROW IS DERIVED, NOT RE-ISOLATED, and it is the only number in this file
// that is. A Publish is its own fixed cost plus exactly one VerifyDrand, so it rises by
// the same 136,000; r/splash/beacon's own suite has no single-Publish gas test to read
// it off, and this change may not touch that realm. Re-isolate it there before quoting
// it as measured.
//
// WHY THE ORIGINAL CHOICE WENT THE OTHER WAY. (2) was specified on the strength of
// a gas table reading "modexp: Base 58000 + 24647680*len(mod)/1024", which would
// have made a modexp call cost ~800k. That table is from a different gno revision
// -- this host has two pinned toolchains, and it was read off GnoBuilder's
// c4c72fdd instead of SPLASH's v1.2.0. On v1.2.0 the crypto/modexp row is Base
// 1400, Slope 2200 on SizeModExpWork (a count of modular multiplications) and
// Slope2 3500 per 1024 bytes of modulus: a 254-bit squaring costs 23k, not 800k.
// Interpreted 64-bit limb arithmetic is the expensive thing here, not the native
// call. If you are about to change this back, measure on the toolchain you will
// deploy with first.
//
// MONTGOMERY IS KEPT, NOT DEAD CODE. mulModP is the independent oracle that
// TestMulModPIdentityMatchesMontgomery compares the identity multiply against:
// two implementations sharing no arithmetic, checked byte-for-byte over every
// ordered pair of 15 limb-boundary edge values, the python-derived vector table,
// 120 in-VM pseudorandom pairs and all 11 rejection cases, with the tally
// asserting that a+b wrapping, a-b going negative and both halvings' odd and even
// branches were each actually reached. Deleting mulModP would delete that oracle.
//
// WHAT IS STILL ON THE TABLE, measured rather than guessed. The multiply is now
// dominated by byte<->limb marshalling, not arithmetic: mulModPLimbs is 387,943
// against mulModPIdentity's 519,791, purely because the caller holds limbs. Moving
// mapToPointSVDW itself into the limb domain would save ~132k on each of its ~8
// products and ~120k on each of its ~6 additions, but would cost ~34k on each of
// its ~5 squarings (a squaring is cheapest in the byte domain, where it is one
// bare modexp) and ~42-81k on each of its 3 full exponentiations. Net estimate
// ~1.4M off a 6.66M map, so VerifyDrand ~13.40M -> ~10.5M: a further 21% for a
// rewrite of the most correctness-critical function in the package. Not taken.
//
// AND SUCH A REWRITE WOULD BE THE FIRST REAL LIMB-DOMAIN CALLER OF mulModPLimbs, which
// is precisely who finding 21's guard is for: the byte-domain wrappers would no longer
// be standing between the SVDW map and the unreduced-operand case.
// 0.0165 GNOT a relay is already 4.5x inside the budget that prompted this work.
//
// One cheap, safe win was left on the table deliberately: inlining mac into the
// two loops below measured 360k instead of 503k gas for mul512, a 28% saving.
// mul512 is now off the hot path entirely -- it is only reached through the
// oracle -- so readability of the reduction loop wins outright and mac stays a
// function.
//
// Everything here is unexported. mulModP, mulModPIdentity and sqrModPNative all
// take and return 32-byte big-endian slices, matching modexp and the point
// encodings used everywhere else in this package, and all three return nil for an
// operand that is not exactly 32 bytes or is >= P.

import (
	"crypto/modexp"
	"math/bits"
)

const (
	// pInvNeg64 is -P^{-1} mod 2^64, the Montgomery reduction constant.
	//
	// Derived, not recalled:
	//   python3 -c "p=0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47;
	//               print(hex((-pow(p,-1,1<<256)) % (1<<64)))"
	//   -> 0x87d20782e4866389
	// TestMontgomeryConstants re-derives it inside the VM from pLimbs alone,
	// so a typo here fails the test suite rather than silently producing
	// wrong products.
	pInvNeg64 = 0x87d20782e4866389

	// r2Hex is R^2 mod P where R = 2^256, i.e. 2^512 mod P. montMul(x, r2)
	// converts x into Montgomery form; montMul(x, 1) converts back.
	//
	//   python3 -c "p=0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47;
	//               print('%064x' % pow(2,512,p))"
	r2Hex = "06d89f71cab8351f47ab1eff0a417ff6b5e71911d44501fbf32cfc5b538afa89"
)

var r2Limbs = toLimbs(mustDecodeHex(r2Hex))

// mac returns the 128-bit a*b + c + carryIn as (hi, lo).
//
// It cannot overflow: a*b <= (2^64-1)^2 = 2^128 - 2^65 + 1, so hi <= 2^64 - 2
// and the two carries that can come out of the low word still leave hi below
// 2^64.
func mac(a, b, c, carryIn uint64) (hi, lo uint64) {
	hi, lo = bits.Mul64(a, b)
	var c1 uint64
	lo, c1 = bits.Add64(lo, c, 0)
	hi, _ = bits.Add64(hi, 0, c1)
	lo, c1 = bits.Add64(lo, carryIn, 0)
	hi, _ = bits.Add64(hi, 0, c1)
	return hi, lo
}

// mul512 is the schoolbook 4x4 -> 8 limb product. Limbs are little-endian
// (index 0 least significant), matching toLimbs.
func mul512(a, b [4]uint64) [8]uint64 {
	var t [8]uint64
	for i := 0; i < 4; i++ {
		var carry uint64
		for j := 0; j < 4; j++ {
			carry, t[i+j] = mac(a[j], b[i], t[i+j], carry)
		}
		// t[i+4] has not been written by any earlier i, so this is an
		// assignment rather than an add.
		t[i+4] = carry
	}
	return t
}

// montReduce returns t * R^{-1} mod P for t < P*R, by separated-operand-scanning
// Montgomery reduction.
func montReduce(t [8]uint64) [4]uint64 {
	// hi9 is the notional ninth limb. The loop can carry past t[7] because
	// t + m_i*P*2^(64i) can exceed 2^512 even though the final quotient does
	// not; see the note on the return value below.
	var hi9 uint64

	for i := 0; i < 4; i++ {
		m := t[i] * pInvNeg64
		var carry uint64
		for j := 0; j < 4; j++ {
			carry, t[i+j] = mac(m, pLimbs[j], t[i+j], carry)
		}
		// t[i] is now zero by construction. Propagate the high carry.
		for k := i + 4; k < 8 && carry != 0; k++ {
			t[k], carry = bits.Add64(t[k], carry, 0)
		}
		hi9 += carry
	}

	r := [4]uint64{t[4], t[5], t[6], t[7]}

	// For a, b < P the input to this function is a*b < P^2 < P*R, so the
	// quotient is below P + P^2/R < 2P. P < 2^254, so 2P < 2^255 and hi9 is
	// necessarily zero. Fold it into the reduction condition anyway: if a
	// caller ever feeds an unreduced operand the answer stays in range for
	// the single subtraction below instead of silently losing 2^256.
	if hi9 != 0 || cmp(r, pLimbs) >= 0 {
		r = sub(r, pLimbs)
	}
	return r
}

// montMul returns a*b*R^{-1} mod P for a, b reduced mod P.
func montMul(a, b [4]uint64) [4]uint64 {
	return montReduce(mul512(a, b))
}

// mulModP returns (a*b) mod P. a and b must be 32-byte big-endian values below
// P; the result is 32 bytes big-endian. Returns nil if either input is not
// exactly 32 bytes or is >= P -- an unreduced operand is a caller bug, and
// returning a plausible-looking wrong product for it is the one outcome this
// package cannot afford.
func mulModP(a, b []byte) []byte {
	if len(a) != 32 || len(b) != 32 {
		return nil
	}
	al := toLimbs(a)
	bl := toLimbs(b)
	if cmp(al, pLimbs) >= 0 || cmp(bl, pLimbs) >= 0 {
		return nil
	}
	// montMul(a, b) = a*b*R^{-1}; multiplying that by R^2 gives a*b.
	return fromLimbs(montMul(montMul(al, bl), r2Limbs))
}

// sqrModP returns (a*a) mod P, with the same contract as mulModP.
func sqrModP(a []byte) []byte { return mulModP(a, a) }

// ---- Approach (1): the squaring identity, via native crypto/modexp ----
//
// This is the alternative the header calls the easier one. It is here because it
// is also, measured on this toolchain, the much cheaper one -- see the table at
// the bottom of this file.
//
//	a*b == ((a+b)^2 - (a-b)^2) / 4    (mod P)
//
// The identity is exact over the integers: (a+b)^2 - (a-b)^2 = 4ab. Reducing
// a+b and a-b mod P first does not change their squares mod P, so the numerator
// is congruent to 4ab and the division by 4 -- which mod P means multiplying by
// the inverse of 4, i.e. halving twice -- recovers ab.

// halveModP returns (x / 2) mod P, i.e. x * inverse(2) mod P, for x reduced mod P.
//
// P is odd, so inverse(2) exists. If x is even the integer x/2 is already the
// answer. If x is odd then x+P is even and (x+P)/2 is the answer, because
// 2*((x+P)/2) = x+P == x (mod P).
//
// No overflow: P < 2^254 and x < P, so x+P < 2^255. The carry out of add is
// therefore always zero; it is folded into the shift anyway so that an unreduced
// input cannot silently lose the top bit.
func halveModP(x [4]uint64) [4]uint64 {
	var carry uint64
	if x[0]&1 == 1 {
		x, carry = add(x, pLimbs)
	}
	// Shift right by one, pulling in carry as bit 256.
	var r [4]uint64
	r[0] = x[0]>>1 | x[1]<<63
	r[1] = x[1]>>1 | x[2]<<63
	r[2] = x[2]>>1 | x[3]<<63
	r[3] = x[3]>>1 | carry<<63
	return r
}

// sqrModPNative returns (a*a) mod P using one native modexp, with exactly
// mulModP's input contract: nil unless a is 32 bytes and below P.
//
// modexp.ModExp returns len(modulus) == 32 bytes, left-padded, so the result
// needs no adjustment.
func sqrModPNative(a []byte) []byte {
	if len(a) != 32 {
		return nil
	}
	if cmp(toLimbs(a), pLimbs) >= 0 {
		return nil
	}
	return modexp.ModExp(a, twoBytes, pBytes)
}

// twoBytes is the exponent 2. A one-byte exponent is what modexp's gas row
// charges least for.
var twoBytes = []byte{2}

// mulModPIdentity returns (a*b) mod P via the squaring identity above. Its
// contract is identical to mulModP's, including returning nil for a non-32-byte
// or unreduced operand: TestMulModPIdentityMatchesMontgomery pins the two
// functions to agreeing on every input, rejections included.
func mulModPIdentity(a, b []byte) []byte {
	if len(a) != 32 || len(b) != 32 {
		return nil
	}
	al := toLimbs(a)
	bl := toLimbs(b)
	if cmp(al, pLimbs) >= 0 || cmp(bl, pLimbs) >= 0 {
		return nil
	}

	return fromLimbs(mulModPLimbs(al, bl))
}

// mulModPLimbs is the identity multiply in the limb domain, for callers that
// already hold reduced limbs and want reduced limbs back. Both operands MUST be
// below P, AND SINCE 2026-09-29 THAT IS CHECKED HERE RATHER THAN ASSUMED.
//
// THE DEFECT THAT PUT THE CHECK IN, AUDIT-2026-09-28.md finding 21. This comment used
// to read "there is no check, because the byte-domain wrappers do it and the SVDW map
// only ever feeds it values it has already reduced". Both halves of that were true, and
// the function was still THE ONLY PRODUCER IN THIS PACKAGE THAT WAS NOT FAIL-CLOSED.
// Fed an unreduced b with b > a + P, subModP's `a < b` branch computes a + (P - b), and
// P - b wraps mod 2^256 because b > P -- so the result is NOT congruent to a - b, the
// numerator is not congruent to 4ab, and the function returns A PLAUSIBLE-LOOKING WRONG
// PRODUCT. This package's own header calls that the one outcome it cannot afford: every
// other entry point returns nil rather than a value that is merely probably right.
// mulModP, mulModPIdentity and sqrModPNative all check; this did not.
//
// IT IS A PANIC AND NOT A nil BECAUSE THE RETURN TYPE HAS NO nil. [4]uint64 has no
// invalid value to hand back, and its zero value is a legitimate product, so the only
// fail-closed answer available is to stop. That is the choice hashToFieldDrand and
// hash_to_g1 already make for their own impossible states.
//
// IT IS UNREACHABLE TODAY AND THE GUARD IS THEREFORE A CONTINGENCY, NOT A FIX TO A LIVE
// BUG: the only non-test caller is mulModPIdentity, which performs exactly this
// comparison on the same values first, and drandcurve.gno's fpMul and fpSqr still bind
// to the input-checked mulModPIdentity and sqrModPNative. NOTHING ON THE LIVE PATH
// CHANGED, and the measured cost of the redundant pair of cmp calls is in the header's
// table. What changed is that a FUTURE caller in the limb domain -- which is the whole
// reason this function is factored out at all -- cannot silently get a wrong answer.
//
// This exists because the byte<->limb conversions, not the arithmetic, are what
// this multiply actually costs. toLimbs and fromLimbs measure ~53k and ~58k gas
// each (see drandgas_test.gno); the byte-domain wrapper pays five conversions,
// this core pays the four that the modexp boundary makes unavoidable.
func mulModPLimbs(al, bl [4]uint64) [4]uint64 {
	if cmp(al, pLimbs) >= 0 || cmp(bl, pLimbs) >= 0 {
		panic("bls254: mulModPLimbs: operand is not reduced mod P")
	}

	// s = (a+b) mod P, d = (a-b) mod P. addModP handles the carry out of a+b
	// exceeding P; subModP handles a < b by adding P back.
	s := fromLimbs(addModP(al, bl, pLimbs))
	d := fromLimbs(subModP(al, bl))

	// Two native squarings. Both operands are already reduced.
	s2 := modexp.ModExp(s, twoBytes, pBytes)
	d2 := modexp.ModExp(d, twoBytes, pBytes)

	// n == 4ab (mod P); halve twice to divide by 4.
	n := subModP(toLimbs(s2), toLimbs(d2))
	return halveModP(halveModP(n))
}

// subModP returns (a - b) mod P for a, b reduced mod P.
//
// THE PRECONDITION IS LOAD-BEARING AND IS WHERE FINDING 21 ACTUALLY LIVED. On the
// `a < b` branch it computes a + (P - b), and sub() wraps mod 2^256: so for b > P the
// term P - b is a huge wrong number and the result is not congruent to a - b. There is
// no way to detect that from inside this function -- every [4]uint64 is a valid return
// value -- so the contract is enforced by its callers, and mulModPLimbs states it as a
// panic rather than assuming it.
func subModP(a, b [4]uint64) [4]uint64 {
	if cmp(a, b) >= 0 {
		return sub(a, b)
	}
	// a < b: a - b + P, computed as a + (P - b). P - b is in [1, P] and a is
	// below b <= P-1, so the sum is below P and no carry escapes.
	d, _ := add(a, sub(pLimbs, b))
	return d
}

// negModP returns (-a) mod P for a reduced mod P.
func negModP(a [4]uint64) [4]uint64 {
	var zero [4]uint64
	if cmp(a, zero) == 0 {
		return zero
	}
	return sub(pLimbs, a)
}

gnomod.toml

module = "gno.land/p/g1r4aw43kagaaquhegxw6xr346h9f2qu2ezf0jar/bls254"
gno = "0.9"

[addpkg]
  creator = "g1r4aw43kagaaquhegxw6xr346h9f2qu2ezf0jar"
  height = 232643
  max_deposit = "100000000ugnot"