Skip to content

Commit

Permalink
feat: Update safe_math and move to libraries (#1803)
Browse files Browse the repository at this point in the history
Fixes #1794 and address the wrong check in `mul`. 

Would prefer to add tests directly, but noir don't support failing tests
in noir yet, so there is really no good reason to do that currently. See
noir-lang/noir#1994
  • Loading branch information
superstar0402 committed Aug 25, 2023
1 parent 2f3d1be commit 8ae503d
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
7 changes: 7 additions & 0 deletions yarn-project/noir-libs/safe-math/Nargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "safe_math"
authors = [""]
compiler_version = "0.1"
type = "lib"

[dependencies]
3 changes: 3 additions & 0 deletions yarn-project/noir-libs/safe-math/src/lib.nr
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mod safe_u120;

use crate::safe_u120::SafeU120;
82 changes: 82 additions & 0 deletions yarn-project/noir-libs/safe-math/src/safe_u120.nr
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
struct SafeU120 {
value: u120,
}

impl SafeU120 {
fn is_zero(
self: Self,
) -> bool {
self.value == 0
}

fn sub(
self: Self,
b: SafeU120,
) -> SafeU120 {
assert(self.value >= b.value);
SafeU120 {
value: self.value - b.value
}
}

fn add(
self: Self,
b: SafeU120,
) -> SafeU120 {
let c: u120 = self.value + b.value;
assert(c >= self.value);
SafeU120 {
value: c
}
}

fn mul(
self: Self,
b: SafeU120,
) -> SafeU120 {
let c: u120 = self.value * b.value;
if b.value > 0 {
assert(c / b.value == self.value);
}
SafeU120 {
value: c
}
}

fn div(
self: Self,
b: SafeU120,
) -> SafeU120 {
assert(b.value != 0);
SafeU120 {
value: self.value / b.value
}
}

fn mul_div(
self: Self,
b: SafeU120,
divisor: SafeU120
) -> SafeU120 {
let c = SafeU120::mul(self, b);
SafeU120 {
value: c.value / divisor.value
}
}

fn mul_div_up(
self: Self,
b: SafeU120,
divisor: SafeU120
) -> SafeU120 {
let c = SafeU120::mul(self, b);
let adder = ((self.value * b.value % divisor.value) as u120 > 0) as u120;
SafeU120 {
value: c.value / divisor.value + adder
}
}

// todo: implement mul_div with 240 bit intermediate values.
}

// Adding test in here is pretty useless as long as noir don't support failings tests.

0 comments on commit 8ae503d

Please sign in to comment.