2 *****************************************************************************
4 Implementation of interfaces for wNAF ("weighted Non-Adjacent Form")
5 exponentiation routines.
9 *****************************************************************************
10 * @author This file is part of libff, developed by SCIPR Lab
11 * and contributors (see AUTHORS).
12 * @copyright MIT license (see LICENSE file)
13 *****************************************************************************/
25 std::vector<long> &wnaf, const size_t window_size, const bigint<n> &scalar)
27 const size_t length = scalar.max_bits(); // upper bound
28 wnaf.resize(length + 1);
31 while (!c.is_zero()) {
33 if ((c.data[0] & 1) == 1) {
34 u = c.data[0] % (1u << (window_size + 1));
35 if (u > (1 << window_size)) {
36 u = u - (1 << (window_size + 1));
40 mpn_sub_1(c.data, c.data, n, u);
42 mpn_add_1(c.data, c.data, n, -u);
50 mpn_rshift(c.data, c.data, n, 1); // c = c/2
57 std::vector<long> find_wnaf(const size_t window_size, const bigint<n> &scalar)
59 std::vector<long> res;
60 update_wnaf(res, window_size, scalar);
64 template<typename T> size_t wnaf_opt_window_size(const size_t scalar_bits)
66 for (long i = T::wnaf_window_table.size() - 1; i >= 0; --i) {
67 if (scalar_bits >= T::wnaf_window_table[i]) {
76 T fixed_window_wnaf_exp(
77 const size_t window_size, const T &base, const std::vector<long> &naf)
79 std::vector<T> table(1ul << (window_size - 1));
82 for (size_t i = 0; i < 1ul << (window_size - 1); ++i) {
88 bool found_nonzero = false;
89 for (long i = naf.size() - 1; i >= 0; --i) {
97 res = res + table[naf[i] / 2];
99 res = res - table[(-naf[i]) / 2];
107 template<typename T, mp_size_t n>
108 T fixed_window_wnaf_exp(
109 const size_t window_size, const T &base, const bigint<n> &scalar)
111 std::vector<long> naf = find_wnaf(window_size, scalar);
112 return fixed_window_wnaf_exp<T>(window_size, base, naf);
115 template<typename T, mp_size_t n>
116 T opt_window_wnaf_exp(
117 const T &base, const bigint<n> &scalar, const size_t scalar_bits)
119 const size_t best = wnaf_opt_window_size<T>(scalar_bits);
121 return fixed_window_wnaf_exp(best, base, scalar);
123 return scalar * base;