Skip to content

Commit

Permalink
fix: implement ln fallback locally
Browse files Browse the repository at this point in the history
  • Loading branch information
dignifiedquire committed Jan 31, 2025
1 parent 9571ec9 commit 7e9dffd
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 9 deletions.
7 changes: 0 additions & 7 deletions Cargo.lock

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

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"]
zeroize = { version = "1.5", features = ["alloc"] }
crypto-bigint = { version = "0.6.0", default-features = false, features = ["zeroize", "alloc"] }
crypto-primes = { version = "0.6.0", default-features = false }
libm = "0.2"

# optional dependencies
sha1 = { version = "=0.11.0-pre.4", optional = true, default-features = false, features = ["oid"] }
Expand Down
32 changes: 31 additions & 1 deletion src/algorithms/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,21 @@ fn logf(val: f64) -> f64 {
/// Natural logarithm for `f64`.
#[cfg(not(feature = "std"))]
fn logf(val: f64) -> f64 {
libm::logf(val as f32) as f64
logf_approx(val as f32) as f64
}

/// Ln implementation based on
/// <https://gist.github.com/LingDong-/7e4c4cae5cbbc44400a05fba65f06f23>
#[cfg(any(not(feature = "std"), test))]
fn logf_approx(x: f32) -> f32 {
let bx: u32 = x.to_bits();
let ex: u32 = bx >> 23;
let t: i32 = (ex as i32) - 127;
let s: u32 = if t < 0 { -t as u32 } else { t as u32 };
let bx = 1065353216 | (bx & 8388607);
let x = f32::from_bits(bx);

-1.49278 + (2.11263 + (-0.729104 + 0.10969 * x) * x) * x + core::f32::consts::LN_2 * (s as f32)
}

fn generate_prime_with_rng<R: CryptoRngCore>(rng: &mut R, bit_length: u32) -> BoxedUint {
Expand All @@ -141,6 +155,7 @@ fn generate_prime_with_rng<R: CryptoRngCore>(rng: &mut R, bit_length: u32) -> Bo
#[cfg(test)]
mod tests {
use super::*;
use rand::Rng;
use rand_chacha::{rand_core::SeedableRng, ChaCha8Rng};

const EXP: u64 = 65537;
Expand Down Expand Up @@ -186,4 +201,19 @@ mod tests {
key_generation!(key_generation_multi_8_576, 8, 576);
// TODO: reenable, currently slow
// key_generation!(key_generation_multi_16_1024, 16, 1024);

#[test]
fn test_log_approx() {
let mut rng = ChaCha8Rng::from_seed([42; 32]);

for i in 0..100 {
println!("round {i}");
let prime_limit: f64 = rng.gen();
let a = logf(prime_limit);
let b = logf_approx(prime_limit as f32);

let diff = a - b as f64;
assert!(diff < 0.001, "{} != {}", a, b);
}
}
}

0 comments on commit 7e9dffd

Please sign in to comment.