ethereum / py_ecc

Python implementation of ECC pairing and bn_128 and bls12_381 curve operations
MIT License
183 stars 82 forks source link

Segmentation fault when using multiply #127

Open Popeyef5 opened 2 years ago

Popeyef5 commented 2 years ago

What is wrong?

'Segmentation fault (core dumped)' error when doing

multiply(G1, -1)

On bn128. Happened with the few other negative numbers I tried. Did not try with other curves, I assume the problem persists because -1 // 2 = -1 and the recursive nature of the multiply function.

How can it be fixed

This fixes it:

def multiply(pt: Point2D[Field], n: int) -> Point2D[Field]:
    m = abs(n)
    if m == 0:
        ret = None
    elif m == 1:
        ret = pt
    elif not m % 2:
        ret = multiply(double(pt), m // 2)
    else:
        ret = add(multiply(double(pt), int(m // 2)), pt)
    if n < 0:
        ret = neg(ret)
    return ret

alternatively this should work as well but might be less efficient:

def multiply(pt: Point2D[Field], n: int) -> Point2D[Field]:
    n = n % field_modulus
   # rest of the function still the same

Could write up a quick PR if this indeed works.