From 73b71a184cb93bd5ecc89186375bca4fb5610d8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mamy=20Andr=C3=A9-Ratsimbazafy?= Date: Mon, 10 Feb 2020 19:57:35 +0100 Subject: [PATCH] Fix off-by-one copy, pass small bigints modulo tests --- constantine/bigints_raw.nim | 5 +++-- tests/test_bigints.nim | 36 ++++++++++++++++++++++++++++-------- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/constantine/bigints_raw.nim b/constantine/bigints_raw.nim index 028f054..dae885b 100644 --- a/constantine/bigints_raw.nim +++ b/constantine/bigints_raw.nim @@ -418,7 +418,8 @@ func reduce*(r: BigIntViewMut, a: BigIntViewAny, M: BigIntViewConst) = # and modular shift-left-add the rest let mLen = M.numLimbs() let aOffset = aLen - mLen - copyMem(r[0].addr, a[aOffset].unsafeAddr, (mLen-1) * sizeof(Word)) + copyMem(r[0].addr, a[aOffset+1].unsafeAddr, (mLen-1) * sizeof(Word)) r[^1] = Zero - for i in countdown(aOffset-1, 0): + # Now shift-left the copied words while adding the new word modulo M + for i in countdown(aOffset, 0): r.shlAddMod(a[i], M) diff --git a/tests/test_bigints.nim b/tests/test_bigints.nim index 493c658..c0ab575 100644 --- a/tests/test_bigints.nim +++ b/tests/test_bigints.nim @@ -127,13 +127,33 @@ suite "Arithmetic operations - Addition": suite "Modular operations - small modulus": # Vectors taken from Stint - https://github.com/status-im/nim-stint test "100 mod 13": - let a = BigInt[32].fromUint(100'u32) - let m = BigInt[4].fromUint(13'u8) + # Test 1 word and more than 1 word + block: + let a = BigInt[7].fromUint(100'u32) + let m = BigInt[4].fromUint(13'u8) - var r: BigInt[4] - r.reduce(a, m) - check: - bool(r == BigInt[4].fromUint(100'u8 mod 13)) + var r: BigInt[4] + r.reduce(a, m) + check: + bool(r == BigInt[4].fromUint(100'u8 mod 13)) + + block: # + let a = BigInt[32].fromUint(100'u32) + let m = BigInt[4].fromUint(13'u8) + + var r: BigInt[4] + r.reduce(a, m) + check: + bool(r == BigInt[4].fromUint(100'u8 mod 13)) + + block: # + let a = BigInt[64].fromUint(100'u32) + let m = BigInt[4].fromUint(13'u8) + + var r: BigInt[4] + r.reduce(a, m) + check: + bool(r == BigInt[4].fromUint(100'u8 mod 13)) test "2^64 mod 3": let a = BigInt[65].fromHex("0x1_00000000_00000000") @@ -159,7 +179,7 @@ suite "Modular operations - small modulus - Stint specific failures highlighted let u = 65696211516342324'u64 let v = 174261910798982'u64 - let a = BigInt[64].fromUint(u) + let a = BigInt[56].fromUint(u) let m = BigInt[48].fromUint(v) var r: BigInt[48] @@ -172,7 +192,7 @@ suite "Modular operations - small modulus - Stint specific failures highlighted let u = 15080397990160655'u64 let v = 600432699691'u64 - let a = BigInt[64].fromUint(u) + let a = BigInt[54].fromUint(u) let m = BigInt[40].fromUint(v) var r: BigInt[40]