shuijian-xu / bitcoin

0 stars 0 forks source link

Constructing a Finite Field in Python #125

Open shuijian-xu opened 5 years ago

shuijian-xu commented 5 years ago

We want to represent each finite field element, so in Python, we’ll be creating a class that represents a single finite field element. Naturally, we’ll name the class FieldElement.

The class represents an element in a field Fprime. The bare bones of the class look like this:

class FieldElement:

def __init__(self, num, prime):
    if num >= prime or num < 0:  #1
        error = 'Num {} not in field range 0 to {}'.format(
            num, prime - 1)
        raise ValueError(error)
    self.num = num  #2
    self.prime = prime

def __repr__(self):
    return 'FieldElement_{}({})'.format(self.prime, self.num)

def __eq__(self, other): 
    if other is None:
        return False
    return self.num == other.num and self.prime == other.prime  #3

1 We first check that num is between 0 and prime-1 inclusive. If not, we get an invalid FieldElement and we raise a ValueError, which is what we should raise when we get an inappropriate value.

2 The rest of the init method assigns the initialization values to the object.

3 The eq method checks if two objects of class FieldElement are equal. This is only true when the num and prime properties are equal.

What we’ve defined already allows us to do this:

from ecc import FieldElement a = FieldElement(7, 13) b = FieldElement(6, 13) print(a == b) False print(a == a) True

Python allows us to override the == operator on FieldElement with the eq method, which is something we’ll be taking advantage of going forward.