Post
Topic
Board Development & Technical Discussion
Re: What algorithm is this ?
by
ymgve2
on 06/02/2023, 16:41:56 UTC
Do NOT use ChatGPT for crypto code, FFS... That snippet is like 10% of the code required to do point addition. This is the code I used some years ago (slow, but readable)

Code:
def modinv(x, n):
    return pow(x, n-2, n)

class Point(object):
    def __init__(self, x, y, inf=False):
        self.x = x
        self.y = y
        self.inf = inf

def curve_add(p, q, N):
    if p.inf:
        return q
       
    if q.inf:
        return p
   
    if p.x == q.x:
        if p.y == q.y:
            d1 = (3 * p.x * p.x) % N
            d2 = (2 * p.y) % N
        else:
            return Point(-1, -1, True)
    else:
        d1 = (q.y - p.y) % N
        d2 = (q.x - p.x) % N

    d2i = modinv(d2, N)
    d = (d1 * d2i) % N
       
    resx = (d * d - p.x - q.x) % N
    resy = (d * (p.x - resx) - p.y) % N
   
    return Point(resx, resy)

def scalar_mul(scalar, p, N):
    t = p
    res = None
    while scalar != 0:
        if scalar & 1 == 1:
            if res is None:
                res = t
            else:
                res = curve_add(res, t, N)
       
        t = curve_add(t, t, N)
       
        scalar = scalar >> 1
       
    return res


The modular inversion can be implemented in a lot of different ways, but as I recall not in any parallel ways. But it is also not a "search".

The way you parallelize these kinds of searches is to work with several different private key starting points in parallel, not trying to do several things at once at the low level. A fast FPGA implementation would have multiples of these curve adders alongside each other, each set up to work on different inputs.

(As an aside, the modular inversion is by far the slowest part of the process, so most speed focused code use a trick - if you want to find the inverse of A and B, you can calculate the inverse I=1/(A*B), then the inverse of A becomes B*I and the inverse of B becomes A*I - this can be extended to calculate the inverse of any number of integers with only a single inversion)