Files
math/poly/poly_test.go
T
Hanzo AI e018a9c3d1 LP-107 Phase 2: math substrate — params, backend, codec, modarith,
ntt, poly, rns, sample

Eight pure-Go reference packages that own the canonical semantics of
every cryptographic-math primitive Lux protocols share. Backends
(AVX2 / NEON / cgo+C++ / CUDA / Metal / WGSL) plug in behind the
substrate; KATs gate byte-equality across them.

Packages added:

* params/    — ModulusID, NTTParamID, FHEParamID, PulsarParamID,
               HashSuiteID, BackendID; KATHeader required-fields
               schema. Stable string IDs; renaming is a breaking
               change.

* backend/   — Policy enum (PureGo / NativeCPU / GPUPreferred /
               GPURequired); Resolve(policy, registered) returns the
               BackendID per LP-107's fallback chain. GPURequired
               returns ErrUnavailable when no GPU backend is
               registered.

* codec/     — Bounded readers (closes lattice issues #2 + #4 DoS
               class permanently). Limits + LimitError + Reader.
               ReadUint{16,32,64}Slice all reject the 70T-element
               attack input before allocating; depth + frame-bytes
               caps; iterative (no recursion). Regression test
               TestReadUint64Slice_RejectsHugeLength encodes the
               original lattice issue #4 input.

* modarith/  — Modulus type with QInv, R2, Barrett constants
               (computed via math/big once per modulus). AddMod /
               SubMod / MulMod (Div64 reference path). MontMulMod /
               ToMontgomery / FromMontgomery cross-checked against
               MulMod across 100 random Pulsar-Q pairs.
               ReductionMode enum byte-equal to lattice/types.

* ntt/       — Service + Backend interface; pure-Go backend
               delegates to lattice/v7/ring.SubRing.NTT/INTT (the
               canonical Lattigo-derived Montgomery NTT body — no
               re-implementation, just dispatch). Round-trip +
               batch + determinism tests on Pulsar N=256.

* poly/      — Add / Sub / ScalarMul / PointwiseMul (NTT-domain) /
               negacyclic Mul (NTT round-trip). Composes modarith +
               ntt; no lower-level reach.

* rns/       — Basis(Moduli, Name) for FHE RNS chains. Single +
               two-prime construction validated; rejects even moduli.
               Phase 3 will add basis-extension and modulus-switching.

* sample/    — Uniform (rejection sampling, mask-and-retry); Ternary
               (density + sign byte); CenteredBinomial (popcount
               difference); DiscreteGaussianRejection (6-sigma cutoff).
               All take an io.Reader so callers can KAT-replay.

Architecture invariants enforced in package docs:

  - Go is the canonical semantic reference.
  - Backend selection MUST NOT alter transcript bytes (consensus
    paths default to PolicyPureGo / PolicyNativeCPU).
  - No unbounded codec readers anywhere near wire formats.
  - No re-implementation: where lattice/v7/ring already owns the
    canonical body, we delegate, not fork.
  - One ID space; renaming is a breaking change.

Test posture: 8/8 packages green via `GOWORK=off go test ./...`.

Phases 3-7 (queued):
  3. lattice consumes math
  4. pulsar consumes lattice + math
  5. fhe consumes math
  6. luxcpp/crypto/math native backend mirror
  7. cross-runtime KAT release gate

See SUBSTRATE.md for the full posture and migration plan; full LP at
~/work/lux/lps/LP-107-lux-math-substrate.md.
2026-05-04 09:28:23 -07:00

92 lines
2.0 KiB
Go

// Copyright (c) 2026 Lux Industries Inc.
// SPDX-License-Identifier: BSD-3-Clause
package poly
import (
"math/rand/v2"
"testing"
"github.com/luxfi/math/backend"
"github.com/luxfi/math/ntt"
"github.com/luxfi/math/params"
)
const PulsarQ = uint64(0x1000000004A01)
var pulsarParams = &ntt.Params{
N: 256,
Q: PulsarQ,
ID: params.NTTPulsarN256,
}
func TestAddSub_RoundTrip(t *testing.T) {
N := 256
a := make([]uint64, N)
b := make([]uint64, N)
r := rand.New(rand.NewPCG(0xdead, 0))
for i := range a {
a[i] = r.Uint64() % PulsarQ
b[i] = r.Uint64() % PulsarQ
}
sum := make([]uint64, N)
if err := Add(sum, a, b, PulsarQ); err != nil {
t.Fatalf("Add: %v", err)
}
got := make([]uint64, N)
if err := Sub(got, sum, b, PulsarQ); err != nil {
t.Fatalf("Sub: %v", err)
}
for i := range a {
if got[i] != a[i] {
t.Fatalf("[%d]: got %d, want %d", i, got[i], a[i])
}
}
}
func TestScalarMul(t *testing.T) {
N := 256
a := make([]uint64, N)
for i := range a {
a[i] = uint64(i + 1)
}
dst := make([]uint64, N)
if err := ScalarMul(dst, a, 7, PulsarQ); err != nil {
t.Fatalf("ScalarMul: %v", err)
}
for i := range a {
want := (uint64(i+1) * 7) % PulsarQ
if dst[i] != want {
t.Errorf("[%d]: got %d, want %d", i, dst[i], want)
}
}
}
func TestMul_NegacyclicVsBigInt(t *testing.T) {
// Verify a * b mod (X^N + 1) for small constants using package
// ntt's pure-Go backend, then sanity-check against a hand-computed
// expectation.
svc, err := ntt.NewService(pulsarParams, backend.PolicyPureGo)
if err != nil {
t.Fatalf("ntt.NewService: %v", err)
}
N := int(pulsarParams.N)
a := make([]uint64, N)
b := make([]uint64, N)
a[0] = 2
b[0] = 3
dst := make([]uint64, N)
if err := Mul(dst, a, b, svc); err != nil {
t.Fatalf("Mul: %v", err)
}
// (2)*(3) = 6 in coefficient 0; everything else 0.
if dst[0] != 6 {
t.Errorf("dst[0] = %d, want 6", dst[0])
}
for i := 1; i < N; i++ {
if dst[i] != 0 {
t.Errorf("dst[%d] = %d, want 0", i, dst[i])
}
}
}