jimmysong / programmingbitcoin

Repository for the book
Other
1.75k stars 656 forks source link

rmul method inside FieldElement Class to be added before completing ex 4 chapter 3 #261

Open enricobottazzi opened 2 years ago

enricobottazzi commented 2 years ago

In order to complete Exercise 4 chapter 3, it is necessary to execute a call the self == other exception in point addition. This will likely return you an error

  File "/Users/enricobottazzi/Documents/GitHub/ec-primer-rust/ec.py", line 47, in __add__
    s = (3 * self.x**2 + self.a) / (2 * self.y)
TypeError: unsupported operand type(s) for *: 'int' and 'FieldElement'

The way to avoid this error you need ti add the __rmul__ method inside the FieldElement Class as implemented here => https://github.com/jimmysong/programmingbitcoin/blob/master/code-ch03/ecc.py#L75

The problem is that this method is never explained nor mentioned inside the book.

plebiolira commented 2 years ago

Hi Enrico,

I ran into the same issue last night.

Instead of implementing __rmul__ to FieldElement, I updated the __add__ method on class Point to the following.

From

if self == other:
        s = (3 * self.x**2 + self.a) / (2 * self.y)
        x = s**2 - 2 * self.x
        y = s * (self.x - x) - self.y
        return self.__class__(x, y, self.a, self.b)

to

if self == other:
            s = ((self.x**2+self.x**2+self.x**2)+self.a)/(self.y+self.y)
            x = s**2-(self.x+self.x)
            y = s*(self.x-x)-self.y
            return self.__class__(x, y, self.a, self.b)

Basically, instead of multiplying self.x by 3, I simply added it to itself 3 times for which there was a method for, and so on.

__rmul__ seems to be the scalable solution, though.