From 6dbb007869fef44b873758af1ec13341f8b21a68 Mon Sep 17 00:00:00 2001 From: Jonas Nick Date: Tue, 27 Feb 2018 21:34:08 +0000 Subject: [PATCH] Increase sparsity of pippenger fixed window naf representation --- src/ecmult_impl.h | 13 +++++++++++++ src/tests.c | 3 +-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/ecmult_impl.h b/src/ecmult_impl.h index fd14bf1285784..490982b27dd06 100644 --- a/src/ecmult_impl.h +++ b/src/ecmult_impl.h @@ -607,6 +607,19 @@ static int secp256k1_wnaf_fixed(int *wnaf, const secp256k1_scalar *s, int w) { } else { wnaf[pos] = (val + sign) ^ sign; } + /* Set a coefficient to zero if it is 1 or -1 and the proceeding digit + * is strictly negative or strictly positive respectively. Only change + * coefficients at previous positions because above code assumes that + * wnaf[pos - 1] is odd. + */ + if (pos >= 2 && ((wnaf[pos - 1] == 1 && wnaf[pos - 2] < 0) || (wnaf[pos - 1] == -1 && wnaf[pos - 2] > 0))) { + if (wnaf[pos - 1] == 1) { + wnaf[pos - 2] += 1 << w; + } else { + wnaf[pos - 2] -= 1 << w; + } + wnaf[pos - 1] = 0; + } ++pos; } VERIFY_CHECK(pos == WNAF_SIZE(w)); diff --git a/src/tests.c b/src/tests.c index 893d29722c0e2..ed88811dd97c4 100644 --- a/src/tests.c +++ b/src/tests.c @@ -3022,8 +3022,7 @@ void test_fixed_wnaf(const secp256k1_scalar *number, int w) { for (i = WNAF_SIZE(w)-1; i >= 0; --i) { secp256k1_scalar t; int v = wnaf[i]; - CHECK(v != 0); /* check nonzero */ - CHECK(v & 1); /* check parity */ + CHECK(v == 0 || v & 1); /* check parity */ CHECK(v > -(1 << w)); /* check range above */ CHECK(v < (1 << w)); /* check range below */