Skip to content

Have PrimeField::from_repr borrow its input#137

Open
tarcieri wants to merge 1 commit intozkcrypto:release-0.14.0from
tarcieri:have-from-repr-borrow-input
Open

Have PrimeField::from_repr borrow its input#137
tarcieri wants to merge 1 commit intozkcrypto:release-0.14.0from
tarcieri:have-from-repr-borrow-input

Conversation

@tarcieri
Copy link
Copy Markdown
Contributor

From the API guidelines, a function that does not require ownership should borrow its input:

https://rust-lang.github.io/api-guidelines/flexibility.html?highlight=clone#caller-decides-where-to-copy-and-place-data-c-caller-control

In general, I think there's an intermediate decoding step between PrimeField::Repr and the corresponding Self type which receives an impl thereof, rather than the Self type actually taking ownership of the Repr data.

Since field element types sometimes represent secrets, taking ownership of the data means the caller can't zeroize that data, and moving the data rather than borrowing it may introduce an additional copy.

From the API guidelines, a function that does not require ownership
should borrow its input:

https://rust-lang.github.io/api-guidelines/flexibility.html?highlight=clone#caller-decides-where-to-copy-and-place-data-c-caller-control

In general, I think there's an intermediate decoding step between
`PrimeField::Repr` and the corresponding `Self` type which receives an
impl thereof, rather than the `Self` type actually taking ownership of
the `Repr` data.

Since field element types sometimes represent secrets, taking ownership
of the data means the caller can't zeroize that data, and moving the
data rather than borrowing it may introduce an additional copy.
@daxpedda
Copy link
Copy Markdown

daxpedda commented May 29, 2025

@tarcieri
Copy link
Copy Markdown
Contributor Author

Note that the existing bounds somewhat complicate cases where you want to do PrimeField::from_repr on a borrowed input. See RustCrypto/elliptic-curves#1721 which is cloning the field elements in this case

tarcieri added a commit to RustCrypto/elliptic-curves that referenced this pull request Apr 13, 2026
This viral bound came because `PrimeField::from_repr` expects a value
rather than a reference, and previously it was using `Copy` to do the
conversion. However, `Clone` is available unconditionally avoiding the
need for such bounds.

Ultimately `PrimeField::from_repr` should probably borrow its input.
See: zkcrypto/ff#137

This came up implementing wNAF since `ProjectivePoint::wnaf` previously
needed it, so if we use it for `mul_vartime` it ultimately adds viral
bounds that it would be nice to avoid.
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

Successfully merging this pull request may close these issues.

2 participants