Segmentation fault when using multiply
- Dominant language
- Python
- Stars
- 231
- Forks
- 88
- PR merge metrics
- No merged PRs in 30d
Description
* OS: linux
* Python Version (python --version): Python 3.8.13
* Environment (output of `pip freeze`):
argcomplete==1.12.3
attrs==21.4.0
cached-property==1.5.2
certifi==2022.5.18.1
cytoolz==0.11.2
eth-hash==0.3.2
eth-typing==3.0.0
eth-utils==2.0.0
hypothesis==6.46.11
iniconfig==1.1.1
mypy-extensions==0.4.3
numpy==1.22.4
packaging==21.3
pandas==1.4.2
pipx==0.16.4
pluggy==1.0.0
py==1.11.0
py-ecc==6.0.0
pyparsing==3.0.9
pytest==7.1.2
python-dateutil==2.8.2
pytz==2022.1
six==1.16.0
sortedcontainers==2.4.0
tomli==2.0.1
toolz==0.11.2
userpath==1.7.0
### What is wrong?
'Segmentation fault (core dumped)' error when doing
```python
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:
```python
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:
```python
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.
Contributor guide
Research direction
Start at the multiply implementation used by the bn128 curve and reproduce multiply(G1, -1) with Python 3.8.13. Check how negative values affect the recursive path, then add coverage for negative multiplication and confirm the operation no longer segfaults while preserving the expected curve result.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- cryptography
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100