Assessment reports>Session Token>Discussion>Gas savings

Gas savings

In the FQ2Sqrt function of BN256G2, a square root computation in the base field can be saved. If the number has no imaginary part (i.e., x2 == 0) and the number is not a square, then the second square root computation _sqrt(FIELD_MODULUS - x1) is not necessary as it will return the same value t1 as for the previous square root computation.

In , the square root of is computed with

and we have this:

If is not a square, it means from the Legendre symbol that

So in , we have this:

And as explained before, the square root of in is if is not a square in .

Thus, the code can be replaced by the following:

// if x.b is zero
if (x2 == 0) {
    // Fp::squareRoot(t1, x.a)
    (t1, has_root) = _sqrt(x1);

    // if sqrt exists
    if (has_root) {
        return (t1, 0); // y.a = t1, y.b = 0
    } else {
        return (0, t1); // y.a = 0, y.b = t1
    }
}

It saves the gas of computing a second square root in the base field.

Another possible gas-saving measure is in ECTwistMul. There is no need to compute the scalar multiplication in case of the point at infinity; the point at infinity can be returned directly. Similarly, if the scalar is zero, there is no need to compute the multiplication.

Session team implemented the suggested changes for the square root computation in .

Zellic © 2024Back to top ↑