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

p521: Improve Debug for unsaturated math #949

Merged
merged 3 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions p521/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ sha2 = { version = "0.10", optional = true, default-features = false }

# optional dependencies
primeorder = { version = "0.13.1", optional = true, path = "../primeorder" }
base16ct = "0.2.0"

[features]
default = ["pem", "std"]
Expand Down
36 changes: 35 additions & 1 deletion p521/src/arithmetic/field.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,43 @@ const MODULUS_HEX: &str = "00000000000001fffffffffffffffffffffffffffffffffffffff
const MODULUS: U576 = U576::from_be_hex(MODULUS_HEX);

/// Element of the secp521r1 base field used for curve coordinates.
#[derive(Clone, Copy, Debug)]
#[derive(Clone, Copy)]
pub struct FieldElement(fiat_p521_tight_field_element);

impl core::fmt::Debug for FieldElement {
/// Formatting machinery for [`FieldElement`]
///
/// # Why
/// ```ignore
/// let fe1 = FieldElement([9, 0, 0, 0, 0, 0, 0, 0, 0]);
/// let fe2 = FieldElement([
/// 8,
/// 0,
/// 288230376151711744,
/// 288230376151711743,
/// 288230376151711743,
/// 288230376151711743,
/// 288230376151711743,
/// 288230376151711743,
/// 144115188075855871,
/// ]);
/// ```
///
/// For the above example, deriving [`core::fmt::Debug`] will result in returning 2 different strings,
/// which are in reality the same due to p521's unsaturated math, instead print the output as a hex string in
/// big-endian
///
/// This makes debugging easier.
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut bytes = fiat_p521_to_bytes(&self.0);
bytes.reverse();
let formatter = base16ct::HexDisplay(&bytes);
f.debug_tuple("FieldElement")
.field(&format_args!("0x{formatter:X}"))
.finish()
}
}

impl FieldElement {
/// Zero element.
pub const ZERO: Self = Self::from_u64(0);
Expand Down
Loading