From aef2d09e4caa5e195d31c99a19b0fc1061842297 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Bylica?= Date: Wed, 13 Aug 2025 20:02:00 +0200 Subject: [PATCH] modexp: Optimize the exponentiation loop Use the information that in the first iteration of the exponentiation loop the bit is aways 1. --- lib/evmone_precompiles/modexp.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/lib/evmone_precompiles/modexp.cpp b/lib/evmone_precompiles/modexp.cpp index afa9fe6997..842b8fd83c 100644 --- a/lib/evmone_precompiles/modexp.cpp +++ b/lib/evmone_precompiles/modexp.cpp @@ -73,17 +73,23 @@ class Exponent template UIntT modexp_odd(const UIntT& base, Exponent exp, const UIntT& mod) noexcept { + assert(mod != 0); const evmmax::ModArith arith{mod}; const auto base_mont = arith.to_mont(base); - auto ret = arith.to_mont(1); - for (auto i = exp.bit_width(); i != 0; --i) + if (const auto bit_width = exp.bit_width(); bit_width != 0) [[likely]] { - ret = arith.mul(ret, ret); - if (exp[i - 1]) - ret = arith.mul(ret, base_mont); + auto i = bit_width - 1; + while (true) + { + if (exp[i]) + ret = arith.mul(ret, base_mont); + if (i == 0) + break; + --i; + ret = arith.mul(ret, ret); + } } - return arith.from_mont(ret); }