mmcloughlin / ec3

Elliptic Curve Cryptography Compiler: an incomplete experiment in code-generation for elliptic curves in Go
BSD 3-Clause "New" or "Revised" License
54 stars 6 forks source link

gen: handling of montgomery encode/decode #86

Open mmcloughlin opened 5 years ago

mmcloughlin commented 5 years ago

The encoding and decoding of field elements into Montgomery domain is quite ugly.

https://github.com/mmcloughlin/ec3/blob/298e8f0fc9ebc8c95c8b3f1cc891679b6cc7c97f/examples/p256/point.go#L40-L49

Then we also have code like this to initialize constants.

var (
    bi, _ = new(big.Int).SetString("41058363725152142129326129780047268409114441015993725554835256314039467401291", 10)
    b     = new(Elt).SetIntEncode(bi)
)

Finally, the implementation of scalar Inverse() needs to know whether encoding is necessary.

    K.SetInt(k)
    scalarencode(&K, &K)
    scalarinv(&inv, &K)
    scalardecode(&inv, &inv)
    return inv.Int()

I wonder if this can be completely handed at the field layer. For example, what if the Set() and Int() methods encoded/decoded by default? Then the point operations layer wouldn't have to know. Perhaps we would also need a "raw" interface to set values directly.

Related #47 #55 #82

mmcloughlin commented 5 years ago

30452bf439c348c970ad0176476f5b2b52d2bd20 goes some of the way to resolving this, but has the ugly effect that non-montgomery fields will have two sets of constructors that are identical (the Raw variants are the same as the regular ones).

I think an improved version of this would generate constructors depending on the field type and then export some kind of "interface" object mapping operation types to function names. This interface could have a function name for "construct_raw" and "construct_encoded". These would resolve to different function names for Montgomery fields, but the same otherwise.