Skip to content

Commit

Permalink
modexp: improve runtime Montgomery constants compute. 2.49x faster on…
Browse files Browse the repository at this point in the history
… DOS vectors
  • Loading branch information
mratsim committed Sep 6, 2023
1 parent 586c71b commit 9751ee2
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import
../../platforms/[abstractions, allocs, bithacks],
./limbs_views,
./limbs_mod,
./limbs_fixedprec
./limbs_fixedprec,
./limbs_division

# No exceptions allowed
{.push raises: [], checks: off.}
Expand Down Expand Up @@ -68,7 +69,16 @@ func r_powmod_vartime(r: var openArray[SecretWord], M: openArray[SecretWord], n:

func oneMont_vartime*(r: var openArray[SecretWord], M: openArray[SecretWord]) {.meter.} =
## Returns 1 in Montgomery domain:
r.r_powmod_vartime(M, 1)

# r.r_powmod_vartime(M, 1)

let mBits = getBits_LE_vartime(M)

let t = allocStackArray(SecretWord, M.len + 1)
zeroMem(t, M.len*sizeof(SecretWord))
t[M.len] = One

r.view().reduce(LimbsViewMut t, M.len*WordBitWidth+1, M.view(), mBits)

func r2_vartime*(r: var openArray[SecretWord], M: openArray[SecretWord]) {.meter.} =
## Returns the Montgomery domain magic constant for the input modulus:
Expand All @@ -77,7 +87,17 @@ func r2_vartime*(r: var openArray[SecretWord], M: openArray[SecretWord]) {.meter
##
## Assuming a field modulus of size 256-bit with 63-bit words, we require 5 words
## R² ≡ ((2^63)^5)^2 (mod M) = 2^630 (mod M)
r.r_powmod_vartime(M, 2)

# r.r_powmod_vartime(M, 2)

let mBits = getBits_LE_vartime(M)

let t = allocStackArray(SecretWord, 2*M.len + 1)
zeroMem(t, 2*M.len*sizeof(SecretWord))
t[2*M.len] = One

r.view().reduce(LimbsViewMut t, 2*M.len*WordBitWidth+1, M.view(), mBits)


# Montgomery multiplication
# ------------------------------------------
Expand Down
3 changes: 2 additions & 1 deletion metering/m_modexp.nim
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ let input = [
0x33,

# Exponent
0x01,
0x07,

# Modulus
0x04, 0xea, 0xbb, 0x12, 0x55, 0x88, 0xd7, 0x3c, 0xad, 0x22, 0xea, 0x2b, 0x4a, 0x77, 0x6e, 0x9d,
Expand All @@ -48,5 +48,6 @@ resetMetering()

let status = eth_evm_modexp(r, input)
doAssert status == cttEVM_Success

const flags = if UseASM_X86_64 or UseASM_X86_32: "UseAssembly" else: "NoAssembly"
reportCli(Metrics, flags)
2 changes: 1 addition & 1 deletion metering/tracer.nim
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ when CTT_METER or CTT_TRACE:
let stopTime = getMonoTime()
when SupportsGetTicks:
let elapsedCycles = stopCycle - startCycle
let elapsedTime = inMicroseconds(stopTime - startTime)
let elapsedTime = inNanoseconds(stopTime - startTime)

discard Metrics[id].cumulatedTimeNs.atomicInc(elapsedTime)
when SupportsGetTicks:
Expand Down

0 comments on commit 9751ee2

Please sign in to comment.