Skip to content

Commit

Permalink
Implement felt to bigint functions
Browse files Browse the repository at this point in the history
  • Loading branch information
pefontana committed Dec 11, 2023
1 parent 6dd0c22 commit 053ed0f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions crates/starknet-types-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ arbitrary = { version = "1.3.0", optional = true, default-features = false }
num-traits = { version = "0.2.16", default-features = false }
num-bigint = {version = "0.4.4", default-features = false}
num-integer = {version = "0.1.45", default-features = false}
lazy_static = { version = "1.4.0", default-features = false }

[features]
default = ["std", "serde", "curve"]
Expand Down
41 changes: 41 additions & 0 deletions crates/starknet-types-core/src/felt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -945,6 +945,47 @@ mod errors {
}
}

pub mod bigints {
use lazy_static::lazy_static;
use num_bigint::{BigUint, Sign, ToBigInt};
use num_traits::Num;

use super::*;
lazy_static! {
pub static ref CAIRO_PRIME_BIGINT: BigInt = BigInt::from_str_radix(
"800000000000011000000000000000000000000000000000000000000000001",
16
)
.unwrap();
}

pub fn felt_to_biguint(felt: Felt) -> BigUint {
let big_digits = felt
.to_le_digits()
.into_iter()
.flat_map(|limb| [limb as u32, (limb >> 32) as u32])
.collect();
BigUint::new(big_digits)
}

pub fn felt_to_bigint(felt: Felt) -> BigInt {
felt_to_biguint(felt).to_bigint().unwrap()
}

pub fn biguint_to_felt(biguint: &BigUint) -> Felt {
Felt::from_bytes_le_slice(&biguint.to_bytes_le())
}

pub fn bigint_to_felt(bigint: &BigInt) -> Felt {
let (sign, bytes) = bigint.mod_floor(&CAIRO_PRIME_BIGINT).to_bytes_le();
let felt = Felt::from_bytes_le_slice(&bytes);
if sign == Sign::Minus {
felt.neg()
} else {
felt
}
}
}
#[cfg(test)]
mod test {
use super::alloc::{format, string::String, vec::Vec};
Expand Down

0 comments on commit 053ed0f

Please sign in to comment.