PoC: Add hazmat module (exposing scalar, point) #1635
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds a "hazmat" [1] module for accessing internal data structures and functions (scalar and point for now), with the idea that other libraries could build on top of that. The implementation is inspired by secp256k1-zkp/#153, but aims to provide data types that can be allocated on the stack instead of the heap, as it seems to be significantly simpler from a user perspective if the burden of dynamic memory management can be avoided. The approach to achieve this is by using a "shell type" with fixed size and alignment that hosts the underlying structure not visible to the user [2], eg for scalar:
Without the alignment enforcing dummy, the compiler emits warnings like
"warning: cast from 'const secp256k1_hazmat_scalar *' to 'secp256k1_scalar *' increases required alignment from 1 to 8 [-Wcast-align]"
when the public type is converted to the underlying internal type via casting. This admittedly looks a bit fishy and I'm not sure if this is even standard-compliant C89, so would appreciate feedback particularly on that.For exposing the ge/gej types, a "smart" point object is used that stores the result in jacobi coordinates together with a "z-is-one" flag and converts to affine coordinates when needed (which is trivial by simply assigning x/y if that flag is set). For multiplication with the generator point, a secp256k1 context object is needed, as otherwise it wouldn't be possible to take use of the optimized and more secure variant.
See the added example for how this module could be used in practice.
For further open questions, see the earlier writeup https://gist.github.com/theStack/0893258c3aba91c28539b9334d2e0608.
[1] ="hazardous material"; this terminology origins in Python's
pyca/cryptography
library, see https://cryptography.io/en/latest/hazmat/primitives/ ("You should ONLY use it if you’re 100% absolutely sure that you know what you’re doing because this module is full of land mines, dragons, and dinosaurs with laser guns.")[2] see e.g. https://fastcompression.blogspot.com/2019/01/opaque-types-and-static-allocation.html