Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(zink-codegen)/added bound checks for primitive numbers #282

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions zink/codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,41 @@ pub fn external(_args: TokenStream, input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as ItemFn);
selector::external(input)
}

/// Bounds for Arithmetic Primitives
trait SafeArithmetic: Sized {
fn safe_add(self, rhs: Self) -> Self;
fn safe_sub(self, rhs: Self) -> Self;
fn safe_mul(self, rhs: Self) -> Self;
fn safe_div(self, rhs: Self);
}

macro_rules! impl_safe_arithmetic {
($t:ty) => {
impl SafeArithmetic for $t {
fn safe_add(self, rhs: Self) -> Self {
self.checked_add(rhs)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we can not use the checked_add from rust library because it will generate verbose bytecode in the WASM IR, instead, we need to append EVM assembly opcodes to operations, for example

fn safe_add(self, rhs: Self) -> Self {
   // the return value r is now on stack
   let r = self.add(rhs);
   if r > Self::MAX {
     zink::revert!("...");
   }
   r
}

Same for all of the other operations

Copy link
Author

@sobuur0 sobuur0 Dec 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@clearloop i'm having some imports issue, where should i place the logic?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

replace them into your current functions of the SafeArithmetic trait, could please elaborate which kind of import issues you are facing?

.unwrap_or_else(|| revert!(concat!(stringify!($t), " addition overflow")))
}

fn safe_sub(self, rhs: Self) -> Self {
self.checked_sub(rhs)
.unwrap_or_else(|| revert!(concat!(stringify!($t), " subtraction overflow")))
}

fn safe_mul(self, rhs: Self) -> Self {
self.checked_mul(rhs)
.unwrap_or_else(|| revert!(concat!(stringify!($t), " multiplication overflow")))
}

fn safe_div(self, rhs: Self) -> Self {
if rhs == 0 {
revert!(concat!(stringify!($t), " division by zero"))
} else {
self.checked_div(rhs)
.unwrap_or_else(|| revert!(concat!(stringify!($t), " division overflow")))
}
}
}
};
}
Loading