jimmysong / programmingbitcoin

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

Point Addition not Working CH02 #157

Open bowlingb opened 5 years ago

bowlingb commented 5 years ago

Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32 Adding a valid point to itself three times should still be a point on the curve.

from ecc import * a = Point(x=-1, y=-1, a=5, b=7) print(a+a) Point(18.0,77.0)_5_7 print(a+a+a) Traceback (most recent call last): File "", line 1, in File "C:\programmingbitcoin-master\code-ch03\ecc.py", line 189, in add return self.class(x, y, self.a, self.b) File "C:\programmingbitcoin-master\code-ch03\ecc.py", line 145, in init raise ValueError('({}, {}) is not on the curve'.format(x, y)) ValueError: (-0.14681440443213134, -2.5025513923312417) is not on the curve

chanhosuh commented 5 years ago

Looks like a floating point comparison error:

In [1]: x = -0.14681440443213134

In [2]: y = -2.5025513923312417

In [3]: -y**2 + x**3 + 5*x + 7
Out[3]: 1.7763568394002505e-14

The Point.__init__ uses == to compare floats in the case where x, y, etc. are floats. The case actually needed for Bitcoin is when x and y are finite field elements, when == works properly.