diff --git a/elliptic-curve/src/arithmetic/wnaf.rs b/elliptic-curve/src/arithmetic/wnaf.rs index 366bc1b4e..a95445fc2 100644 --- a/elliptic-curve/src/arithmetic/wnaf.rs +++ b/elliptic-curve/src/arithmetic/wnaf.rs @@ -13,7 +13,7 @@ //! such that no two consecutive digits are non-zero. //! //! A configurable window size trades memory for speed: a larger window precomputes more multiples -//! of the base point (a table of `2^(w-1)` entries) but requires fewer group additions per-bit of +//! of the base point (a table of `2^(w-2)` entries) but requires fewer group additions per-bit of //! the scalar. //! //! # RustCrypto Notes @@ -39,13 +39,18 @@ pub trait WnafGroup: Group { } /// Replaces the contents of `table` with a w-NAF window table for the given window size. +/// +/// For a window of size `w`, non-zero wNAF digits are odd and have magnitude at most +/// `2^(w-1) - 1`. The table is indexed by `|digit| / 2`, so the required size is +/// `(2^(w-1) - 1) / 2 + 1 = 2^(w-2)` entries. pub(crate) fn wnaf_table(table: &mut Vec, mut base: G, window: usize) { + let table_len = 1 << (window - 2); table.clear(); - table.reserve(1 << (window - 1)); + table.reserve(table_len); let dbl = base.double(); - for _ in 0..(1 << (window - 1)) { + for _ in 0..table_len { table.push(base); base.add_assign(&dbl); }