protolambda / go-kzg

FFT, data-recovery and KZG commitments, a.k.a. Kate commitments, in Go - *super experimental*
MIT License
90 stars 26 forks source link

BLST support #13

Closed protolambda closed 1 year ago

protolambda commented 3 years ago

WARNING: work in progress. Known memory leak.

Requires BLST Go bindings patch (the current bindings are very restricted):

type Scalar = C.blst_scalar
type Fr = C.blst_fr

func (s *Scalar) FromFr(a *Fr) {
    C.blst_scalar_from_fr(s, a)
}

func (fr *Fr) FromScalar(a *Scalar) {
    C.blst_fr_from_scalar(fr, a)
}

func (fr *Fr) Add(a *Fr, b *Fr) {
    C.blst_fr_add(fr, a, b)
}

func (fr *Fr) Sub(a *Fr, b *Fr) {
    C.blst_fr_sub(fr, a, b)
}

func (fr *Fr) Mul(a *Fr, b *Fr) {
    C.blst_fr_mul(fr, a, b)
}

func (fr *Fr) Sqr(a *Fr) {
    C.blst_fr_sqr(fr, a)
}

func (fr *Fr) EuclInverse(a *Fr) {
    C.blst_fr_eucl_inverse(fr, a)
}

func (p1 *P1) Negative() {
    C.blst_p1_cneg(p1, true)
}

func (p2 *P2) Negative() {
    C.blst_p2_cneg(p2, true)
}

func (p1 *P1) Add(a *P1, b *P1) {
    C.blst_p1_add(p1, a, b)
}

func (p2 *P2) Add(a *P2, b *P2) {
    C.blst_p2_add(p2, a, b)
}

func (p1 *P1) Mult(a *P1, b *Scalar, nbits uint) {
    C.blst_p1_mult(p1, a, &b.b[0], C.size_t(nbits))
}

func (p2 *P2) Mult(a *P2, b *Scalar, nbits uint) {
    C.blst_p2_mult(p2, a, &b.b[0], C.size_t(nbits))
}

// Tests whether e(a1, a2) == e(b1, b2)
func PairingsVerify(a1 *P1, a2 *P2, b1 *P1, b2 *P2) bool {
    var loop0, loop1, gt_point Fp12
    var aa1, bb1 P1Affine
    var aa2, bb2 P2Affine

    a1neg := *a1
    C.blst_p1_cneg(&a1neg, true)

    C.blst_p1_to_affine(&aa1, &a1neg)
    C.blst_p1_to_affine(&bb1, b1)
    C.blst_p2_to_affine(&aa2, a2)
    C.blst_p2_to_affine(&bb2, b2)

    C.blst_miller_loop(&loop0, &aa2, &aa1)
    C.blst_miller_loop(&loop1, &bb2, &bb1)

    C.blst_fp12_mul(&gt_point, &loop0, &loop1)
    C.blst_final_exp(&gt_point, &gt_point)

    return bool(C.blst_fp12_is_one(&gt_point))
}

func GenP1() *P1 {
    return (*P1)(C.blst_p1_generator())
}

func GenP2() *P2 {
    return (*P2)(C.blst_p2_generator())
}
protolambda commented 1 year ago

c-kzg is the way forward to use BLST. See original: https://github.com/benjaminion/c-kzg and new https://github.com/ethereum/c-kzg-4844