Skip to content

Commit

Permalink
default mod_builtins feature
Browse files Browse the repository at this point in the history
  • Loading branch information
FrancoGiachetta committed Sep 30, 2024
1 parent 45b739f commit fdd5341
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
2 changes: 1 addition & 1 deletion cairo1-run/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ num-traits = { version = "0.2", default-features = false }
num-bigint.workspace = true

[features]
default = ["with_mimalloc"]
default = ["with_mimalloc", "mod_builtin"]
with_mimalloc = ["dep:mimalloc"]
mod_builtin = ["cairo-vm/mod_builtin"]
33 changes: 24 additions & 9 deletions vm/src/hint_processor/cairo_1_hint_processor/circuit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ use core::{
};

use ark_ff::{One, Zero};
use num_bigint::BigUint;
use num_integer::Integer;
use num_bigint::{BigInt, BigUint, ToBigInt};
use num_integer::{ExtendedGcd, Integer};
use num_traits::Signed;
use starknet_types_core::felt::Felt;

use crate::{
Expand Down Expand Up @@ -105,14 +106,9 @@ impl CircuitInstance<'_> {
}
// inverse gate: lhs * rhs = 1 => lhs = 1 / rhs
(None, Some(r)) => {
let res = match r.modinv(&self.modulus) {
Some(inv) => inv,
None => {
return false;
}
};
let (success, res) = invert_or_nullify(r, &self.modulus);
self.write_mul_mod_value(index, res);
true
success
}
_ => unreachable!("Unexpected None value while filling mul_mod gate"),
}
Expand Down Expand Up @@ -145,6 +141,25 @@ fn write_circuit_value(vm: &mut VirtualMachine, add: Relocatable, mut value: Big
}
}

fn invert_or_nullify(value: BigUint, modulus: &BigUint) -> (bool, BigUint) {
let ExtendedGcd::<_> { gcd, x, y: _ } =
value.to_bigint().unwrap().extended_gcd(&modulus.to_bigint().unwrap());

let gcd = gcd.to_biguint().unwrap();
if gcd.is_one() {
return (true, positive_modulus(&x, modulus));
}
let nullifier = modulus / gcd;
// Note that gcd divides the value, so value * nullifier = value * (modulus / gcd) =
// (value // gcd) * modulus = 0 (mod modulus)
(false, nullifier)
}

fn positive_modulus(value: &BigInt, modulus: &BigUint) -> BigUint {
let value_magnitud = value.magnitude().mod_floor(modulus);
if value.is_negative() { modulus - value_magnitud } else { value_magnitud }
}

/// Fills the values for a circuit
///
/// Returns the first mul gate index that failed to fill its values or
Expand Down

0 comments on commit fdd5341

Please sign in to comment.