Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

k256: type safety for non-normalized field elements #531

Open
tarcieri opened this issue Mar 14, 2022 · 1 comment
Open

k256: type safety for non-normalized field elements #531

tarcieri opened this issue Mar 14, 2022 · 1 comment

Comments

@tarcieri
Copy link
Member

The k256 crate uses lazy normalization of field elements. While not a user-facing concern as we deliberately encapsulate FieldElement, there is a potential for bugs in code in k256 itself in the event one "forgets" to normalize a field element prior to returning it as the result of some computation. See #530 as an example (although there have been others).

One potential way to eliminate this class of bugs is to use separate types for normalized vs non-normalized field elements. For example, we could introduce something like LazyFieldElement on which all of the arithmetic operations are defined, while retaining FieldElement for the normalized form and defining all serialization operations on that.

LazyFieldElement::normalize could return FieldElement, and we could additionally have bidirectional From conversions between the two.

Things would be a bit tricky in regard to the the ff::Field traits. I imagine for compatibility reasons they would need to be impl'd on FieldElement, converting to a LazyFieldElement to perform the arithmetic, and then calling normalize() to get a FieldElement again as a result, which would mean that the performance benefits of lazy normalization wouldn't be available under such an API. However, that is the only safe usage pattern since the traits are designed to abstract over different fields/field implementations, and not all of them have lazy normalization.

cc @fjarri

@fjarri
Copy link
Contributor

fjarri commented Mar 14, 2022

I think it's a great idea for preventing errors, but yes, trait stuff might get difficult.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
@tarcieri @fjarri and others