From bec4a15c12ac2da32ffb1f3764d9f0181992df07 Mon Sep 17 00:00:00 2001 From: collin Date: Fri, 12 Mar 2021 14:23:41 -0800 Subject: [PATCH 01/10] refactor to use snarkvm int8 gadget --- Cargo.lock | 2 + compiler/src/errors/value/integer.rs | 25 +- compiler/src/value/integer/integer.rs | 1 + compiler/src/value/integer/macros.rs | 11 +- gadgets/benches/integer_arithmetic.rs | 3 +- gadgets/src/bits/rca.rs | 2 +- gadgets/src/signed_integer/arithmetic/add.rs | 4 +- gadgets/src/signed_integer/arithmetic/div.rs | 4 +- gadgets/src/signed_integer/arithmetic/mul.rs | 4 +- gadgets/src/signed_integer/arithmetic/neg.rs | 2 +- gadgets/src/signed_integer/arithmetic/pow.rs | 4 +- gadgets/src/signed_integer/arithmetic/sub.rs | 4 +- gadgets/src/signed_integer/int_impl.rs | 2 +- gadgets/src/signed_integer/relational/cmp.rs | 4 +- gadgets/src/signed_integer/relational/eq.rs | 4 +- gadgets/src/signed_integer/utilities/alloc.rs | 4 +- gadgets/src/signed_integer/utilities/eq.rs | 2 +- .../src/signed_integer/utilities/select.rs | 2 +- gadgets/tests/signed_integer/i8.rs | 854 +++++++++--------- gadgets/tests/signed_integer/mod.rs | 2 +- 20 files changed, 479 insertions(+), 461 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a21706842a..9b0be60484 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,5 +1,7 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + [[package]] name = "addr2line" version = "0.14.1" diff --git a/compiler/src/errors/value/integer.rs b/compiler/src/errors/value/integer.rs index 175141d828..ee9a5e6ab1 100644 --- a/compiler/src/errors/value/integer.rs +++ b/compiler/src/errors/value/integer.rs @@ -16,6 +16,8 @@ use leo_ast::{FormattedError, IntegerType, LeoError, Span, Type}; use leo_gadgets::errors::SignedIntegerError; + +use snarkvm_gadgets::errors::SignedIntegerError as SnarkVMSignedIntegerError; use snarkvm_r1cs::SynthesisError; #[derive(Debug, Error)] @@ -53,13 +55,7 @@ impl IntegerError { } pub fn signed(error: SignedIntegerError, span: &Span) -> Self { - let message = format!("integer operation failed due to the signed integer error `{:?}`", error,); - - Self::new_from_span(message, span) - } - - pub fn synthesis(error: SynthesisError, span: &Span) -> Self { - let message = format!("integer operation failed due to the synthesis error `{}`", error,); + let message = format!("integer operation failed due to the signed integer error `{:?}`", error); Self::new_from_span(message, span) } @@ -73,6 +69,21 @@ impl IntegerError { Self::new_from_span(message, span) } + pub fn snarkvm_error(error: SnarkVMSignedIntegerError, span: &Span) -> Self { + let message = format!( + "the integer operation failed due to the signed integer error `{:?}`", + error + ); + + Self::new_from_span(message, span) + } + + pub fn synthesis(error: SynthesisError, span: &Span) -> Self { + let message = format!("integer operation failed due to the synthesis error `{}`", error); + + Self::new_from_span(message, span) + } + pub fn negate_operation(span: &Span) -> Self { let message = "integer negation can only be enforced on signed integers".to_string(); diff --git a/compiler/src/value/integer/integer.rs b/compiler/src/value/integer/integer.rs index a2affe09b6..6022788c35 100644 --- a/compiler/src/value/integer/integer.rs +++ b/compiler/src/value/integer/integer.rs @@ -27,6 +27,7 @@ use snarkvm_gadgets::traits::utilities::{ bits::comparator::{ComparatorGadget, EvaluateLtGadget}, boolean::Boolean, eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, + int::Int8, select::CondSelectGadget, uint::*, }; diff --git a/compiler/src/value/integer/macros.rs b/compiler/src/value/integer/macros.rs index 9cdab71779..c216cb9918 100644 --- a/compiler/src/value/integer/macros.rs +++ b/compiler/src/value/integer/macros.rs @@ -18,6 +18,7 @@ use leo_gadgets::signed_integer::*; use snarkvm_gadgets::traits::utilities::{ boolean::Boolean, + int::Int8, uint::{UInt128, UInt16, UInt32, UInt64, UInt8}, }; use std::fmt::Debug; @@ -84,7 +85,9 @@ macro_rules! match_unsigned_integer { macro_rules! match_signed_integer { ($integer: ident, $span: ident => $expression: expr) => { match $integer { - Integer::I8($integer) => Some(Integer::I8($expression.map_err(|e| IntegerError::signed(e, $span))?)), + Integer::I8($integer) => Some(Integer::I8( + $expression.map_err(|e| IntegerError::snarkvm_error(e, $span))?, + )), Integer::I16($integer) => Some(Integer::I16($expression.map_err(|e| IntegerError::signed(e, $span))?)), Integer::I32($integer) => Some(Integer::I32($expression.map_err(|e| IntegerError::signed(e, $span))?)), Integer::I64($integer) => Some(Integer::I64($expression.map_err(|e| IntegerError::signed(e, $span))?)), @@ -135,9 +138,9 @@ macro_rules! match_integers_span { $expression.map_err(|e| IntegerError::synthesis(e, $span))?, )), - (Integer::I8($a), Integer::I8($b)) => { - Some(Integer::I8($expression.map_err(|e| IntegerError::signed(e, $span))?)) - } + (Integer::I8($a), Integer::I8($b)) => Some(Integer::I8( + $expression.map_err(|e| IntegerError::snarkvm_error(e, $span))?, + )), (Integer::I16($a), Integer::I16($b)) => { Some(Integer::I16($expression.map_err(|e| IntegerError::signed(e, $span))?)) } diff --git a/gadgets/benches/integer_arithmetic.rs b/gadgets/benches/integer_arithmetic.rs index eada31b5cb..ccdb6cb7c3 100644 --- a/gadgets/benches/integer_arithmetic.rs +++ b/gadgets/benches/integer_arithmetic.rs @@ -14,11 +14,12 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use leo_gadgets::{Int128, Int16, Int32, Int64, Int8}; +use leo_gadgets::{Int128, Int16, Int32, Int64}; use snarkvm_gadgets::traits::utilities::{ alloc::AllocGadget, arithmetic::{Add, Div, Mul, Sub}, + int::Int8, }; use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; diff --git a/gadgets/src/bits/rca.rs b/gadgets/src/bits/rca.rs index 270e7d2415..1f16cb5a3c 100644 --- a/gadgets/src/bits/rca.rs +++ b/gadgets/src/bits/rca.rs @@ -57,4 +57,4 @@ macro_rules! rpc_impl { )*) } -rpc_impl!(Int8 Int16 Int32 Int64 Int128); +rpc_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/add.rs b/gadgets/src/signed_integer/arithmetic/add.rs index 57327d434e..ba4606726c 100644 --- a/gadgets/src/signed_integer/arithmetic/add.rs +++ b/gadgets/src/signed_integer/arithmetic/add.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{bits::RippleCarryAdder, errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64, Int8}; +use crate::{bits::RippleCarryAdder, errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64}; use snarkvm_fields::{fp_parameters::FpParameters, PrimeField}; use snarkvm_gadgets::traits::utilities::{ @@ -141,4 +141,4 @@ macro_rules! add_int_impl { )*) } -add_int_impl!(Int8 Int16 Int32 Int64 Int128); +add_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/div.rs b/gadgets/src/signed_integer/arithmetic/div.rs index 656583a643..eb2cad506a 100644 --- a/gadgets/src/signed_integer/arithmetic/div.rs +++ b/gadgets/src/signed_integer/arithmetic/div.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64, Int8}; +use crate::{errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64}; use snarkvm_fields::PrimeField; use snarkvm_gadgets::traits::utilities::{ alloc::AllocGadget, @@ -249,4 +249,4 @@ macro_rules! div_int_impl { )*) } -div_int_impl!(Int8, Int16, Int32, Int64, Int128); +div_int_impl!(Int16, Int32, Int64, Int128); diff --git a/gadgets/src/signed_integer/arithmetic/mul.rs b/gadgets/src/signed_integer/arithmetic/mul.rs index 7717287343..6b21178307 100644 --- a/gadgets/src/signed_integer/arithmetic/mul.rs +++ b/gadgets/src/signed_integer/arithmetic/mul.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{bits::RippleCarryAdder, errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64, Int8}; +use crate::{bits::RippleCarryAdder, errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64}; use snarkvm_fields::{FpParameters, PrimeField}; use snarkvm_gadgets::traits::utilities::{ alloc::AllocGadget, @@ -208,4 +208,4 @@ macro_rules! mul_int_impl { )*) } -mul_int_impl!(Int8 Int16 Int32 Int64 Int128); +mul_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/neg.rs b/gadgets/src/signed_integer/arithmetic/neg.rs index a030f42a50..bd213aab7c 100644 --- a/gadgets/src/signed_integer/arithmetic/neg.rs +++ b/gadgets/src/signed_integer/arithmetic/neg.rs @@ -51,4 +51,4 @@ macro_rules! neg_int_impl { )*) } -neg_int_impl!(Int8 Int16 Int32 Int64 Int128); +neg_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/pow.rs b/gadgets/src/signed_integer/arithmetic/pow.rs index faef2159ff..f5994fa926 100644 --- a/gadgets/src/signed_integer/arithmetic/pow.rs +++ b/gadgets/src/signed_integer/arithmetic/pow.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64, Int8}; +use crate::{errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64}; use snarkvm_fields::PrimeField; use snarkvm_gadgets::traits::utilities::{ @@ -75,4 +75,4 @@ macro_rules! pow_int_impl { )*) } -pow_int_impl!(Int8 Int16 Int32 Int64 Int128); +pow_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/sub.rs b/gadgets/src/signed_integer/arithmetic/sub.rs index df49d4a606..63be7ed4b0 100644 --- a/gadgets/src/signed_integer/arithmetic/sub.rs +++ b/gadgets/src/signed_integer/arithmetic/sub.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{errors::SignedIntegerError, Int128, Int16, Int32, Int64, Int8}; +use crate::{errors::SignedIntegerError, Int128, Int16, Int32, Int64}; use snarkvm_fields::PrimeField; use snarkvm_gadgets::traits::utilities::arithmetic::{Add, Neg, Sub}; use snarkvm_r1cs::ConstraintSystem; @@ -35,4 +35,4 @@ macro_rules! sub_int_impl { )*) } -sub_int_impl!(Int8 Int16 Int32 Int64 Int128); +sub_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/int_impl.rs b/gadgets/src/signed_integer/int_impl.rs index 211199871a..ac4b3748cc 100644 --- a/gadgets/src/signed_integer/int_impl.rs +++ b/gadgets/src/signed_integer/int_impl.rs @@ -89,7 +89,7 @@ macro_rules! int_impl { }; } -int_impl!(Int8, i8, 8); +// int_impl!(Int8, i8, 8); int_impl!(Int16, i16, 16); int_impl!(Int32, i32, 32); int_impl!(Int64, i64, 64); diff --git a/gadgets/src/signed_integer/relational/cmp.rs b/gadgets/src/signed_integer/relational/cmp.rs index 26cfcaea7c..acd456a2a2 100644 --- a/gadgets/src/signed_integer/relational/cmp.rs +++ b/gadgets/src/signed_integer/relational/cmp.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{Int128, Int16, Int32, Int64, Int8}; +use crate::{Int128, Int16, Int32, Int64}; use snarkvm_fields::PrimeField; use snarkvm_gadgets::traits::utilities::{ @@ -87,4 +87,4 @@ macro_rules! cmp_gadget_impl { )*) } -cmp_gadget_impl!(Int8 Int16 Int32 Int64 Int128); +cmp_gadget_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/relational/eq.rs b/gadgets/src/signed_integer/relational/eq.rs index 0cc1dcf792..c5007a94bf 100644 --- a/gadgets/src/signed_integer/relational/eq.rs +++ b/gadgets/src/signed_integer/relational/eq.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{Int, Int128, Int16, Int32, Int64, Int8}; +use crate::{Int, Int128, Int16, Int32, Int64}; use snarkvm_fields::PrimeField; use snarkvm_gadgets::traits::utilities::{boolean::Boolean, eq::EvaluateEqGadget}; @@ -57,4 +57,4 @@ macro_rules! eq_gadget_impl { )*) } -eq_gadget_impl!(Int8 Int16 Int32 Int64 Int128); +eq_gadget_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/utilities/alloc.rs b/gadgets/src/signed_integer/utilities/alloc.rs index 154b12f48c..a7cd797fcb 100644 --- a/gadgets/src/signed_integer/utilities/alloc.rs +++ b/gadgets/src/signed_integer/utilities/alloc.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{Int, Int128, Int16, Int32, Int64, Int8}; +use crate::{Int, Int128, Int16, Int32, Int64}; use core::{borrow::Borrow, iter}; use snarkvm_fields::Field; @@ -107,4 +107,4 @@ macro_rules! alloc_int_impl { )*) } -alloc_int_impl!(Int8 Int16 Int32 Int64 Int128); +alloc_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/utilities/eq.rs b/gadgets/src/signed_integer/utilities/eq.rs index d3d9066f9c..e15793b005 100644 --- a/gadgets/src/signed_integer/utilities/eq.rs +++ b/gadgets/src/signed_integer/utilities/eq.rs @@ -47,4 +47,4 @@ macro_rules! cond_eq_int_impl { )*) } -cond_eq_int_impl!(Int8, Int16, Int32, Int64, Int128); +cond_eq_int_impl!(Int16, Int32, Int64, Int128); diff --git a/gadgets/src/signed_integer/utilities/select.rs b/gadgets/src/signed_integer/utilities/select.rs index 8cbcede327..d64e47d90c 100644 --- a/gadgets/src/signed_integer/utilities/select.rs +++ b/gadgets/src/signed_integer/utilities/select.rs @@ -73,4 +73,4 @@ macro_rules! select_int_impl { )*) } -select_int_impl!(Int8 Int16 Int32 Int64 Int128); +select_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/tests/signed_integer/i8.rs b/gadgets/tests/signed_integer/i8.rs index a2480e7e31..65b27e966c 100644 --- a/gadgets/tests/signed_integer/i8.rs +++ b/gadgets/tests/signed_integer/i8.rs @@ -1,427 +1,427 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_gadgets::Int8; - -use snarkvm_fields::{One, Zero}; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::{Add, Div, Mul, Pow, Sub}, - boolean::Boolean, -}; -use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; - -use rand::Rng; -use rand_core::SeedableRng; -use rand_xorshift::XorShiftRng; -use std::i8; - -fn check_all_constant_bits(expected: i8, actual: Int8) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i8; - let result = expected & mask; - - match *b { - Boolean::Is(_) => panic!(), - Boolean::Not(_) => panic!(), - Boolean::Constant(b) => { - let bit = result == mask; - assert_eq!(b, bit); - } - } - } -} - -fn check_all_allocated_bits(expected: i8, actual: Int8) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i8; - let result = expected & mask; - - match *b { - Boolean::Is(ref b) => { - let bit = result == mask; - assert_eq!(b.get_value().unwrap(), bit); - } - Boolean::Not(ref b) => { - let bit = result == mask; - assert_eq!(!b.get_value().unwrap(), bit); - } - Boolean::Constant(_) => unreachable!(), - } - } -} - -#[test] -fn test_int8_constant_and_alloc() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - - let a_const = Int8::constant(a); - - assert!(a_const.value == Some(a)); - - check_all_constant_bits(a, a_const); - - let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - - assert!(cs.is_satisfied()); - assert!(a_bit.value == Some(a)); - - check_all_allocated_bits(a, a_bit); - } -} - -#[test] -fn test_int8_add_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - let b: i8 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int8::constant(a); - let b_bit = Int8::constant(b); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int8_add() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - let b: i8 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the addition constraint still works - if cs.get("addition/result bit_gadget 0/boolean").is_zero() { - cs.set("addition/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("addition/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int8_sub_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - let b: i8 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int8::constant(a); - let b_bit = Int8::constant(b); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int8_sub() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - let b: i8 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the subtraction constraint still works - if cs - .get("subtraction/add_complement/result bit_gadget 0/boolean") - .is_zero() - { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int8_mul_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - let b: i8 = rng.gen(); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int8::constant(a); - let b_bit = Int8::constant(b); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int8_mul() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - let b: i8 = rng.gen(); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the multiplication constraint still works - if cs.get("multiplication/result bit_gadget 0/boolean").is_zero() { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int8_div_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - let b: i8 = rng.gen(); - - if a.checked_neg().is_none() { - return; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int8::constant(a); - let b_bit = Int8::constant(b); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int8_div() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..100 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen(); - let b: i8 = rng.gen(); - - if a.checked_neg().is_none() { - continue; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - } -} - -#[test] -fn test_int8_pow_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..100 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen_range(-4..4); - let b: i8 = rng.gen_range(-4..4); - - let expected = match a.checked_pow(b as u32) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int8::constant(a); - let b_bit = Int8::constant(b); - - let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int8_pow() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..10 { - let mut cs = TestConstraintSystem::::new(); - - let a: i8 = rng.gen_range(-4..4); - let b: i8 = rng.gen_range(-4..4); - - let expected = match a.checked_pow(b as u32) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the exponentiation constraint still works - if cs - .get("exponentiation/multiply_by_self_0/result bit_gadget 0/boolean") - .is_zero() - { - cs.set( - "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", - Fr::one(), - ); - } else { - cs.set( - "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", - Fr::zero(), - ); - } - - assert!(!cs.is_satisfied()); - } -} +// // Copyright (C) 2019-2021 Aleo Systems Inc. +// // This file is part of the Leo library. +// +// // The Leo library is free software: you can redistribute it and/or modify +// // it under the terms of the GNU General Public License as published by +// // the Free Software Foundation, either version 3 of the License, or +// // (at your option) any later version. +// +// // The Leo library is distributed in the hope that it will be useful, +// // but WITHOUT ANY WARRANTY; without even the implied warranty of +// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// // GNU General Public License for more details. +// +// // You should have received a copy of the GNU General Public License +// // along with the Leo library. If not, see . +// +// use leo_gadgets::Int8; +// +// use snarkvm_fields::{One, Zero}; +// use snarkvm_gadgets::traits::utilities::{ +// alloc::AllocGadget, +// arithmetic::{Add, Div, Mul, Pow, Sub}, +// boolean::Boolean, +// }; +// use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; +// +// use rand::Rng; +// use rand_core::SeedableRng; +// use rand_xorshift::XorShiftRng; +// use std::i8; +// +// fn check_all_constant_bits(expected: i8, actual: Int8) { +// for (i, b) in actual.bits.iter().enumerate() { +// // shift value by i +// let mask = 1 << i as i8; +// let result = expected & mask; +// +// match *b { +// Boolean::Is(_) => panic!(), +// Boolean::Not(_) => panic!(), +// Boolean::Constant(b) => { +// let bit = result == mask; +// assert_eq!(b, bit); +// } +// } +// } +// } +// +// fn check_all_allocated_bits(expected: i8, actual: Int8) { +// for (i, b) in actual.bits.iter().enumerate() { +// // shift value by i +// let mask = 1 << i as i8; +// let result = expected & mask; +// +// match *b { +// Boolean::Is(ref b) => { +// let bit = result == mask; +// assert_eq!(b.get_value().unwrap(), bit); +// } +// Boolean::Not(ref b) => { +// let bit = result == mask; +// assert_eq!(!b.get_value().unwrap(), bit); +// } +// Boolean::Constant(_) => unreachable!(), +// } +// } +// } +// +// #[test] +// fn test_int8_constant_and_alloc() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..1000 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// +// let a_const = Int8::constant(a); +// +// assert!(a_const.value == Some(a)); +// +// check_all_constant_bits(a, a_const); +// +// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); +// +// assert!(cs.is_satisfied()); +// assert!(a_bit.value == Some(a)); +// +// check_all_allocated_bits(a, a_bit); +// } +// } +// +// #[test] +// fn test_int8_add_constants() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..1000 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// let b: i8 = rng.gen(); +// +// let expected = match a.checked_add(b) { +// Some(valid) => valid, +// None => continue, +// }; +// +// let a_bit = Int8::constant(a); +// let b_bit = Int8::constant(b); +// +// let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); +// +// assert!(r.value == Some(expected)); +// +// check_all_constant_bits(expected, r); +// } +// } +// +// #[test] +// fn test_int8_add() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..1000 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// let b: i8 = rng.gen(); +// +// let expected = match a.checked_add(b) { +// Some(valid) => valid, +// None => continue, +// }; +// +// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); +// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); +// +// let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); +// +// assert!(cs.is_satisfied()); +// +// assert!(r.value == Some(expected)); +// +// check_all_allocated_bits(expected, r); +// +// // Flip a bit_gadget and see if the addition constraint still works +// if cs.get("addition/result bit_gadget 0/boolean").is_zero() { +// cs.set("addition/result bit_gadget 0/boolean", Fr::one()); +// } else { +// cs.set("addition/result bit_gadget 0/boolean", Fr::zero()); +// } +// +// assert!(!cs.is_satisfied()); +// } +// } +// +// #[test] +// fn test_int8_sub_constants() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..1000 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// let b: i8 = rng.gen(); +// +// if b.checked_neg().is_none() { +// // negate with overflows will fail: -128 +// continue; +// } +// let expected = match a.checked_sub(b) { +// // subtract with overflow will fail: -0 +// Some(valid) => valid, +// None => continue, +// }; +// +// let a_bit = Int8::constant(a); +// let b_bit = Int8::constant(b); +// +// let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); +// +// assert!(r.value == Some(expected)); +// +// check_all_constant_bits(expected, r); +// } +// } +// +// #[test] +// fn test_int8_sub() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..1000 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// let b: i8 = rng.gen(); +// +// if b.checked_neg().is_none() { +// // negate with overflows will fail: -128 +// continue; +// } +// let expected = match a.checked_sub(b) { +// // subtract with overflow will fail: -0 +// Some(valid) => valid, +// None => continue, +// }; +// +// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); +// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); +// +// let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); +// +// assert!(cs.is_satisfied()); +// +// assert!(r.value == Some(expected)); +// +// check_all_allocated_bits(expected, r); +// +// // Flip a bit_gadget and see if the subtraction constraint still works +// if cs +// .get("subtraction/add_complement/result bit_gadget 0/boolean") +// .is_zero() +// { +// cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::one()); +// } else { +// cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::zero()); +// } +// +// assert!(!cs.is_satisfied()); +// } +// } +// +// #[test] +// fn test_int8_mul_constants() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..1000 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// let b: i8 = rng.gen(); +// +// let expected = match a.checked_mul(b) { +// Some(valid) => valid, +// None => continue, +// }; +// +// let a_bit = Int8::constant(a); +// let b_bit = Int8::constant(b); +// +// let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); +// +// assert!(r.value == Some(expected)); +// +// check_all_constant_bits(expected, r); +// } +// } +// +// #[test] +// fn test_int8_mul() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..1000 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// let b: i8 = rng.gen(); +// +// let expected = match a.checked_mul(b) { +// Some(valid) => valid, +// None => continue, +// }; +// +// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); +// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); +// +// let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); +// +// assert!(cs.is_satisfied()); +// +// assert!(r.value == Some(expected)); +// +// check_all_allocated_bits(expected, r); +// +// // Flip a bit_gadget and see if the multiplication constraint still works +// if cs.get("multiplication/result bit_gadget 0/boolean").is_zero() { +// cs.set("multiplication/result bit_gadget 0/boolean", Fr::one()); +// } else { +// cs.set("multiplication/result bit_gadget 0/boolean", Fr::zero()); +// } +// +// assert!(!cs.is_satisfied()); +// } +// } +// +// #[test] +// fn test_int8_div_constants() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..1000 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// let b: i8 = rng.gen(); +// +// if a.checked_neg().is_none() { +// return; +// } +// +// let expected = match a.checked_div(b) { +// Some(valid) => valid, +// None => return, +// }; +// +// let a_bit = Int8::constant(a); +// let b_bit = Int8::constant(b); +// +// let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); +// +// assert!(r.value == Some(expected)); +// +// check_all_constant_bits(expected, r); +// } +// } +// +// #[test] +// fn test_int8_div() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..100 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen(); +// let b: i8 = rng.gen(); +// +// if a.checked_neg().is_none() { +// continue; +// } +// +// let expected = match a.checked_div(b) { +// Some(valid) => valid, +// None => return, +// }; +// +// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); +// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); +// +// let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); +// +// assert!(cs.is_satisfied()); +// +// assert!(r.value == Some(expected)); +// +// check_all_allocated_bits(expected, r); +// } +// } +// +// #[test] +// fn test_int8_pow_constants() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..100 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen_range(-4..4); +// let b: i8 = rng.gen_range(-4..4); +// +// let expected = match a.checked_pow(b as u32) { +// Some(valid) => valid, +// None => continue, +// }; +// +// let a_bit = Int8::constant(a); +// let b_bit = Int8::constant(b); +// +// let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); +// +// assert!(r.value == Some(expected)); +// +// check_all_constant_bits(expected, r); +// } +// } +// +// #[test] +// fn test_int8_pow() { +// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); +// +// for _ in 0..10 { +// let mut cs = TestConstraintSystem::::new(); +// +// let a: i8 = rng.gen_range(-4..4); +// let b: i8 = rng.gen_range(-4..4); +// +// let expected = match a.checked_pow(b as u32) { +// Some(valid) => valid, +// None => continue, +// }; +// +// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); +// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); +// +// let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); +// +// assert!(cs.is_satisfied()); +// +// assert!(r.value == Some(expected)); +// +// check_all_allocated_bits(expected, r); +// +// // Flip a bit_gadget and see if the exponentiation constraint still works +// if cs +// .get("exponentiation/multiply_by_self_0/result bit_gadget 0/boolean") +// .is_zero() +// { +// cs.set( +// "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", +// Fr::one(), +// ); +// } else { +// cs.set( +// "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", +// Fr::zero(), +// ); +// } +// +// assert!(!cs.is_satisfied()); +// } +// } diff --git a/gadgets/tests/signed_integer/mod.rs b/gadgets/tests/signed_integer/mod.rs index 7d9e327e70..e262f23bc9 100644 --- a/gadgets/tests/signed_integer/mod.rs +++ b/gadgets/tests/signed_integer/mod.rs @@ -18,4 +18,4 @@ pub mod i128; pub mod i16; pub mod i32; pub mod i64; -pub mod i8; +// pub mod i8; From 6962e1c2e13ac67d1720d04c2d3d65c423edb7de Mon Sep 17 00:00:00 2001 From: collin Date: Fri, 12 Mar 2021 15:03:22 -0800 Subject: [PATCH 02/10] refactor to use snarkvm int16 int32 int64 int128 gadgets --- compiler/src/errors/value/integer.rs | 12 +----------- compiler/src/value/integer/integer.rs | 3 +-- compiler/src/value/integer/macros.rs | 14 +++++--------- gadgets/benches/integer_arithmetic.rs | 5 ++--- gadgets/src/bits/rca.rs | 2 -- gadgets/src/lib.rs | 12 ++++++------ gadgets/tests/mod.rs | 4 ++-- gadgets/tests/signed_integer/mod.rs | 9 +++++---- 8 files changed, 22 insertions(+), 39 deletions(-) diff --git a/compiler/src/errors/value/integer.rs b/compiler/src/errors/value/integer.rs index ee9a5e6ab1..eb0096e400 100644 --- a/compiler/src/errors/value/integer.rs +++ b/compiler/src/errors/value/integer.rs @@ -15,9 +15,8 @@ // along with the Leo library. If not, see . use leo_ast::{FormattedError, IntegerType, LeoError, Span, Type}; -use leo_gadgets::errors::SignedIntegerError; -use snarkvm_gadgets::errors::SignedIntegerError as SnarkVMSignedIntegerError; +use snarkvm_gadgets::errors::SignedIntegerError; use snarkvm_r1cs::SynthesisError; #[derive(Debug, Error)] @@ -69,15 +68,6 @@ impl IntegerError { Self::new_from_span(message, span) } - pub fn snarkvm_error(error: SnarkVMSignedIntegerError, span: &Span) -> Self { - let message = format!( - "the integer operation failed due to the signed integer error `{:?}`", - error - ); - - Self::new_from_span(message, span) - } - pub fn synthesis(error: SynthesisError, span: &Span) -> Self { let message = format!("integer operation failed due to the synthesis error `{}`", error); diff --git a/compiler/src/value/integer/integer.rs b/compiler/src/value/integer/integer.rs index 6022788c35..40368405ec 100644 --- a/compiler/src/value/integer/integer.rs +++ b/compiler/src/value/integer/integer.rs @@ -18,7 +18,6 @@ use crate::{errors::IntegerError, IntegerTrait}; use leo_asg::{ConstInt, IntegerType, Span}; use leo_ast::InputValue; -use leo_gadgets::signed_integer::*; use snarkvm_fields::{Field, PrimeField}; use snarkvm_gadgets::traits::utilities::{ @@ -27,7 +26,7 @@ use snarkvm_gadgets::traits::utilities::{ bits::comparator::{ComparatorGadget, EvaluateLtGadget}, boolean::Boolean, eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, - int::Int8, + int::{Int128, Int16, Int32, Int64, Int8}, select::CondSelectGadget, uint::*, }; diff --git a/compiler/src/value/integer/macros.rs b/compiler/src/value/integer/macros.rs index c216cb9918..932a646fa4 100644 --- a/compiler/src/value/integer/macros.rs +++ b/compiler/src/value/integer/macros.rs @@ -14,11 +14,9 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use leo_gadgets::signed_integer::*; - use snarkvm_gadgets::traits::utilities::{ boolean::Boolean, - int::Int8, + int::{Int128, Int16, Int32, Int64, Int8}, uint::{UInt128, UInt16, UInt32, UInt64, UInt8}, }; use std::fmt::Debug; @@ -85,9 +83,7 @@ macro_rules! match_unsigned_integer { macro_rules! match_signed_integer { ($integer: ident, $span: ident => $expression: expr) => { match $integer { - Integer::I8($integer) => Some(Integer::I8( - $expression.map_err(|e| IntegerError::snarkvm_error(e, $span))?, - )), + Integer::I8($integer) => Some(Integer::I8($expression.map_err(|e| IntegerError::signed(e, $span))?)), Integer::I16($integer) => Some(Integer::I16($expression.map_err(|e| IntegerError::signed(e, $span))?)), Integer::I32($integer) => Some(Integer::I32($expression.map_err(|e| IntegerError::signed(e, $span))?)), Integer::I64($integer) => Some(Integer::I64($expression.map_err(|e| IntegerError::signed(e, $span))?)), @@ -138,9 +134,9 @@ macro_rules! match_integers_span { $expression.map_err(|e| IntegerError::synthesis(e, $span))?, )), - (Integer::I8($a), Integer::I8($b)) => Some(Integer::I8( - $expression.map_err(|e| IntegerError::snarkvm_error(e, $span))?, - )), + (Integer::I8($a), Integer::I8($b)) => { + Some(Integer::I8($expression.map_err(|e| IntegerError::signed(e, $span))?)) + } (Integer::I16($a), Integer::I16($b)) => { Some(Integer::I16($expression.map_err(|e| IntegerError::signed(e, $span))?)) } diff --git a/gadgets/benches/integer_arithmetic.rs b/gadgets/benches/integer_arithmetic.rs index ccdb6cb7c3..2bdd0b7842 100644 --- a/gadgets/benches/integer_arithmetic.rs +++ b/gadgets/benches/integer_arithmetic.rs @@ -14,12 +14,10 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use leo_gadgets::{Int128, Int16, Int32, Int64}; - use snarkvm_gadgets::traits::utilities::{ alloc::AllocGadget, arithmetic::{Add, Div, Mul, Sub}, - int::Int8, + int::{Int128, Int16, Int32, Int64, Int8}, }; use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; @@ -29,6 +27,7 @@ use std::i128; use criterion::{criterion_group, criterion_main, Criterion}; +// TODO: move these benchmarks to snarkvm? macro_rules! create_add_bench { ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { fn $bench_name(c: &mut Criterion) { diff --git a/gadgets/src/bits/rca.rs b/gadgets/src/bits/rca.rs index 1f16cb5a3c..86b7a8cf65 100644 --- a/gadgets/src/bits/rca.rs +++ b/gadgets/src/bits/rca.rs @@ -14,8 +14,6 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -use crate::{bits::FullAdder, signed_integer::*}; - use snarkvm_fields::{Field, PrimeField}; use snarkvm_gadgets::traits::utilities::boolean::Boolean; use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; diff --git a/gadgets/src/lib.rs b/gadgets/src/lib.rs index 38eed81ac1..d2ba9d58da 100644 --- a/gadgets/src/lib.rs +++ b/gadgets/src/lib.rs @@ -14,12 +14,12 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -#[macro_use] -extern crate thiserror; +// #[macro_use] +// extern crate thiserror; -pub mod bits; +// pub mod bits; -pub mod errors; +// pub mod errors; -pub mod signed_integer; -pub use self::signed_integer::*; +// pub mod signed_integer; +// pub use self::signed_integer::*; diff --git a/gadgets/tests/mod.rs b/gadgets/tests/mod.rs index 39c7dd79cc..898f5b4c27 100644 --- a/gadgets/tests/mod.rs +++ b/gadgets/tests/mod.rs @@ -14,5 +14,5 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -pub mod signed_integer; -pub use self::signed_integer::*; +// pub mod signed_integer; +// pub use self::signed_integer::*; diff --git a/gadgets/tests/signed_integer/mod.rs b/gadgets/tests/signed_integer/mod.rs index e262f23bc9..73b3adce90 100644 --- a/gadgets/tests/signed_integer/mod.rs +++ b/gadgets/tests/signed_integer/mod.rs @@ -14,8 +14,9 @@ // You should have received a copy of the GNU General Public License // along with the Leo library. If not, see . -pub mod i128; -pub mod i16; -pub mod i32; -pub mod i64; +// Todo: move these tests to snarkvm. +// pub mod i128; +// pub mod i16; +// pub mod i32; +// pub mod i64; // pub mod i8; From e369cb7049e30848daf588d2d72295d8086899b8 Mon Sep 17 00:00:00 2001 From: collin Date: Fri, 12 Mar 2021 15:08:44 -0800 Subject: [PATCH 03/10] remove leo-gadgets crate --- Cargo.lock | 17 - Cargo.toml | 5 - compiler/Cargo.toml | 4 - gadgets/Cargo.toml | 55 -- gadgets/LICENSE.md | 596 ------------------ gadgets/README.md | 5 - gadgets/benches/integer_arithmetic.rs | 430 ------------- gadgets/src/bits/adder.rs | 54 -- gadgets/src/bits/mod.rs | 22 - gadgets/src/bits/rca.rs | 58 -- gadgets/src/errors/mod.rs | 18 - gadgets/src/errors/signed_integer.rs | 29 - gadgets/src/lib.rs | 25 - gadgets/src/signed_integer/arithmetic/add.rs | 144 ----- gadgets/src/signed_integer/arithmetic/div.rs | 252 -------- gadgets/src/signed_integer/arithmetic/mod.rs | 34 - gadgets/src/signed_integer/arithmetic/mul.rs | 211 ------- gadgets/src/signed_integer/arithmetic/neg.rs | 54 -- gadgets/src/signed_integer/arithmetic/pow.rs | 78 --- gadgets/src/signed_integer/arithmetic/sub.rs | 38 -- gadgets/src/signed_integer/int_impl.rs | 96 --- gadgets/src/signed_integer/mod.rs | 29 - gadgets/src/signed_integer/relational/cmp.rs | 90 --- gadgets/src/signed_integer/relational/eq.rs | 60 -- gadgets/src/signed_integer/relational/mod.rs | 22 - gadgets/src/signed_integer/utilities/alloc.rs | 110 ---- gadgets/src/signed_integer/utilities/eq.rs | 50 -- gadgets/src/signed_integer/utilities/mod.rs | 25 - .../src/signed_integer/utilities/select.rs | 76 --- gadgets/tests/mod.rs | 18 - gadgets/tests/signed_integer/i128.rs | 361 ----------- gadgets/tests/signed_integer/i16.rs | 433 ------------- gadgets/tests/signed_integer/i32.rs | 435 ------------- gadgets/tests/signed_integer/i64.rs | 425 ------------- gadgets/tests/signed_integer/i8.rs | 427 ------------- gadgets/tests/signed_integer/mod.rs | 22 - 36 files changed, 4808 deletions(-) delete mode 100644 gadgets/Cargo.toml delete mode 100644 gadgets/LICENSE.md delete mode 100644 gadgets/README.md delete mode 100644 gadgets/benches/integer_arithmetic.rs delete mode 100644 gadgets/src/bits/adder.rs delete mode 100644 gadgets/src/bits/mod.rs delete mode 100644 gadgets/src/bits/rca.rs delete mode 100644 gadgets/src/errors/mod.rs delete mode 100644 gadgets/src/errors/signed_integer.rs delete mode 100644 gadgets/src/lib.rs delete mode 100644 gadgets/src/signed_integer/arithmetic/add.rs delete mode 100644 gadgets/src/signed_integer/arithmetic/div.rs delete mode 100644 gadgets/src/signed_integer/arithmetic/mod.rs delete mode 100644 gadgets/src/signed_integer/arithmetic/mul.rs delete mode 100644 gadgets/src/signed_integer/arithmetic/neg.rs delete mode 100644 gadgets/src/signed_integer/arithmetic/pow.rs delete mode 100644 gadgets/src/signed_integer/arithmetic/sub.rs delete mode 100644 gadgets/src/signed_integer/int_impl.rs delete mode 100644 gadgets/src/signed_integer/mod.rs delete mode 100644 gadgets/src/signed_integer/relational/cmp.rs delete mode 100644 gadgets/src/signed_integer/relational/eq.rs delete mode 100644 gadgets/src/signed_integer/relational/mod.rs delete mode 100644 gadgets/src/signed_integer/utilities/alloc.rs delete mode 100644 gadgets/src/signed_integer/utilities/eq.rs delete mode 100644 gadgets/src/signed_integer/utilities/mod.rs delete mode 100644 gadgets/src/signed_integer/utilities/select.rs delete mode 100644 gadgets/tests/mod.rs delete mode 100644 gadgets/tests/signed_integer/i128.rs delete mode 100644 gadgets/tests/signed_integer/i16.rs delete mode 100644 gadgets/tests/signed_integer/i32.rs delete mode 100644 gadgets/tests/signed_integer/i64.rs delete mode 100644 gadgets/tests/signed_integer/i8.rs delete mode 100644 gadgets/tests/signed_integer/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 9b0be60484..01fbd835ba 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1236,7 +1236,6 @@ dependencies = [ "leo-asg", "leo-asg-passes", "leo-ast", - "leo-gadgets", "leo-imports", "leo-input", "leo-package", @@ -1260,21 +1259,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "leo-gadgets" -version = "1.2.3" -dependencies = [ - "criterion", - "rand", - "rand_core", - "rand_xorshift", - "snarkvm-fields", - "snarkvm-gadgets", - "snarkvm-r1cs", - "snarkvm-utilities", - "thiserror", -] - [[package]] name = "leo-imports" version = "1.2.3" @@ -1312,7 +1296,6 @@ dependencies = [ "lazy_static", "leo-ast", "leo-compiler", - "leo-gadgets", "leo-imports", "leo-input", "leo-package", diff --git a/Cargo.toml b/Cargo.toml index 6ddfa9a8d3..3e1edc43d6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,7 +29,6 @@ members = [ "asg", "ast", "compiler", - "gadgets", "imports", "input", "linter", @@ -48,10 +47,6 @@ version = "1.2.3" path = "./compiler" version = "1.2.3" -[dependencies.leo-gadgets] -path = "./gadgets" -version = "1.2.3" - [dependencies.leo-imports] path = "./imports" version = "1.2.3" diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml index f5572ef64c..89d9373f15 100644 --- a/compiler/Cargo.toml +++ b/compiler/Cargo.toml @@ -21,10 +21,6 @@ edition = "2018" path = "../ast" version = "1.2.3" -[dependencies.leo-gadgets] -path = "../gadgets" -version = "1.2.3" - [dependencies.leo-imports] path = "../imports" version = "1.2.3" diff --git a/gadgets/Cargo.toml b/gadgets/Cargo.toml deleted file mode 100644 index 5238eed768..0000000000 --- a/gadgets/Cargo.toml +++ /dev/null @@ -1,55 +0,0 @@ -[package] -name = "leo-gadgets" -version = "1.2.3" -authors = [ "The Aleo Team " ] -description = "Gadgets of the Leo programming language" -homepage = "https://aleo.org" -repository = "https://github.com/AleoHQ/leo" -keywords = [ - "aleo", - "cryptography", - "leo", - "programming-language", - "zero-knowledge" -] -categories = [ "cryptography::cryptocurrencies", "web-programming" ] -include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ] -license = "GPL-3.0" -edition = "2018" - -[dependencies.snarkvm-fields] -version = "0.2.0" -default-features = false - -[dependencies.snarkvm-gadgets] -version = "0.2.0" -default-features = false - -[dependencies.snarkvm-r1cs] -version = "0.2.0" -default-features = false - -[dependencies.snarkvm-utilities] -version = "0.2.0" - -[dependencies.rand] -version = "0.8" -default-features = false - -[dependencies.rand_xorshift] -version = "0.3" -default-features = false - -[dependencies.thiserror] -version = "1.0" - -[dev-dependencies.criterion] -version = "0.3" - -[dev-dependencies.rand_core] -version = "0.6.2" - -[[bench]] -name = "integer_arithmetic" -path = "benches/integer_arithmetic.rs" -harness = false diff --git a/gadgets/LICENSE.md b/gadgets/LICENSE.md deleted file mode 100644 index b95c626e2a..0000000000 --- a/gadgets/LICENSE.md +++ /dev/null @@ -1,596 +0,0 @@ -GNU General Public License -========================== - -Version 3, 29 June 2007 - -Copyright © 2007 Free Software Foundation, Inc. <> - -Everyone is permitted to copy and distribute verbatim copies of this license -document, but changing it is not allowed. - -## Preamble - -The GNU General Public License is a free, copyleft license for software and other -kinds of works. - -The licenses for most software and other practical works are designed to take away -your freedom to share and change the works. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change all versions of a -program--to make sure it remains free software for all its users. We, the Free -Software Foundation, use the GNU General Public License for most of our software; it -applies also to any other work released this way by its authors. You can apply it to -your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our General -Public Licenses are designed to make sure that you have the freedom to distribute -copies of free software (and charge for them if you wish), that you receive source -code or can get it if you want it, that you can change the software or use pieces of -it in new free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you these rights or -asking you to surrender the rights. Therefore, you have certain responsibilities if -you distribute copies of the software, or if you modify it: responsibilities to -respect the freedom of others. - -For example, if you distribute copies of such a program, whether gratis or for a fee, -you must pass on to the recipients the same freedoms that you received. You must make -sure that they, too, receive or can get the source code. And you must show them these -terms so they know their rights. - -Developers that use the GNU GPL protect your rights with two steps: **(1)** assert -copyright on the software, and **(2)** offer you this License giving you legal permission -to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains that there is -no warranty for this free software. For both users' and authors' sake, the GPL -requires that modified versions be marked as changed, so that their problems will not -be attributed erroneously to authors of previous versions. - -Some devices are designed to deny users access to install or run modified versions of -the software inside them, although the manufacturer can do so. This is fundamentally -incompatible with the aim of protecting users' freedom to change the software. The -systematic pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we have designed -this version of the GPL to prohibit the practice for those products. If such problems -arise substantially in other domains, we stand ready to extend this provision to -those domains in future versions of the GPL, as needed to protect the freedom of -users. - -Finally, every program is threatened constantly by software patents. States should -not allow patents to restrict development and use of software on general-purpose -computers, but in those that do, we wish to avoid the special danger that patents -applied to a free program could make it effectively proprietary. To prevent this, the -GPL assures that patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and modification follow. - -## TERMS AND CONDITIONS - -### 0. Definitions - -“This License” refers to version 3 of the GNU General Public License. - -“Copyright” also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - -“The Program” refers to any copyrightable work licensed under this -License. Each licensee is addressed as “you”. “Licensees” and -“recipients” may be individuals or organizations. - -To “modify” a work means to copy from or adapt all or part of the work in -a fashion requiring copyright permission, other than the making of an exact copy. The -resulting work is called a “modified version” of the earlier work or a -work “based on” the earlier work. - -A “covered work” means either the unmodified Program or a work based on -the Program. - -To “propagate” a work means to do anything with it that, without -permission, would make you directly or secondarily liable for infringement under -applicable copyright law, except executing it on a computer or modifying a private -copy. Propagation includes copying, distribution (with or without modification), -making available to the public, and in some countries other activities as well. - -To “convey” a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through a computer -network, with no transfer of a copy, is not conveying. - -An interactive user interface displays “Appropriate Legal Notices” to the -extent that it includes a convenient and prominently visible feature that **(1)** -displays an appropriate copyright notice, and **(2)** tells the user that there is no -warranty for the work (except to the extent that warranties are provided), that -licensees may convey the work under this License, and how to view a copy of this -License. If the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - -### 1. Source Code - -The “source code” for a work means the preferred form of the work for -making modifications to it. “Object code” means any non-source form of a -work. - -A “Standard Interface” means an interface that either is an official -standard defined by a recognized standards body, or, in the case of interfaces -specified for a particular programming language, one that is widely used among -developers working in that language. - -The “System Libraries” of an executable work include anything, other than -the work as a whole, that **(a)** is included in the normal form of packaging a Major -Component, but which is not part of that Major Component, and **(b)** serves only to -enable use of the work with that Major Component, or to implement a Standard -Interface for which an implementation is available to the public in source code form. -A “Major Component”, in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system (if any) on which -the executable work runs, or a compiler used to produce the work, or an object code -interpreter used to run it. - -The “Corresponding Source” for a work in object code form means all the -source code needed to generate, install, and (for an executable work) run the object -code and to modify the work, including scripts to control those activities. However, -it does not include the work's System Libraries, or general-purpose tools or -generally available free programs which are used unmodified in performing those -activities but which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for the work, and -the source code for shared libraries and dynamically linked subprograms that the work -is specifically designed to require, such as by intimate data communication or -control flow between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate -automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -### 2. Basic Permissions - -All rights granted under this License are granted for the term of copyright on the -Program, and are irrevocable provided the stated conditions are met. This License -explicitly affirms your unlimited permission to run the unmodified Program. The -output from running a covered work is covered by this License only if the output, -given its content, constitutes a covered work. This License acknowledges your rights -of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without -conditions so long as your license otherwise remains in force. You may convey covered -works to others for the sole purpose of having them make modifications exclusively -for you, or provide you with facilities for running those works, provided that you -comply with the terms of this License in conveying all material for which you do not -control copyright. Those thus making or running the covered works for you must do so -exclusively on your behalf, under your direction and control, on terms that prohibit -them from making any copies of your copyrighted material outside their relationship -with you. - -Conveying under any other circumstances is permitted solely under the conditions -stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - -### 3. Protecting Users' Legal Rights From Anti-Circumvention Law - -No covered work shall be deemed part of an effective technological measure under any -applicable law fulfilling obligations under article 11 of the WIPO copyright treaty -adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention -of such measures. - -When you convey a covered work, you waive any legal power to forbid circumvention of -technological measures to the extent such circumvention is effected by exercising -rights under this License with respect to the covered work, and you disclaim any -intention to limit operation or modification of the work as a means of enforcing, -against the work's users, your or third parties' legal rights to forbid circumvention -of technological measures. - -### 4. Conveying Verbatim Copies - -You may convey verbatim copies of the Program's source code as you receive it, in any -medium, provided that you conspicuously and appropriately publish on each copy an -appropriate copyright notice; keep intact all notices stating that this License and -any non-permissive terms added in accord with section 7 apply to the code; keep -intact all notices of the absence of any warranty; and give all recipients a copy of -this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may offer -support or warranty protection for a fee. - -### 5. Conveying Modified Source Versions - -You may convey a work based on the Program, or the modifications to produce it from -the Program, in the form of source code under the terms of section 4, provided that -you also meet all of these conditions: - -* **a)** The work must carry prominent notices stating that you modified it, and giving a -relevant date. -* **b)** The work must carry prominent notices stating that it is released under this -License and any conditions added under section 7. This requirement modifies the -requirement in section 4 to “keep intact all notices”. -* **c)** You must license the entire work, as a whole, under this License to anyone who -comes into possession of a copy. This License will therefore apply, along with any -applicable section 7 additional terms, to the whole of the work, and all its parts, -regardless of how they are packaged. This License gives no permission to license the -work in any other way, but it does not invalidate such permission if you have -separately received it. -* **d)** If the work has interactive user interfaces, each must display Appropriate Legal -Notices; however, if the Program has interactive interfaces that do not display -Appropriate Legal Notices, your work need not make them do so. - -A compilation of a covered work with other separate and independent works, which are -not by their nature extensions of the covered work, and which are not combined with -it such as to form a larger program, in or on a volume of a storage or distribution -medium, is called an “aggregate” if the compilation and its resulting -copyright are not used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work in an aggregate -does not cause this License to apply to the other parts of the aggregate. - -### 6. Conveying Non-Source Forms - -You may convey a covered work in object code form under the terms of sections 4 and -5, provided that you also convey the machine-readable Corresponding Source under the -terms of this License, in one of these ways: - -* **a)** Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by the Corresponding Source fixed on a -durable physical medium customarily used for software interchange. -* **b)** Convey the object code in, or embodied in, a physical product (including a -physical distribution medium), accompanied by a written offer, valid for at least -three years and valid for as long as you offer spare parts or customer support for -that product model, to give anyone who possesses the object code either **(1)** a copy of -the Corresponding Source for all the software in the product that is covered by this -License, on a durable physical medium customarily used for software interchange, for -a price no more than your reasonable cost of physically performing this conveying of -source, or **(2)** access to copy the Corresponding Source from a network server at no -charge. -* **c)** Convey individual copies of the object code with a copy of the written offer to -provide the Corresponding Source. This alternative is allowed only occasionally and -noncommercially, and only if you received the object code with such an offer, in -accord with subsection 6b. -* **d)** Convey the object code by offering access from a designated place (gratis or for -a charge), and offer equivalent access to the Corresponding Source in the same way -through the same place at no further charge. You need not require recipients to copy -the Corresponding Source along with the object code. If the place to copy the object -code is a network server, the Corresponding Source may be on a different server -(operated by you or a third party) that supports equivalent copying facilities, -provided you maintain clear directions next to the object code saying where to find -the Corresponding Source. Regardless of what server hosts the Corresponding Source, -you remain obligated to ensure that it is available for as long as needed to satisfy -these requirements. -* **e)** Convey the object code using peer-to-peer transmission, provided you inform -other peers where the object code and Corresponding Source of the work are being -offered to the general public at no charge under subsection 6d. - -A separable portion of the object code, whose source code is excluded from the -Corresponding Source as a System Library, need not be included in conveying the -object code work. - -A “User Product” is either **(1)** a “consumer product”, which -means any tangible personal property which is normally used for personal, family, or -household purposes, or **(2)** anything designed or sold for incorporation into a -dwelling. In determining whether a product is a consumer product, doubtful cases -shall be resolved in favor of coverage. For a particular product received by a -particular user, “normally used” refers to a typical or common use of -that class of product, regardless of the status of the particular user or of the way -in which the particular user actually uses, or expects or is expected to use, the -product. A product is a consumer product regardless of whether the product has -substantial commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - -“Installation Information” for a User Product means any methods, -procedures, authorization keys, or other information required to install and execute -modified versions of a covered work in that User Product from a modified version of -its Corresponding Source. The information must suffice to ensure that the continued -functioning of the modified object code is in no case prevented or interfered with -solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for -use in, a User Product, and the conveying occurs as part of a transaction in which -the right of possession and use of the User Product is transferred to the recipient -in perpetuity or for a fixed term (regardless of how the transaction is -characterized), the Corresponding Source conveyed under this section must be -accompanied by the Installation Information. But this requirement does not apply if -neither you nor any third party retains the ability to install modified object code -on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to -continue to provide support service, warranty, or updates for a work that has been -modified or installed by the recipient, or for the User Product in which it has been -modified or installed. Access to a network may be denied when the modification itself -materially and adversely affects the operation of the network or violates the rules -and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with -this section must be in a format that is publicly documented (and with an -implementation available to the public in source code form), and must require no -special password or key for unpacking, reading or copying. - -### 7. Additional Terms - -“Additional permissions” are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. Additional -permissions that are applicable to the entire Program shall be treated as though they -were included in this License, to the extent that they are valid under applicable -law. If additional permissions apply only to part of the Program, that part may be -used separately under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any -additional permissions from that copy, or from any part of it. (Additional -permissions may be written to require their own removal in certain cases when you -modify the work.) You may place additional permissions on material, added by you to a -covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a -covered work, you may (if authorized by the copyright holders of that material) -supplement the terms of this License with terms: - -* **a)** Disclaiming warranty or limiting liability differently from the terms of -sections 15 and 16 of this License; or -* **b)** Requiring preservation of specified reasonable legal notices or author -attributions in that material or in the Appropriate Legal Notices displayed by works -containing it; or -* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that -modified versions of such material be marked in reasonable ways as different from the -original version; or -* **d)** Limiting the use for publicity purposes of names of licensors or authors of the -material; or -* **e)** Declining to grant rights under trademark law for use of some trade names, -trademarks, or service marks; or -* **f)** Requiring indemnification of licensors and authors of that material by anyone -who conveys the material (or modified versions of it) with contractual assumptions of -liability to the recipient, for any liability that these contractual assumptions -directly impose on those licensors and authors. - -All other non-permissive additional terms are considered “further -restrictions” within the meaning of section 10. If the Program as you received -it, or any part of it, contains a notice stating that it is governed by this License -along with a term that is a further restriction, you may remove that term. If a -license document contains a further restriction but permits relicensing or conveying -under this License, you may add to a covered work material governed by the terms of -that license document, provided that the further restriction does not survive such -relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in -the relevant source files, a statement of the additional terms that apply to those -files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a -separately written license, or stated as exceptions; the above requirements apply -either way. - -### 8. Termination - -You may not propagate or modify a covered work except as expressly provided under -this License. Any attempt otherwise to propagate or modify it is void, and will -automatically terminate your rights under this License (including any patent licenses -granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a -particular copyright holder is reinstated **(a)** provisionally, unless and until the -copyright holder explicitly and finally terminates your license, and **(b)** permanently, -if the copyright holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently -if the copyright holder notifies you of the violation by some reasonable means, this -is the first time you have received notice of violation of this License (for any -work) from that copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of -parties who have received copies or rights from you under this License. If your -rights have been terminated and not permanently reinstated, you do not qualify to -receive new licenses for the same material under section 10. - -### 9. Acceptance Not Required for Having Copies - -You are not required to accept this License in order to receive or run a copy of the -Program. Ancillary propagation of a covered work occurring solely as a consequence of -using peer-to-peer transmission to receive a copy likewise does not require -acceptance. However, nothing other than this License grants you permission to -propagate or modify any covered work. These actions infringe copyright if you do not -accept this License. Therefore, by modifying or propagating a covered work, you -indicate your acceptance of this License to do so. - -### 10. Automatic Licensing of Downstream Recipients - -Each time you convey a covered work, the recipient automatically receives a license -from the original licensors, to run, modify and propagate that work, subject to this -License. You are not responsible for enforcing compliance by third parties with this -License. - -An “entity transaction” is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an organization, or -merging organizations. If propagation of a covered work results from an entity -transaction, each party to that transaction who receives a copy of the work also -receives whatever licenses to the work the party's predecessor in interest had or -could give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if the predecessor -has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or -affirmed under this License. For example, you may not impose a license fee, royalty, -or other charge for exercise of rights granted under this License, and you may not -initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging -that any patent claim is infringed by making, using, selling, offering for sale, or -importing the Program or any portion of it. - -### 11. Patents - -A “contributor” is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The work thus -licensed is called the contributor's “contributor version”. - -A contributor's “essential patent claims” are all patent claims owned or -controlled by the contributor, whether already acquired or hereafter acquired, that -would be infringed by some manner, permitted by this License, of making, using, or -selling its contributor version, but do not include claims that would be infringed -only as a consequence of further modification of the contributor version. For -purposes of this definition, “control” includes the right to grant patent -sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license -under the contributor's essential patent claims, to make, use, sell, offer for sale, -import and otherwise run, modify and propagate the contents of its contributor -version. - -In the following three paragraphs, a “patent license” is any express -agreement or commitment, however denominated, not to enforce a patent (such as an -express permission to practice a patent or covenant not to sue for patent -infringement). To “grant” such a patent license to a party means to make -such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the -Corresponding Source of the work is not available for anyone to copy, free of charge -and under the terms of this License, through a publicly available network server or -other readily accessible means, then you must either **(1)** cause the Corresponding -Source to be so available, or **(2)** arrange to deprive yourself of the benefit of the -patent license for this particular work, or **(3)** arrange, in a manner consistent with -the requirements of this License, to extend the patent license to downstream -recipients. “Knowingly relying” means you have actual knowledge that, but -for the patent license, your conveying the covered work in a country, or your -recipient's use of the covered work in a country, would infringe one or more -identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you -convey, or propagate by procuring conveyance of, a covered work, and grant a patent -license to some of the parties receiving the covered work authorizing them to use, -propagate, modify or convey a specific copy of the covered work, then the patent -license you grant is automatically extended to all recipients of the covered work and -works based on it. - -A patent license is “discriminatory” if it does not include within the -scope of its coverage, prohibits the exercise of, or is conditioned on the -non-exercise of one or more of the rights that are specifically granted under this -License. You may not convey a covered work if you are a party to an arrangement with -a third party that is in the business of distributing software, under which you make -payment to the third party based on the extent of your activity of conveying the -work, and under which the third party grants, to any of the parties who would receive -the covered work from you, a discriminatory patent license **(a)** in connection with -copies of the covered work conveyed by you (or copies made from those copies), or **(b)** -primarily for and in connection with specific products or compilations that contain -the covered work, unless you entered into that arrangement, or that patent license -was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied -license or other defenses to infringement that may otherwise be available to you -under applicable patent law. - -### 12. No Surrender of Others' Freedom - -If conditions are imposed on you (whether by court order, agreement or otherwise) -that contradict the conditions of this License, they do not excuse you from the -conditions of this License. If you cannot convey a covered work so as to satisfy -simultaneously your obligations under this License and any other pertinent -obligations, then as a consequence you may not convey it at all. For example, if you -agree to terms that obligate you to collect a royalty for further conveying from -those to whom you convey the Program, the only way you could satisfy both those terms -and this License would be to refrain entirely from conveying the Program. - -### 13. Use with the GNU Affero General Public License - -Notwithstanding any other provision of this License, you have permission to link or -combine any covered work with a work licensed under version 3 of the GNU Affero -General Public License into a single combined work, and to convey the resulting work. -The terms of this License will continue to apply to the part which is the covered -work, but the special requirements of the GNU Affero General Public License, section -13, concerning interaction through a network will apply to the combination as such. - -### 14. Revised Versions of this License - -The Free Software Foundation may publish revised and/or new versions of the GNU -General Public License from time to time. Such new versions will be similar in spirit -to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies that -a certain numbered version of the GNU General Public License “or any later -version” applies to it, you have the option of following the terms and -conditions either of that numbered version or of any later version published by the -Free Software Foundation. If the Program does not specify a version number of the GNU -General Public License, you may choose any version ever published by the Free -Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the GNU -General Public License can be used, that proxy's public statement of acceptance of a -version permanently authorizes you to choose that version for the Program. - -Later license versions may give you additional or different permissions. However, no -additional obligations are imposed on any author or copyright holder as a result of -your choosing to follow a later version. - -### 15. Disclaimer of Warranty - -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER -EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE -QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE -DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -### 16. Limitation of Liability - -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY -COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS -PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, -INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE -OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE -WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - -### 17. Interpretation of Sections 15 and 16 - -If the disclaimer of warranty and limitation of liability provided above cannot be -given local legal effect according to their terms, reviewing courts shall apply local -law that most closely approximates an absolute waiver of all civil liability in -connection with the Program, unless a warranty or assumption of liability accompanies -a copy of the Program in return for a fee. - -_END OF TERMS AND CONDITIONS_ - -## How to Apply These Terms to Your New Programs - -If you develop a new program, and you want it to be of the greatest possible use to -the public, the best way to achieve this is to make it free software which everyone -can redistribute and change under these terms. - -To do so, attach the following notices to the program. It is safest to attach them -to the start of each source file to most effectively state the exclusion of warranty; -and each file should have at least the “copyright” line and a pointer to -where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If the program does terminal interaction, make it output a short notice like this -when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type 'show c' for details. - -The hypothetical commands `show w` and `show c` should show the appropriate parts of -the General Public License. Of course, your program's commands might be different; -for a GUI interface, you would use an “about box”. - -You should also get your employer (if you work as a programmer) or school, if any, to -sign a “copyright disclaimer” for the program, if necessary. For more -information on this, and how to apply and follow the GNU GPL, see -<>. - -The GNU General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may consider it -more useful to permit linking proprietary applications with the library. If this is -what you want to do, use the GNU Lesser General Public License instead of this -License. But first, please read -<>. diff --git a/gadgets/README.md b/gadgets/README.md deleted file mode 100644 index fb14195b0e..0000000000 --- a/gadgets/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# leo-gadgets - -[![Crates.io](https://img.shields.io/crates/v/leo-gadgets.svg?color=neon)](https://crates.io/crates/leo-gadgets) -[![Authors](https://img.shields.io/badge/authors-Aleo-orange.svg)](../AUTHORS) -[![License](https://img.shields.io/badge/License-GPLv3-blue.svg)](./LICENSE.md) diff --git a/gadgets/benches/integer_arithmetic.rs b/gadgets/benches/integer_arithmetic.rs deleted file mode 100644 index 2bdd0b7842..0000000000 --- a/gadgets/benches/integer_arithmetic.rs +++ /dev/null @@ -1,430 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::{Add, Div, Mul, Sub}, - int::{Int128, Int16, Int32, Int64, Int8}, -}; -use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; - -use rand::{Rng, SeedableRng}; -use rand_xorshift::XorShiftRng; -use std::i128; - -use criterion::{criterion_group, criterion_main, Criterion}; - -// TODO: move these benchmarks to snarkvm? -macro_rules! create_add_bench { - ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { - fn $bench_name(c: &mut Criterion) { - fn $foo_name(cs: &mut TestConstraintSystem, rng: &mut XorShiftRng) { - let a: $std_type = rng.gen(); - let b: $std_type = rng.gen(); - - if a.checked_add(b).is_none() { - return; - } - - let bench_run_id: u64 = rng.gen(); - - let a_bit = <$bit_type>::alloc(cs.ns(|| format!("{}: a (add)", bench_run_id)), || Ok(a)).unwrap(); - let b_bit = <$bit_type>::alloc(cs.ns(|| format!("{}: b (add)", bench_run_id)), || Ok(b)).unwrap(); - - a_bit - .add(cs.ns(|| format!("{}: a add b", bench_run_id)), &b_bit) - .unwrap(); - } - - let mut cs = TestConstraintSystem::::new(); - - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - c.bench_function(&format!("integer_arithmetic::{}", $bench_id), |b| { - b.iter(|| $foo_name(&mut cs, &mut rng)) - }); - } - }; -} - -macro_rules! create_add_bench_const { - ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { - fn $bench_name(c: &mut Criterion) { - fn $foo_name(cs: &mut TestConstraintSystem, rng: &mut XorShiftRng) { - let a: $std_type = rng.gen(); - let b: $std_type = rng.gen(); - - if a.checked_add(b).is_none() { - return; - } - - let bench_run_id: u64 = rng.gen(); - - let a_bit_const = <$bit_type>::constant(a); - let b_bit_const = <$bit_type>::constant(b); - a_bit_const - .add( - cs.ns(|| format!("{}: a add b: const", bench_run_id)), - &b_bit_const, - ) - .unwrap(); - } - - let mut cs = TestConstraintSystem::::new(); - - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - c.bench_function(&format!("integer_arithmetic::{}", $bench_id), |b| { - b.iter(|| $foo_name(&mut cs, &mut rng)) - }); - } - }; -} - -macro_rules! create_sub_bench { - ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { - fn $bench_name(c: &mut Criterion) { - fn $foo_name(cs: &mut TestConstraintSystem, rng: &mut XorShiftRng) { - let a: $std_type = rng.gen(); - let b: $std_type = rng.gen(); - - if b.checked_neg().is_none() || a.checked_sub(b).is_none() { - return; - } - - let bench_run_id: u64 = rng.gen(); - - let a_bit = <$bit_type>::alloc(cs.ns(|| format!("{}: a (sub)", bench_run_id)), || Ok(a)).unwrap(); - let b_bit = <$bit_type>::alloc(cs.ns(|| format!("{}: b (sub)", bench_run_id)), || Ok(b)).unwrap(); - - a_bit - .sub(cs.ns(|| format!("{}: a sub b", bench_run_id)), &b_bit) - .unwrap(); - } - - let mut cs = TestConstraintSystem::::new(); - - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - c.bench_function(&format!("integer_arithmetic::{}", $bench_id), |b| { - b.iter(|| $foo_name(&mut cs, &mut rng)) - }); - } - }; -} - -macro_rules! create_sub_bench_const { - ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { - fn $bench_name(c: &mut Criterion) { - fn $foo_name(cs: &mut TestConstraintSystem, rng: &mut XorShiftRng) { - let a: $std_type = rng.gen(); - let b: $std_type = rng.gen(); - - if b.checked_neg().is_none() || a.checked_sub(b).is_none() { - return; - } - - let bench_run_id: u64 = rng.gen(); - - let a_bit_const = <$bit_type>::constant(a); - let b_bit_const = <$bit_type>::constant(b); - a_bit_const - .sub( - cs.ns(|| format!("{}: a sub b: const", bench_run_id)), - &b_bit_const, - ) - .unwrap(); - } - - let mut cs = TestConstraintSystem::::new(); - - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - c.bench_function(&format!("integer_arithmetic::{}", $bench_id), |b| { - b.iter(|| $foo_name(&mut cs, &mut rng)) - }); - } - }; -} - -macro_rules! create_mul_bench { - ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { - fn $bench_name(c: &mut Criterion) { - fn $foo_name(cs: &mut TestConstraintSystem, rng: &mut XorShiftRng) { - let a: $std_type = rng.gen(); - let b: $std_type = rng.gen(); - - if a.checked_mul(b).is_none() { - return; - } - - let bench_run_id: u64 = rng.gen(); - - let a_bit = <$bit_type>::alloc(cs.ns(|| format!("{}: a (mul)", bench_run_id)), || Ok(a)).unwrap(); - let b_bit = <$bit_type>::alloc(cs.ns(|| format!("{}: b (mul)", bench_run_id)), || Ok(b)).unwrap(); - a_bit - .mul(cs.ns(|| format!("{}: a mul b", bench_run_id)), &b_bit) - .unwrap(); - } - - let mut cs = TestConstraintSystem::::new(); - - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - c.bench_function(&format!("integer_arithmetic::{}", $bench_id), |b| { - b.iter(|| $foo_name(&mut cs, &mut rng)) - }); - } - }; -} - -macro_rules! create_mul_bench_const { - ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { - fn $bench_name(c: &mut Criterion) { - fn $foo_name(cs: &mut TestConstraintSystem, rng: &mut XorShiftRng) { - let a: $std_type = rng.gen(); - let b: $std_type = rng.gen(); - - if a.checked_mul(b).is_none() { - return; - } - - let bench_run_id: u64 = rng.gen(); - - let a_bit_const = <$bit_type>::constant(a); - let b_bit_const = <$bit_type>::constant(b); - a_bit_const - .mul( - cs.ns(|| format!("{}: a mul b: const", bench_run_id)), - &b_bit_const, - ) - .unwrap(); - } - - let mut cs = TestConstraintSystem::::new(); - - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - c.bench_function(&format!("integer_arithmetic::{}", $bench_id), |b| { - b.iter(|| $foo_name(&mut cs, &mut rng)) - }); - } - }; -} - -macro_rules! create_div_bench { - ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { - fn $bench_name(c: &mut Criterion) { - fn $foo_name(cs: &mut TestConstraintSystem, rng: &mut XorShiftRng) { - let a: $std_type = rng.gen(); - let b: $std_type = rng.gen(); - - if a.checked_neg().is_none() || a.checked_div(b).is_none() { - return; - } - - let bench_run_id: u64 = rng.gen(); - - let a_bit = <$bit_type>::alloc(cs.ns(|| format!("{}: a (div)", bench_run_id)), || Ok(a)).unwrap(); - let b_bit = <$bit_type>::alloc(cs.ns(|| format!("{}: b (div)", bench_run_id)), || Ok(b)).unwrap(); - a_bit - .div(cs.ns(|| format!("{}: a div b", bench_run_id)), &b_bit) - .unwrap(); - } - - let mut cs = TestConstraintSystem::::new(); - - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - c.bench_function(&format!("integer_arithmetic::{}", $bench_id), |b| { - b.iter(|| $foo_name(&mut cs, &mut rng)) - }); - } - }; -} - -macro_rules! create_div_bench_const { - ($bench_name:ident, $bench_id:expr, $foo_name:ident, $std_type:ty, $bit_type:ty) => { - fn $bench_name(c: &mut Criterion) { - fn $foo_name(cs: &mut TestConstraintSystem, rng: &mut XorShiftRng) { - let a: $std_type = rng.gen(); - let b: $std_type = rng.gen(); - - if a.checked_neg().is_none() || a.checked_div(b).is_none() { - return; - } - - let bench_run_id: u64 = rng.gen(); - - let a_bit_const = <$bit_type>::constant(a); - let b_bit_const = <$bit_type>::constant(b); - a_bit_const - .div( - cs.ns(|| format!("{}: a div b: const", bench_run_id)), - &b_bit_const, - ) - .unwrap(); - } - - let mut cs = TestConstraintSystem::::new(); - - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - c.bench_function(&format!("integer_arithmetic::{}", $bench_id), |b| { - b.iter(|| $foo_name(&mut cs, &mut rng)) - }); - } - }; -} - -create_add_bench!(bench_i8_add, "i8_add", i8_add, i8, Int8); -create_add_bench!(bench_i16_add, "i16_add", i16_add, i16, Int16); -create_add_bench!(bench_i32_add, "i32_add", i32_add, i32, Int32); -create_add_bench!(bench_i64_add, "i64_add", i64_add, i64, Int64); -create_add_bench!(bench_i128_add, "i128_add", i128_add, i128, Int128); - -create_add_bench_const!(bench_i8_add_const, "i8_add_const", i8_add, i8, Int8); -create_add_bench_const!(bench_i16_add_const, "i16_add_const", i16_add, i16, Int16); -create_add_bench_const!(bench_i32_add_const, "i32_add_const", i32_add, i32, Int32); -create_add_bench_const!(bench_i64_add_const, "i64_add_const", i64_add, i64, Int64); -create_add_bench_const!(bench_i128_add_const, "i128_add_const", i128_add, i128, Int128); - -create_sub_bench!(bench_i8_sub, "i8_sub", i8_sub, i8, Int8); -create_sub_bench!(bench_i16_sub, "i16_sub", i16_sub, i16, Int16); -create_sub_bench!(bench_i32_sub, "i32_sub", i32_sub, i32, Int32); -create_sub_bench!(bench_i64_sub, "i64_sub", i64_sub, i64, Int64); -create_sub_bench!(bench_i128_sub, "i128_sub", i128_sub, i128, Int128); - -create_sub_bench_const!(bench_i8_sub_const, "i8_sub_const", i8_sub, i8, Int8); -create_sub_bench_const!(bench_i16_sub_const, "i16_sub_const", i16_sub, i16, Int16); -create_sub_bench_const!(bench_i32_sub_const, "i32_sub_const", i32_sub, i32, Int32); -create_sub_bench_const!(bench_i64_sub_const, "i64_sub_const", i64_sub, i64, Int64); -create_sub_bench_const!(bench_i128_sub_const, "i128_sub_const", i128_sub, i128, Int128); - -create_mul_bench!(bench_i8_mul, "i8_mul", i8_mul, i8, Int8); -create_mul_bench!(bench_i16_mul, "i16_mul", i16_mul, i16, Int16); -create_mul_bench!(bench_i32_mul, "i32_mul", i32_mul, i32, Int32); -create_mul_bench!(bench_i64_mul, "i64_mul", i64_mul, i64, Int64); -create_mul_bench!(bench_i128_mul, "i128_mul", i128_mul, i128, Int128); - -create_mul_bench_const!(bench_i8_mul_const, "i8_mul_const", i8_mul, i8, Int8); -create_mul_bench_const!(bench_i16_mul_const, "i16_mul_const", i16_mul, i16, Int16); -create_mul_bench_const!(bench_i32_mul_const, "i32_mul_const", i32_mul, i32, Int32); -create_mul_bench_const!(bench_i64_mul_const, "i64_mul_const", i64_mul, i64, Int64); -create_mul_bench_const!(bench_i128_mul_const, "i128_mul_const", i128_mul, i128, Int128); - -create_div_bench!(bench_i8_div, "i8_div", i8_div, i8, Int8); -create_div_bench!(bench_i16_div, "i16_div", i16_div, i16, Int16); -create_div_bench!(bench_i32_div, "i32_div", i32_div, i32, Int32); -// create_div_bench!(bench_i64_div, "i64_div", i64_div, i64, Int64); -// create_div_bench!(bench_i128_div, "i128_div", i128_div, i128, Int128); - -create_div_bench_const!(bench_i8_div_const, "i8_div_const", i8_div, i8, Int8); -create_div_bench_const!(bench_i16_div_const, "i16_div_const", i16_div, i16, Int16); -create_div_bench_const!(bench_i32_div_const, "i32_div_const", i32_div, i32, Int32); -// create_div_bench_const!(bench_i64_div_const, "i64_div_const", i64_div, i64, Int64); -// create_div_bench_const!(bench_i128_div_const, "i128_div_const", i128_div, i128, Int128); - -criterion_group!( - name = benches_add; - config = Criterion::default(); - targets = bench_i8_add, - bench_i16_add, - bench_i32_add, - bench_i64_add, - bench_i128_add, -); - -criterion_group!( - name = benches_add_const; - config = Criterion::default(); - targets = bench_i8_add_const, - bench_i16_add_const, - bench_i32_add_const, - bench_i64_add_const, - bench_i128_add_const, -); - -criterion_group!( - name = benches_sub; - config = Criterion::default(); - targets = bench_i8_sub, - bench_i16_sub, - bench_i32_sub, - bench_i64_sub, - bench_i128_sub, -); - -criterion_group!( - name = benches_sub_const; - config = Criterion::default(); - targets = bench_i8_sub_const, - bench_i16_sub_const, - bench_i32_sub_const, - bench_i64_sub_const, - bench_i128_sub_const, -); - -criterion_group!( - name = benches_mul; - config = Criterion::default(); - targets = bench_i8_mul, - bench_i16_mul, - bench_i32_mul, - bench_i64_mul, - bench_i128_mul, -); - -criterion_group!( - name = benches_mul_const; - config = Criterion::default(); - targets = bench_i8_mul_const, - bench_i16_mul_const, - bench_i32_mul_const, - bench_i64_mul_const, - bench_i128_mul_const, -); - -criterion_group!( - name = benches_div; - config = Criterion::default(); - targets = bench_i8_div, - bench_i16_div, - bench_i32_div, - // bench_i64_div, - // bench_i128_div, -); - -criterion_group!( - name = benches_div_const; - config = Criterion::default(); - targets = bench_i8_div_const, - bench_i16_div_const, - bench_i32_div_const, - // bench_i64_div_const, - // bench_i128_div_const, -); - -criterion_main!( - benches_add, - benches_add_const, - benches_sub, - benches_sub_const, - benches_mul, - benches_mul_const, - benches_div, - benches_div_const -); diff --git a/gadgets/src/bits/adder.rs b/gadgets/src/bits/adder.rs deleted file mode 100644 index 9ebc028a7e..0000000000 --- a/gadgets/src/bits/adder.rs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use snarkvm_fields::Field; -use snarkvm_gadgets::traits::utilities::boolean::Boolean; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -/// Single bit binary adder with carry bit -/// https://en.wikipedia.org/wiki/Adder_(electronics)#Full_adder -/// sum = (a XOR b) XOR carry -/// carry = a AND b OR carry AND (a XOR b) -/// Returns (sum, carry) -pub trait FullAdder<'a, F: Field> -where - Self: std::marker::Sized, -{ - fn add>( - cs: CS, - a: &'a Self, - b: &'a Self, - carry: &'a Self, - ) -> Result<(Self, Self), SynthesisError>; -} - -impl<'a, F: Field> FullAdder<'a, F> for Boolean { - fn add>( - mut cs: CS, - a: &'a Self, - b: &'a Self, - carry: &'a Self, - ) -> Result<(Self, Self), SynthesisError> { - let a_x_b = Boolean::xor(cs.ns(|| "a XOR b"), a, b)?; - let sum = Boolean::xor(cs.ns(|| "adder sum"), &a_x_b, carry)?; - - let c1 = Boolean::and(cs.ns(|| "a AND b"), a, b)?; - let c2 = Boolean::and(cs.ns(|| "carry AND (a XOR b)"), carry, &a_x_b)?; - let carry = Boolean::or(cs.ns(|| "c1 OR c2"), &c1, &c2)?; - - Ok((sum, carry)) - } -} diff --git a/gadgets/src/bits/mod.rs b/gadgets/src/bits/mod.rs deleted file mode 100644 index d1898884dc..0000000000 --- a/gadgets/src/bits/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#[macro_use] -pub mod adder; -pub use self::adder::*; - -pub mod rca; -pub use self::rca::*; diff --git a/gadgets/src/bits/rca.rs b/gadgets/src/bits/rca.rs deleted file mode 100644 index 86b7a8cf65..0000000000 --- a/gadgets/src/bits/rca.rs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use snarkvm_fields::{Field, PrimeField}; -use snarkvm_gadgets::traits::utilities::boolean::Boolean; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -/// Returns the bitwise sum of a n-bit number with carry bit -pub trait RippleCarryAdder -where - Self: std::marker::Sized, -{ - fn add_bits>(&self, cs: CS, other: &Self) -> Result, SynthesisError>; -} - -// Generic impl -impl RippleCarryAdder for Vec { - fn add_bits>(&self, mut cs: CS, other: &Self) -> Result, SynthesisError> { - let mut result = Vec::with_capacity(self.len() + 1); - let mut carry = Boolean::constant(false); - for (i, (a, b)) in self.iter().zip(other.iter()).enumerate() { - let (sum, next) = Boolean::add(cs.ns(|| format!("rpc {}", i)), a, b, &carry)?; - - carry = next; - result.push(sum); - } - - // append the carry bit to the end - result.push(carry); - - Ok(result) - } -} - -macro_rules! rpc_impl { - ($($gadget: ident)*) => ($( - impl RippleCarryAdder for $gadget { - fn add_bits>(&self, cs: CS, other: &Self) -> Result, SynthesisError> { - self.bits.add_bits(cs, &other.bits) - } - } - )*) -} - -rpc_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/errors/mod.rs b/gadgets/src/errors/mod.rs deleted file mode 100644 index 39c7dd79cc..0000000000 --- a/gadgets/src/errors/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -pub mod signed_integer; -pub use self::signed_integer::*; diff --git a/gadgets/src/errors/signed_integer.rs b/gadgets/src/errors/signed_integer.rs deleted file mode 100644 index 8998531882..0000000000 --- a/gadgets/src/errors/signed_integer.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use snarkvm_r1cs::SynthesisError; - -#[derive(Debug, Error)] -pub enum SignedIntegerError { - #[error("Integer overflow")] - Overflow, - - #[error("Division by zero")] - DivisionByZero, - - #[error("{}", _0)] - SynthesisError(#[from] SynthesisError), -} diff --git a/gadgets/src/lib.rs b/gadgets/src/lib.rs deleted file mode 100644 index d2ba9d58da..0000000000 --- a/gadgets/src/lib.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -// #[macro_use] -// extern crate thiserror; - -// pub mod bits; - -// pub mod errors; - -// pub mod signed_integer; -// pub use self::signed_integer::*; diff --git a/gadgets/src/signed_integer/arithmetic/add.rs b/gadgets/src/signed_integer/arithmetic/add.rs deleted file mode 100644 index ba4606726c..0000000000 --- a/gadgets/src/signed_integer/arithmetic/add.rs +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{bits::RippleCarryAdder, errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64}; - -use snarkvm_fields::{fp_parameters::FpParameters, PrimeField}; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::Add, - boolean::{AllocatedBit, Boolean}, -}; -use snarkvm_r1cs::{Assignment, ConstraintSystem, LinearCombination}; - -macro_rules! add_int_impl { - ($($gadget: ident)*) => ($( - impl Add for $gadget { - type ErrorType = SignedIntegerError; - - fn add>(&self, mut cs: CS, other: &Self) -> Result { - // Compute the maximum value of the sum - let max_bits = <$gadget as Int>::SIZE; - - // Make some arbitrary bounds for ourselves to avoid overflows - // in the scalar field - assert!(F::Parameters::MODULUS_BITS >= max_bits as u32); - - // Accumulate the value - let result_value = match (self.value, other.value) { - (Some(a), Some(b)) => { - // check for addition overflow here - let val = match a.checked_add(b) { - Some(val) => val, - None => return Err(SignedIntegerError::Overflow) - }; - - Some(val) - }, - _ => { - // If any of the operands have unknown value, we won't - // know the value of the result - None - } - }; - - // This is a linear combination that we will enforce to be zero - let mut lc = LinearCombination::zero(); - - let mut all_constants = true; - - let mut bits = self.add_bits(cs.ns(|| format!("bits")), other)?; - - // we discard the carry since we check for overflow above - let _carry = bits.pop(); - - // Iterate over each bit_gadget of result and add each bit to - // the linear combination - let mut coeff = F::one(); - for bit in bits { - match bit { - Boolean::Is(ref bit) => { - all_constants = false; - - // Add the coeff * bit_gadget - lc += (coeff, bit.get_variable()); - } - Boolean::Not(ref bit) => { - all_constants = false; - - // Add coeff * (1 - bit_gadget) = coeff * ONE - coeff * bit_gadget - lc = lc + (coeff, CS::one()) - (coeff, bit.get_variable()); - } - Boolean::Constant(bit) => { - if bit { - lc += (coeff, CS::one()); - } - } - } - - coeff.double_in_place(); - } - - - // The value of the actual result is modulo 2 ^ $size - let modular_value = result_value.map(|v| v as <$gadget as Int>::IntegerType); - - if all_constants && modular_value.is_some() { - // We can just return a constant, rather than - // unpacking the result into allocated bits. - - return Ok(Self::constant(modular_value.unwrap())); - } - - // Storage area for the resulting bits - let mut result_bits = Vec::with_capacity(max_bits); - - // Allocate each bit_gadget of the result - let mut coeff = F::one(); - for i in 0..max_bits { - // get bit value - let mask = 1 << i as <$gadget as Int>::IntegerType; - - // Allocate the bit_gadget - let b = AllocatedBit::alloc(cs.ns(|| format!("result bit_gadget {}", i)), || { - result_value.map(|v| (v & mask) == mask).get() - })?; - - // Subtract this bit_gadget from the linear combination to ensure that the sums - // balance out - lc = lc - (coeff, b.get_variable()); - - result_bits.push(b.into()); - - coeff.double_in_place(); - } - - // Enforce that the linear combination equals zero - cs.enforce(|| "modular addition", |lc| lc, |lc| lc, |_| lc); - - // Discard carry bits we don't care about - result_bits.truncate(<$gadget as Int>::SIZE); - - Ok(Self { - bits: result_bits, - value: modular_value, - }) - } - } - )*) -} - -add_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/div.rs b/gadgets/src/signed_integer/arithmetic/div.rs deleted file mode 100644 index eb2cad506a..0000000000 --- a/gadgets/src/signed_integer/arithmetic/div.rs +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64}; -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::{Add, Div, Neg, Sub}, - bits::ComparatorGadget, - boolean::{AllocatedBit, Boolean}, - eq::EvaluateEqGadget, - select::CondSelectGadget, -}; -use snarkvm_r1cs::ConstraintSystem; - -macro_rules! div_int_impl { - ($($gadget:ident),*) => ($( - impl Div for $gadget { - type ErrorType = SignedIntegerError; - - fn div>( - &self, - mut cs: CS, - other: &Self - ) -> Result { - // N / D pseudocode: - // - // if D = 0 then error(DivisionByZeroException) end - // - // positive = msb(N) == msb(D) -- if msb's equal, return positive result - // - // Q := 0 -- Initialize quotient and remainder to zero - // R := 0 - // - // for i := n − 1 .. 0 do -- Where n is number of bits in N - // R := R << 1 -- Left-shift R by 1 bit - // R(0) := N(i) -- Set the least-significant bit of R equal to bit i of the numerator - // if R ≥ D then - // R := R − D - // Q(i) := 1 - // end - // end - // - // if positive then -- positive result - // Q - // else - // !Q -- negative result - - if other.eq(&Self::constant(0 as <$gadget as Int>::IntegerType)) { - return Err(SignedIntegerError::DivisionByZero); - } - - let is_constant = Boolean::constant(Self::result_is_constant(&self, &other)); - - let allocated_true = Boolean::from(AllocatedBit::alloc(&mut cs.ns(|| "true"), || Ok(true)).unwrap()); - let true_bit = Boolean::conditionally_select( - &mut cs.ns(|| "constant_or_allocated_true"), - &is_constant, - &Boolean::constant(true), - &allocated_true, - )?; - - let allocated_one = Self::alloc(&mut cs.ns(|| "one"), || Ok(1 as <$gadget as Int>::IntegerType))?; - let one = Self::conditionally_select( - &mut cs.ns(|| "constant_or_allocated_1"), - &is_constant, - &Self::constant(1 as <$gadget as Int>::IntegerType), - &allocated_one, - )?; - - let allocated_zero = Self::alloc(&mut cs.ns(|| "zero"), || Ok(0 as <$gadget as Int>::IntegerType))?; - let zero = Self::conditionally_select( - &mut cs.ns(|| "constant_or_allocated_0"), - &is_constant, - &Self::constant(0 as <$gadget as Int>::IntegerType), - &allocated_zero, - )?; - - // if the numerator is 0, return 0 - let self_is_zero = Boolean::Constant(self.eq(&Self::constant(0 as <$gadget as Int>::IntegerType))); - - // if other is the minimum number, the result will be zero or one - // -128 / -128 = 1 - // x / -128 = 0 fractional result rounds to 0 - let min = Self::constant(<$gadget as Int>::IntegerType::MIN); - let other_is_min = other.evaluate_equal( - &mut cs.ns(|| "other_min_check"), - &min - )?; - let self_is_min = self.evaluate_equal( - &mut cs.ns(|| "self_min_check"), - &min - )?; - let both_min = Boolean::and( - &mut cs.ns(|| "both_min"), - &other_is_min, - &self_is_min - )?; - - - // if other is the minimum, set other to -1 so the calculation will not fail - let negative_one = allocated_one.neg(&mut cs.ns(|| "allocated_one"))?; - let a_valid = min.add(&mut cs.ns(||"a_valid"), &allocated_one); - let a_set = Self::conditionally_select( - &mut cs.ns(|| "a_set"), - &self_is_min, - &a_valid?, - &self - )?; - - let b_set = Self::conditionally_select( - &mut cs.ns(|| "b_set"), - &other_is_min, - &negative_one, - &other - )?; - - // If the most significant bits of both numbers are equal, the quotient will be positive - let b_msb = other.bits.last().unwrap(); - let a_msb = self.bits.last().unwrap(); - let positive = a_msb.evaluate_equal(cs.ns(|| "compare_msb"), &b_msb)?; - - // Get the absolute value of each number - let a_comp = a_set.neg(&mut cs.ns(|| "a_neg"))?; - let a = Self::conditionally_select( - &mut cs.ns(|| "a_abs"), - &a_msb, - &a_comp, - &self - )?; - - let b_comp = b_set.neg(&mut cs.ns(|| "b_neg"))?; - let b = Self::conditionally_select( - &mut cs.ns(|| "b_abs"), - &b_msb, - &b_comp, - &b_set, - )?; - - let mut q = zero.clone(); - let mut r = zero; - - let mut index = <$gadget as Int>::SIZE - 1 as usize; - let mut bit_value = (1 as <$gadget as Int>::IntegerType) << ((index - 1) as <$gadget as Int>::IntegerType); - - for (i, bit) in a.bits.iter().rev().enumerate().skip(1) { - - // Left shift remainder by 1 - r = r.add( - &mut cs.ns(|| format!("shift_left_{}", i)), - &r - )?; - - // Set the least-significant bit of remainder to bit i of the numerator - let r_new = r.add( - &mut cs.ns(|| format!("set_remainder_bit_{}", i)), - &one, - )?; - - r = Self::conditionally_select( - &mut cs.ns(|| format!("increment_or_remainder_{}", i)), - &bit, - &r_new, - &r - )?; - - let can_sub = r.greater_than_or_equal( - &mut cs.ns(|| format!("compare_remainder_{}", i)), - &b - )?; - - let sub = r.sub( - &mut cs.ns(|| format!("subtract_divisor_{}", i)), - &b - )?; - - r = Self::conditionally_select( - &mut cs.ns(|| format!("subtract_or_same_{}", i)), - &can_sub, - &sub, - &r - )?; - - index -= 1; - - let mut q_new = q.clone(); - q_new.bits[index] = true_bit; - if let Some(ref mut value) = q_new.value { - *value += bit_value; - } - - bit_value >>= 1; - - q = Self::conditionally_select( - &mut cs.ns(|| format!("set_bit_or_same_{}", i)), - &can_sub, - &q_new, - &q, - )?; - - } - - let q_neg = q.neg(&mut cs.ns(|| "negate"))?; - - q = Self::conditionally_select( - &mut cs.ns(|| "positive or negative"), - &positive, - &q, - &q_neg, - )?; - - // set to zero if we know result is fractional - q = Self::conditionally_select( - &mut cs.ns(|| "fraction"), - &other_is_min, - &allocated_zero, - &q, - )?; - - // set to one if we know result is division of the minimum number by itself - q = Self::conditionally_select( - &mut cs.ns(|| "one_result"), - &both_min, - &allocated_one, - &q, - )?; - - Ok(Self::conditionally_select( - &mut cs.ns(|| "self_or_quotient"), - &self_is_zero, - self, - &q - )?) - } - } - )*) -} - -div_int_impl!(Int16, Int32, Int64, Int128); diff --git a/gadgets/src/signed_integer/arithmetic/mod.rs b/gadgets/src/signed_integer/arithmetic/mod.rs deleted file mode 100644 index 69fc0f7f7b..0000000000 --- a/gadgets/src/signed_integer/arithmetic/mod.rs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#[macro_use] -pub mod add; -pub use self::add::*; - -pub mod div; -pub use self::div::*; - -pub mod mul; -pub use self::mul::*; - -pub mod neg; -pub use self::neg::*; - -pub mod pow; -pub use self::pow::*; - -pub mod sub; -pub use self::sub::*; diff --git a/gadgets/src/signed_integer/arithmetic/mul.rs b/gadgets/src/signed_integer/arithmetic/mul.rs deleted file mode 100644 index 6b21178307..0000000000 --- a/gadgets/src/signed_integer/arithmetic/mul.rs +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{bits::RippleCarryAdder, errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64}; -use snarkvm_fields::{FpParameters, PrimeField}; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::Mul, - bits::SignExtend, - boolean::{AllocatedBit, Boolean}, - select::CondSelectGadget, -}; -use snarkvm_r1cs::{Assignment, ConstraintSystem, LinearCombination}; - -use std::iter; - -macro_rules! mul_int_impl { - ($($gadget: ident)*) => ($( - /// Bitwise multiplication of two signed integer objects. - impl Mul for $gadget { - - type ErrorType = SignedIntegerError; - - fn mul>(&self, mut cs: CS, other: &Self) -> Result { - // pseudocode: - // - // res = 0; - // for (i, bit) in other.bits.enumerate() { - // shifted_self = self << i; - // - // if bit { - // res += shifted_self; - // } - // } - // return res - - - // Conditionally select constant result - let is_constant = Boolean::constant(Self::result_is_constant(&self, &other)); - let allocated_false = Boolean::from(AllocatedBit::alloc(&mut cs.ns(|| "false"), || Ok(false)).unwrap()); - let false_bit = Boolean::conditionally_select( - &mut cs.ns(|| "constant_or_allocated_false"), - &is_constant, - &Boolean::constant(false), - &allocated_false, - )?; - - // Sign extend to double precision - let size = <$gadget as Int>::SIZE * 2; - - let a = Boolean::sign_extend(&self.bits, size); - let b = Boolean::sign_extend(&other.bits, size); - - let mut bits = vec![false_bit; size]; - - // Compute double and add algorithm - let mut to_add = Vec::new(); - let mut a_shifted = Vec::new(); - for (i, b_bit) in b.iter().enumerate() { - // double - a_shifted.extend(iter::repeat(false_bit).take(i)); - a_shifted.extend(a.iter()); - a_shifted.truncate(size); - - // conditionally add - to_add.reserve(a_shifted.len()); - for (j, a_bit) in a_shifted.iter().enumerate() { - let selected_bit = Boolean::conditionally_select( - &mut cs.ns(|| format!("select product bit {} {}", i, j)), - b_bit, - a_bit, - &false_bit, - )?; - - to_add.push(selected_bit); - } - - bits = bits.add_bits( - &mut cs.ns(|| format!("add bit {}", i)), - &to_add - )?; - let _carry = bits.pop(); - to_add.clear(); - a_shifted.clear(); - } - drop(to_add); - drop(a_shifted); - - // Compute the maximum value of the sum - let max_bits = <$gadget as Int>::SIZE; - - // Truncate the bits to the size of the integer - bits.truncate(max_bits); - - // Make some arbitrary bounds for ourselves to avoid overflows - // in the scalar field - assert!(F::Parameters::MODULUS_BITS >= max_bits as u32); - - // Accumulate the value - let result_value = match (self.value, other.value) { - (Some(a), Some(b)) => { - // check for multiplication overflow here - let val = match a.checked_mul(b) { - Some(val) => val, - None => return Err(SignedIntegerError::Overflow) - }; - - Some(val) - }, - _ => { - // If any of the operands have unknown value, we won't - // know the value of the result - None - } - }; - - // This is a linear combination that we will enforce to be zero - let mut lc = LinearCombination::zero(); - - let mut all_constants = true; - - - // Iterate over each bit_gadget of result and add each bit to - // the linear combination - let mut coeff = F::one(); - for bit in bits { - match bit { - Boolean::Is(ref bit) => { - all_constants = false; - - // Add the coeff * bit_gadget - lc += (coeff, bit.get_variable()); - } - Boolean::Not(ref bit) => { - all_constants = false; - - // Add coeff * (1 - bit_gadget) = coeff * ONE - coeff * bit_gadget - lc = lc + (coeff, CS::one()) - (coeff, bit.get_variable()); - } - Boolean::Constant(bit) => { - if bit { - lc += (coeff, CS::one()); - } - } - } - - coeff.double_in_place(); - } - - // The value of the actual result is modulo 2 ^ $size - let modular_value = result_value.map(|v| v as <$gadget as Int>::IntegerType); - - if all_constants && modular_value.is_some() { - // We can just return a constant, rather than - // unpacking the result into allocated bits. - - return Ok(Self::constant(modular_value.unwrap())); - } - - // Storage area for the resulting bits - let mut result_bits = Vec::with_capacity(max_bits); - - // Allocate each bit_gadget of the result - let mut coeff = F::one(); - for i in 0..max_bits { - // get bit value - let mask = 1 << i as <$gadget as Int>::IntegerType; - - // Allocate the bit_gadget - let b = AllocatedBit::alloc(cs.ns(|| format!("result bit_gadget {}", i)), || { - result_value.map(|v| (v & mask) == mask).get() - })?; - - // Subtract this bit_gadget from the linear combination to ensure that the sums - // balance out - lc = lc - (coeff, b.get_variable()); - - result_bits.push(b.into()); - - coeff.double_in_place(); - } - - // Enforce that the linear combination equals zero - cs.enforce(|| "modular multiplication", |lc| lc, |lc| lc, |_| lc); - - // Discard carry bits we don't care about - result_bits.truncate(<$gadget as Int>::SIZE); - - Ok(Self { - bits: result_bits, - value: modular_value, - }) - } - } - )*) -} - -mul_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/neg.rs b/gadgets/src/signed_integer/arithmetic/neg.rs deleted file mode 100644 index bd213aab7c..0000000000 --- a/gadgets/src/signed_integer/arithmetic/neg.rs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{errors::SignedIntegerError, signed_integer::*}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::utilities::arithmetic::Neg; -use snarkvm_r1cs::ConstraintSystem; - -macro_rules! neg_int_impl { - ($($gadget: ident)*) => ($( - impl Neg for $gadget { - type ErrorType = SignedIntegerError; - - fn neg>( - &self, - cs: CS - ) -> Result { - let value = match self.value { - Some(val) => { - match val.checked_neg() { - Some(val_neg) => Some(val_neg), - None => return Err(SignedIntegerError::Overflow) // -0 should fail - } - } - None => None, - }; - - // calculate two's complement - let bits = self.bits.neg(cs)?; - - Ok(Self { - bits, - value, - }) - } - } - )*) -} - -neg_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/pow.rs b/gadgets/src/signed_integer/arithmetic/pow.rs deleted file mode 100644 index f5994fa926..0000000000 --- a/gadgets/src/signed_integer/arithmetic/pow.rs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{errors::SignedIntegerError, Int, Int128, Int16, Int32, Int64}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::{Mul, Pow}, - boolean::Boolean, - select::CondSelectGadget, -}; -use snarkvm_r1cs::ConstraintSystem; - -macro_rules! pow_int_impl { - ($($gadget:ty)*) => ($( - impl Pow for $gadget { - type ErrorType = SignedIntegerError; - - fn pow>(&self, mut cs: CS, other: &Self) -> Result { - // let mut res = Self::one(); - // - // let mut found_one = false; - // - // for i in BitIterator::new(exp) { - // - // res.square_in_place(); - // - // if i { - // res *= self; - // } - // } - // res - - let is_constant = Boolean::constant(Self::result_is_constant(&self, &other)); - let one_const = Self::constant(1 as <$gadget as Int>::IntegerType); - let one_alloc = Self::alloc(&mut cs.ns(|| "allocated_1"), || Ok(1 as <$gadget as Int>::IntegerType))?; - let mut result = Self::conditionally_select( - &mut cs.ns(|| "constant_or_allocated"), - &is_constant, - &one_const, - &one_alloc, - )?; - - for (i, bit) in other.bits.iter().rev().enumerate() { - result = result.mul(cs.ns(|| format!("square_{}", i)), &result).unwrap(); - - let mul_by_self = result - .mul(cs.ns(|| format!("multiply_by_self_{}", i)), &self); - - result = Self::conditionally_select( - &mut cs.ns(|| format!("mul_by_self_or_result_{}", i)), - bit, - &mul_by_self?, - &result, - )?; - - } - Ok(result) - } - } - )*) -} - -pow_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/arithmetic/sub.rs b/gadgets/src/signed_integer/arithmetic/sub.rs deleted file mode 100644 index 63be7ed4b0..0000000000 --- a/gadgets/src/signed_integer/arithmetic/sub.rs +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{errors::SignedIntegerError, Int128, Int16, Int32, Int64}; -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::utilities::arithmetic::{Add, Neg, Sub}; -use snarkvm_r1cs::ConstraintSystem; - -macro_rules! sub_int_impl { - ($($gadget: ident)*) => ($( - impl Sub for $gadget { - type ErrorType = SignedIntegerError; - - fn sub>(&self, mut cs: CS, other: &Self) -> Result { - // Negate other - let other_neg = other.neg(cs.ns(|| format!("negate")))?; - - // self + negated other - self.add(cs.ns(|| format!("add_complement")), &other_neg) - } - } - )*) -} - -sub_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/int_impl.rs b/gadgets/src/signed_integer/int_impl.rs deleted file mode 100644 index ac4b3748cc..0000000000 --- a/gadgets/src/signed_integer/int_impl.rs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use snarkvm_gadgets::traits::utilities::boolean::Boolean; - -use std::fmt::Debug; - -pub trait Int: Debug + Clone { - type IntegerType; - const SIZE: usize; - - fn one() -> Self; - - fn zero() -> Self; - - /// Returns true if all bits in this `Int` are constant - fn is_constant(&self) -> bool; - - /// Returns true if both `Int` objects have constant bits - fn result_is_constant(first: &Self, second: &Self) -> bool { - first.is_constant() && second.is_constant() - } -} - -/// Implements the base struct for a signed integer gadget -macro_rules! int_impl { - ($name: ident, $type_: ty, $size: expr) => { - #[derive(Clone, Debug)] - pub struct $name { - pub bits: Vec, - pub value: Option<$type_>, - } - - impl $name { - pub fn constant(value: $type_) -> Self { - let mut bits = Vec::with_capacity($size); - - for i in 0..$size { - // shift value by i - let mask = 1 << i as $type_; - let result = value & mask; - - // If last bit is one, push one. - if result == mask { - bits.push(Boolean::constant(true)) - } else { - bits.push(Boolean::constant(false)) - } - } - - Self { - bits, - value: Some(value), - } - } - } - - impl Int for $name { - type IntegerType = $type_; - - const SIZE: usize = $size; - - fn one() -> Self { - Self::constant(1 as $type_) - } - - fn zero() -> Self { - Self::constant(0 as $type_) - } - - fn is_constant(&self) -> bool { - // If any bits of self are allocated bits, return false - self.bits.iter().all(|bit| matches!(bit, Boolean::Constant(_))) - } - } - }; -} - -// int_impl!(Int8, i8, 8); -int_impl!(Int16, i16, 16); -int_impl!(Int32, i32, 32); -int_impl!(Int64, i64, 64); -int_impl!(Int128, i128, 128); diff --git a/gadgets/src/signed_integer/mod.rs b/gadgets/src/signed_integer/mod.rs deleted file mode 100644 index b54aa25db6..0000000000 --- a/gadgets/src/signed_integer/mod.rs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#[macro_use] - -pub mod arithmetic; -pub use self::arithmetic::*; - -pub mod int_impl; -pub use self::int_impl::*; - -pub mod relational; -pub use self::relational::*; - -pub mod utilities; -pub use self::utilities::*; diff --git a/gadgets/src/signed_integer/relational/cmp.rs b/gadgets/src/signed_integer/relational/cmp.rs deleted file mode 100644 index acd456a2a2..0000000000 --- a/gadgets/src/signed_integer/relational/cmp.rs +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Int128, Int16, Int32, Int64}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::utilities::{ - bits::comparator::{ComparatorGadget, EvaluateLtGadget}, - boolean::Boolean, - select::CondSelectGadget, -}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; -use std::cmp::Ordering; - -macro_rules! cmp_gadget_impl { - ($($gadget: ident)*) => ($( - /* Bitwise less than comparison of two signed integers */ - impl EvaluateLtGadget for $gadget { - fn less_than>( - &self, - mut cs: CS, - other: &Self - ) -> Result { - - let mut result = Boolean::constant(true); - let mut all_equal = Boolean::constant(true); - - // msb -> lsb - for (i, (a, b)) in self - .bits - .iter() - .rev() - .zip(other.bits.iter().rev()) - .enumerate() - { - - // check msb signed bit - let less = if i == 0 { - // a == 1 & b == 0 - Boolean::and(cs.ns(|| format!("a and not b [{}]", i)), a, &b.not())? - } else { - // a == 0 & b == 1 - Boolean::and(cs.ns(|| format!("not a and b [{}]", i)), &a.not(), b)? - }; - - // a == b = !(a ^ b) - let not_equal = Boolean::xor(cs.ns(|| format!("a XOR b [{}]", i)), a, b)?; - let equal = not_equal.not(); - - // evaluate a <= b - let less_or_equal = Boolean::or(cs.ns(|| format!("less or equal [{}]", i)), &less, &equal)?; - - // If `all_equal` is `true`, sets `result` to `less_or_equal`. Else, sets `result` to `result`. - result = Boolean::conditionally_select(cs.ns(|| format!("select bit [{}]", i)), &all_equal, &less_or_equal, &result)?; - - // keep track of equal bits - all_equal = Boolean::and(cs.ns(|| format!("accumulate equal [{}]", i)), &all_equal, &equal)?; - } - - result = Boolean::and(cs.ns(|| format!("false if all equal")), &result, &all_equal.not())?; - - Ok(result) - } - } - - /* Bitwise comparison of two unsigned integers */ - impl ComparatorGadget for $gadget {} - - impl PartialOrd for $gadget { - fn partial_cmp(&self, other: &Self) -> Option { - Option::from(self.value.cmp(&other.value)) - } - } - )*) -} - -cmp_gadget_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/relational/eq.rs b/gadgets/src/signed_integer/relational/eq.rs deleted file mode 100644 index c5007a94bf..0000000000 --- a/gadgets/src/signed_integer/relational/eq.rs +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Int, Int128, Int16, Int32, Int64}; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::utilities::{boolean::Boolean, eq::EvaluateEqGadget}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -macro_rules! eq_gadget_impl { - ($($gadget: ident)*) => ($( - impl EvaluateEqGadget for $gadget { - fn evaluate_equal>( - &self, - mut cs: CS, - other: &Self - ) -> Result { - let mut result = Boolean::constant(true); - for (i, (a, b)) in self.bits.iter().zip(&other.bits).enumerate() { - let equal = a.evaluate_equal( - &mut cs.ns(|| format!("{} evaluate equality for {}-th bit", <$gadget as Int>::SIZE, i)), - b, - )?; - - result = Boolean::and( - &mut cs.ns(|| format!("{} and result for {}-th bit", <$gadget as Int>::SIZE, i)), - &equal, - &result, - )?; - } - - Ok(result) - } - } - - impl PartialEq for $gadget { - fn eq(&self, other: &Self) -> bool { - // self.value == other.value means that other.value.is_some() too - self.value.is_some() && self.value == other.value - } - } - - impl Eq for $gadget {} - )*) -} - -eq_gadget_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/relational/mod.rs b/gadgets/src/signed_integer/relational/mod.rs deleted file mode 100644 index aec7552341..0000000000 --- a/gadgets/src/signed_integer/relational/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#[macro_use] -pub mod eq; -pub use self::eq::*; - -pub mod cmp; -pub use self::cmp::*; diff --git a/gadgets/src/signed_integer/utilities/alloc.rs b/gadgets/src/signed_integer/utilities/alloc.rs deleted file mode 100644 index a7cd797fcb..0000000000 --- a/gadgets/src/signed_integer/utilities/alloc.rs +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::{Int, Int128, Int16, Int32, Int64}; - -use core::{borrow::Borrow, iter}; -use snarkvm_fields::Field; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - boolean::{AllocatedBit, Boolean}, -}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -fn create_value, I: IntoIterator>, F: Field, CS: ConstraintSystem>( - cs: &mut CS, - iter: I, -) -> Result, SynthesisError> { - iter.into_iter() - .enumerate() - .map(|(i, v)| { - Ok(Boolean::from(AllocatedBit::alloc( - &mut cs.ns(|| format!("allocated bit_gadget {}", i)), - || v.ok_or(SynthesisError::AssignmentMissing), - )?)) - }) - .collect() -} - -macro_rules! alloc_int_impl { - ($($gadget: ident)*) => ($( - impl AllocGadget<<$gadget as Int>::IntegerType, F> for $gadget { - fn alloc< - Fn: FnOnce() -> Result, - T: Borrow<<$gadget as Int>::IntegerType>, - CS: ConstraintSystem - >( - mut cs: CS, - value_gen: Fn, - ) -> Result { - let value = value_gen().map(|val| *val.borrow()); - - let bits = match value { - Ok(mut val) => { - let mut v = Vec::with_capacity(<$gadget as Int>::SIZE); - for _ in 0..<$gadget as Int>::SIZE { - v.push(Some(val & 1 == 1)); - val >>= 1; - } - create_value(&mut cs, v) - } - Err(_) => { - let i = iter::repeat(None::).take(<$gadget as Int>::SIZE); - create_value(&mut cs, i) - }, - }?; - - Ok(Self { - bits, - value: value.ok(), - }) - } - - fn alloc_input< - Fn: FnOnce() -> Result, - T: Borrow<<$gadget as Int>::IntegerType>, - CS: ConstraintSystem - >( - mut cs: CS, - value_gen: Fn, - ) -> Result { - let value = value_gen().map(|val| *val.borrow()); - - let bits = match value { - Ok(mut val) => { - let mut v = Vec::with_capacity(<$gadget as Int>::SIZE); - for _ in 0..<$gadget as Int>::SIZE { - v.push(Some(val & 1 == 1)); - val >>= 1; - } - create_value(&mut cs, v) - } - Err(_) => { - let i = iter::repeat(None::).take(<$gadget as Int>::SIZE); - create_value(&mut cs, i) - }, - }?; - - Ok(Self { - bits, - value: value.ok(), - }) - } - } - )*) -} - -alloc_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/src/signed_integer/utilities/eq.rs b/gadgets/src/signed_integer/utilities/eq.rs deleted file mode 100644 index e15793b005..0000000000 --- a/gadgets/src/signed_integer/utilities/eq.rs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::signed_integer::*; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::utilities::{boolean::Boolean, eq::ConditionalEqGadget}; -use snarkvm_r1cs::{ConstraintSystem, SynthesisError}; - -macro_rules! cond_eq_int_impl { - ($($gadget: ident),*) => ($( - impl ConditionalEqGadget for $gadget { - fn conditional_enforce_equal>( - &self, - mut cs: CS, - other: &Self, - condition: &Boolean, - ) -> Result<(), SynthesisError> { - for (i, (a, b)) in self.bits.iter().zip(&other.bits).enumerate() { - a.conditional_enforce_equal( - &mut cs.ns(|| format!("{} equality check for the {}-th bit", <$gadget as Int>::SIZE, i)), - b, - condition, - )?; - } - - Ok(()) - } - - fn cost() -> usize { - <$gadget as Int>::SIZE * >::cost() - } - } - )*) -} - -cond_eq_int_impl!(Int16, Int32, Int64, Int128); diff --git a/gadgets/src/signed_integer/utilities/mod.rs b/gadgets/src/signed_integer/utilities/mod.rs deleted file mode 100644 index 3f2c19414d..0000000000 --- a/gadgets/src/signed_integer/utilities/mod.rs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -#[macro_use] -pub mod alloc; -pub use self::alloc::*; - -pub mod eq; -pub use self::eq::*; - -pub mod select; -pub use self::select::*; diff --git a/gadgets/src/signed_integer/utilities/select.rs b/gadgets/src/signed_integer/utilities/select.rs deleted file mode 100644 index d64e47d90c..0000000000 --- a/gadgets/src/signed_integer/utilities/select.rs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use crate::signed_integer::*; - -use snarkvm_fields::PrimeField; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - boolean::Boolean, - eq::EqGadget, - select::CondSelectGadget, -}; -use snarkvm_r1cs::{Assignment, ConstraintSystem, SynthesisError}; - -macro_rules! select_int_impl { - ($($gadget: ident)*) => ($( - impl CondSelectGadget for $gadget { - fn conditionally_select> ( - mut cs: CS, - cond: &Boolean, - first: &Self, - second: &Self, - ) -> Result { - if let Boolean::Constant(cond) = *cond { - if cond { - Ok(first.clone()) - } else { - Ok(second.clone()) - } - } else { - let result_val = cond.get_value().and_then(|c| { - if c { - first.value - } else { - second.value - } - }); - - let result = Self::alloc(cs.ns(|| "cond_select_result"), || result_val.get())?; - - for (i, ((bit1, bit2), actual)) in first.bits.iter().zip(second.bits.iter()).zip(result.bits.iter()).enumerate() { - let expected = Boolean::conditionally_select( - &mut cs.ns(|| format!("{}_cond_select_{}", <$gadget as Int>::SIZE, i)), - cond, - bit1, - bit2, - ).unwrap(); - - actual.enforce_equal(&mut cs.ns(|| format!("selected_result_bit_{}", i)), &expected)?; - } - - Ok(result) - } - } - - fn cost() -> usize { - unimplemented!(); - } - } - )*) -} - -select_int_impl!(Int16 Int32 Int64 Int128); diff --git a/gadgets/tests/mod.rs b/gadgets/tests/mod.rs deleted file mode 100644 index 898f5b4c27..0000000000 --- a/gadgets/tests/mod.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -// pub mod signed_integer; -// pub use self::signed_integer::*; diff --git a/gadgets/tests/signed_integer/i128.rs b/gadgets/tests/signed_integer/i128.rs deleted file mode 100644 index 96c78d4a30..0000000000 --- a/gadgets/tests/signed_integer/i128.rs +++ /dev/null @@ -1,361 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_gadgets::Int128; - -use snarkvm_fields::{One, Zero}; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::{Add, Div, Mul, Sub}, - boolean::Boolean, -}; -use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; - -use rand::Rng; -use rand_core::SeedableRng; -use rand_xorshift::XorShiftRng; -use std::i128; - -fn check_all_constant_bits(expected: i128, actual: Int128) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i128; - let result = expected & mask; - - match *b { - Boolean::Is(_) => panic!(), - Boolean::Not(_) => panic!(), - Boolean::Constant(b) => { - let bit = result == mask; - assert_eq!(b, bit); - } - } - } -} - -fn check_all_allocated_bits(expected: i128, actual: Int128) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i128; - let result = expected & mask; - - match *b { - Boolean::Is(ref b) => { - let bit = result == mask; - assert_eq!(b.get_value().unwrap(), bit); - } - Boolean::Not(ref b) => { - let bit = result == mask; - assert_eq!(!b.get_value().unwrap(), bit); - } - Boolean::Constant(_) => unreachable!(), - } - } -} - -#[test] -fn test_int128_constant_and_alloc() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i128 = rng.gen(); - - let a_const = Int128::constant(a); - - assert!(a_const.value == Some(a)); - - check_all_constant_bits(a, a_const); - - let a_bit = Int128::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - - assert!(cs.is_satisfied()); - assert!(a_bit.value == Some(a)); - - check_all_allocated_bits(a, a_bit); - } -} - -#[test] -fn test_int128_add_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..100 { - let mut cs = TestConstraintSystem::::new(); - - let a: i128 = rng.gen(); - let b: i128 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int128::constant(a); - let b_bit = Int128::constant(b); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int128_add() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..100 { - let mut cs = TestConstraintSystem::::new(); - - let a: i128 = rng.gen(); - let b: i128 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int128::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int128::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the addition constraint still works - if cs.get("addition/result bit_gadget 0/boolean").is_zero() { - cs.set("addition/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("addition/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int128_sub_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..100 { - let mut cs = TestConstraintSystem::::new(); - - let a: i128 = rng.gen(); - let b: i128 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int128::constant(a); - let b_bit = Int128::constant(b); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int128_sub() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..100 { - let mut cs = TestConstraintSystem::::new(); - - let a: i128 = rng.gen(); - let b: i128 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int128::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int128::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the subtraction constraint still works - if cs - .get("subtraction/add_complement/result bit_gadget 0/boolean") - .is_zero() - { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int128_mul_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..3 { - let mut cs = TestConstraintSystem::::new(); - - let max = i64::MAX as i128; - let min = i64::MIN as i128; - - let a: i128 = rng.gen_range(min..max); - let b: i128 = rng.gen_range(min..max); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int128::constant(a); - let b_bit = Int128::constant(b); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int128_mul() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..2 { - let mut cs = TestConstraintSystem::::new(); - - let max = i64::MAX as i128; - let min = i64::MIN as i128; - - let a: i128 = rng.gen_range(min..max); - let b: i128 = rng.gen_range(min..max); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int128::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int128::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the multiplication constraint still works - if cs.get("multiplication/result bit_gadget 0/boolean").is_zero() { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int128_div_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..3 { - let mut cs = TestConstraintSystem::::new(); - - let a: i128 = rng.gen(); - let b: i128 = rng.gen(); - - if a.checked_neg().is_none() { - return; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int128::constant(a); - let b_bit = Int128::constant(b); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int128_div() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..2 { - let mut cs = TestConstraintSystem::::new(); - - let a: i128 = rng.gen(); - let b: i128 = rng.gen(); - - if a.checked_neg().is_none() { - continue; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int128::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int128::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - } -} diff --git a/gadgets/tests/signed_integer/i16.rs b/gadgets/tests/signed_integer/i16.rs deleted file mode 100644 index b50943ce4e..0000000000 --- a/gadgets/tests/signed_integer/i16.rs +++ /dev/null @@ -1,433 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_gadgets::Int16; - -use snarkvm_fields::{One, Zero}; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::{Add, Div, Mul, Pow, Sub}, - boolean::Boolean, -}; -use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; - -use rand::Rng; -use rand_core::SeedableRng; -use rand_xorshift::XorShiftRng; -use std::i16; - -fn check_all_constant_bits(expected: i16, actual: Int16) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i16; - let result = expected & mask; - - match *b { - Boolean::Is(_) => panic!(), - Boolean::Not(_) => panic!(), - Boolean::Constant(b) => { - let bit = result == mask; - assert_eq!(b, bit); - } - } - } -} - -fn check_all_allocated_bits(expected: i16, actual: Int16) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i16; - let result = expected & mask; - - match *b { - Boolean::Is(ref b) => { - let bit = result == mask; - assert_eq!(b.get_value().unwrap(), bit); - } - Boolean::Not(ref b) => { - let bit = result == mask; - assert_eq!(!b.get_value().unwrap(), bit); - } - Boolean::Constant(_) => unreachable!(), - } - } -} - -#[test] -fn test_int16_constant_and_alloc() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen(); - - let a_const = Int16::constant(a); - - assert!(a_const.value == Some(a)); - - check_all_constant_bits(a, a_const); - - let a_bit = Int16::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - - assert!(cs.is_satisfied()); - assert!(a_bit.value == Some(a)); - - check_all_allocated_bits(a, a_bit); - } -} - -#[test] -fn test_int16_add_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen(); - let b: i16 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int16::constant(a); - let b_bit = Int16::constant(b); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int16_add() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen(); - let b: i16 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int16::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int16::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the addition constraint still works - if cs.get("addition/result bit_gadget 0/boolean").is_zero() { - cs.set("addition/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("addition/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int16_sub_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen(); - let b: i16 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int16::constant(a); - let b_bit = Int16::constant(b); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int16_sub() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen(); - let b: i16 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int16::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int16::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the subtraction constraint still works - if cs - .get("subtraction/add_complement/result bit_gadget 0/boolean") - .is_zero() - { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int16_mul_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..100 { - let mut cs = TestConstraintSystem::::new(); - - let max = i8::MAX as i16; - let min = i8::MIN as i16; - - let a: i16 = rng.gen_range(min..max); - let b: i16 = rng.gen_range(min..max); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int16::constant(a); - let b_bit = Int16::constant(b); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int16_mul() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..50 { - let mut cs = TestConstraintSystem::::new(); - - let max = i8::MAX as i16; - let min = i8::MIN as i16; - - let a: i16 = rng.gen_range(min..max); - let b: i16 = rng.gen_range(min..max); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int16::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int16::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the multiplication constraint still works - if cs.get("multiplication/result bit_gadget 0/boolean").is_zero() { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int16_div_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..100 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen(); - let b: i16 = rng.gen(); - - if a.checked_neg().is_none() { - return; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int16::constant(a); - let b_bit = Int16::constant(b); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int16_div() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..10 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen(); - let b: i16 = rng.gen(); - - if a.checked_neg().is_none() { - continue; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int16::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int16::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - } -} - -#[test] -fn test_int16_pow_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..10 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen_range(-16..16); - let b: i16 = rng.gen_range(-4..4); - - let expected = match a.checked_pow(b as u32) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int16::constant(a); - let b_bit = Int16::constant(b); - - let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int16_pow() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..3 { - let mut cs = TestConstraintSystem::::new(); - - let a: i16 = rng.gen_range(-16..16); - let b: i16 = rng.gen_range(-4..4); - - let expected = match a.checked_pow(b as u32) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int16::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int16::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the exponentiation constraint still works - if cs - .get("exponentiation/multiply_by_self_0/result bit_gadget 0/boolean") - .is_zero() - { - cs.set( - "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", - Fr::one(), - ); - } else { - cs.set( - "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", - Fr::zero(), - ); - } - - assert!(!cs.is_satisfied()); - } -} diff --git a/gadgets/tests/signed_integer/i32.rs b/gadgets/tests/signed_integer/i32.rs deleted file mode 100644 index e6821b9f24..0000000000 --- a/gadgets/tests/signed_integer/i32.rs +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_gadgets::Int32; - -use snarkvm_fields::{One, Zero}; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::{Add, Div, Mul, Pow, Sub}, - boolean::Boolean, -}; -use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; - -use rand::Rng; -use rand_core::SeedableRng; -use rand_xorshift::XorShiftRng; -use std::i32; - -fn check_all_constant_bits(expected: i32, actual: Int32) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i32; - let result = expected & mask; - - match *b { - Boolean::Is(_) => panic!(), - Boolean::Not(_) => panic!(), - Boolean::Constant(b) => { - let bit = result == mask; - assert_eq!(b, bit); - } - } - } -} - -fn check_all_allocated_bits(expected: i32, actual: Int32) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i32; - let result = expected & mask; - - match *b { - Boolean::Is(ref b) => { - let bit = result == mask; - assert_eq!(b.get_value().unwrap(), bit); - } - Boolean::Not(ref b) => { - let bit = result == mask; - assert_eq!(!b.get_value().unwrap(), bit); - } - Boolean::Constant(_) => unreachable!(), - } - } -} - -#[test] -fn test_int32_constant_and_alloc() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen(); - - let a_const = Int32::constant(a); - - assert!(a_const.value == Some(a)); - - check_all_constant_bits(a, a_const); - - let a_bit = Int32::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - - assert!(cs.is_satisfied()); - assert!(a_bit.value == Some(a)); - - check_all_allocated_bits(a, a_bit); - } -} - -#[test] -fn test_int32_add_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen(); - let b: i32 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int32::constant(a); - let b_bit = Int32::constant(b); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int32_add() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen(); - let b: i32 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int32::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int32::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the addition constraint still works - if cs.get("addition/result bit_gadget 0/boolean").is_zero() { - cs.set("addition/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("addition/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int32_sub_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen(); - let b: i32 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int32::constant(a); - let b_bit = Int32::constant(b); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int32_sub() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen(); - let b: i32 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int32::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int32::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the subtraction constraint still works - if cs - .get("subtraction/add_complement/result bit_gadget 0/boolean") - .is_zero() - { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int32_mul_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..10 { - let mut cs = TestConstraintSystem::::new(); - - let max = i16::MAX as i32; - let min = i16::MIN as i32; - - let a: i32 = rng.gen_range(min..max); - let b: i32 = rng.gen_range(min..max); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int32::constant(a); - let b_bit = Int32::constant(b); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int32_mul() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..10 { - let mut cs = TestConstraintSystem::::new(); - - let max = i16::MAX as i32; - let min = i16::MIN as i32; - - let a: i32 = rng.gen_range(min..max); - let b: i32 = rng.gen_range(min..max); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int32::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int32::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the multiplication constraint still works - if cs.get("multiplication/result bit_gadget 0/boolean").is_zero() { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int32_div_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..10 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen(); - let b: i32 = rng.gen(); - - if a.checked_neg().is_none() { - return; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int32::constant(a); - let b_bit = Int32::constant(b); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int32_div() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..10 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen(); - let b: i32 = rng.gen(); - - if a.checked_neg().is_none() { - continue; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int32::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int32::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - } -} - -#[ignore] -#[test] -fn test_int32_pow_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..3 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen_range(-16..16); - let b: i32 = rng.gen_range(-8..8); - - let expected = match a.checked_pow(b as u32) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int32::constant(a); - let b_bit = Int32::constant(b); - - let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[ignore] -#[test] -fn test_int32_pow() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..3 { - let mut cs = TestConstraintSystem::::new(); - - let a: i32 = rng.gen_range(-16..16); - let b: i32 = rng.gen_range(-8..8); - - let expected = match a.checked_pow(b as u32) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int32::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int32::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the exponentiation constraint still works - if cs - .get("exponentiation/multiply_by_self_0/result bit_gadget 0/boolean") - .is_zero() - { - cs.set( - "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", - Fr::one(), - ); - } else { - cs.set( - "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", - Fr::zero(), - ); - } - - assert!(!cs.is_satisfied()); - } -} diff --git a/gadgets/tests/signed_integer/i64.rs b/gadgets/tests/signed_integer/i64.rs deleted file mode 100644 index 5488b0b92c..0000000000 --- a/gadgets/tests/signed_integer/i64.rs +++ /dev/null @@ -1,425 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -use leo_gadgets::Int64; - -use snarkvm_fields::{One, Zero}; -use snarkvm_gadgets::traits::utilities::{ - alloc::AllocGadget, - arithmetic::{Add, Div, Mul, Pow, Sub}, - boolean::Boolean, -}; -use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; - -use rand::Rng; -use rand_core::SeedableRng; -use rand_xorshift::XorShiftRng; -use std::i64; - -fn check_all_constant_bits(expected: i64, actual: Int64) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i64; - let result = expected & mask; - - match *b { - Boolean::Is(_) => panic!(), - Boolean::Not(_) => panic!(), - Boolean::Constant(b) => { - let bit = result == mask; - assert_eq!(b, bit); - } - } - } -} - -fn check_all_allocated_bits(expected: i64, actual: Int64) { - for (i, b) in actual.bits.iter().enumerate() { - // shift value by i - let mask = 1 << i as i64; - let result = expected & mask; - - match *b { - Boolean::Is(ref b) => { - let bit = result == mask; - assert_eq!(b.get_value().unwrap(), bit); - } - Boolean::Not(ref b) => { - let bit = result == mask; - assert_eq!(!b.get_value().unwrap(), bit); - } - Boolean::Constant(_) => unreachable!(), - } - } -} - -#[test] -fn test_int64_constant_and_alloc() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen(); - - let a_const = Int64::constant(a); - - assert!(a_const.value == Some(a)); - - check_all_constant_bits(a, a_const); - - let a_bit = Int64::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - - assert!(cs.is_satisfied()); - assert!(a_bit.value == Some(a)); - - check_all_allocated_bits(a, a_bit); - } -} - -#[test] -fn test_int64_add_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen(); - let b: i64 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int64::constant(a); - let b_bit = Int64::constant(b); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int64_add() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen(); - let b: i64 = rng.gen(); - - let expected = match a.checked_add(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int64::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int64::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the addition constraint still works - if cs.get("addition/result bit_gadget 0/boolean").is_zero() { - cs.set("addition/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("addition/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int64_sub_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen(); - let b: i64 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int64::constant(a); - let b_bit = Int64::constant(b); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int64_sub() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..1000 { - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen(); - let b: i64 = rng.gen(); - - if b.checked_neg().is_none() { - // negate with overflows will fail: -128 - continue; - } - let expected = match a.checked_sub(b) { - // subtract with overflow will fail: -0 - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int64::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int64::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the subtraction constraint still works - if cs - .get("subtraction/add_complement/result bit_gadget 0/boolean") - .is_zero() - { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int64_mul_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..5 { - let mut cs = TestConstraintSystem::::new(); - - let max = i32::MAX as i64; - let min = i32::MIN as i64; - - let a: i64 = rng.gen_range(min..max); - let b: i64 = rng.gen_range(min..max); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int64::constant(a); - let b_bit = Int64::constant(b); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int64_mul() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..5 { - let mut cs = TestConstraintSystem::::new(); - - let max = i32::MAX as i64; - let min = i32::MIN as i64; - - let a: i64 = rng.gen_range(min..max); - let b: i64 = rng.gen_range(min..max); - - let expected = match a.checked_mul(b) { - Some(valid) => valid, - None => continue, - }; - - let a_bit = Int64::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int64::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the multiplication constraint still works - if cs.get("multiplication/result bit_gadget 0/boolean").is_zero() { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::one()); - } else { - cs.set("multiplication/result bit_gadget 0/boolean", Fr::zero()); - } - - assert!(!cs.is_satisfied()); - } -} - -#[test] -fn test_int64_div_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..3 { - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen(); - let b: i64 = rng.gen(); - - if a.checked_neg().is_none() { - return; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int64::constant(a); - let b_bit = Int64::constant(b); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); - } -} - -#[test] -fn test_int64_div() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - for _ in 0..3 { - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen(); - let b: i64 = rng.gen(); - - if a.checked_neg().is_none() { - continue; - } - - let expected = match a.checked_div(b) { - Some(valid) => valid, - None => return, - }; - - let a_bit = Int64::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int64::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - } -} - -#[ignore] -#[test] -fn test_int64_pow_constants() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen_range(-16..16); - let b: i64 = rng.gen_range(-12..12); - - let expected = a.checked_pow(b as u32).unwrap(); - - let a_bit = Int64::constant(a); - let b_bit = Int64::constant(b); - - let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); - - assert!(r.value == Some(expected)); - - check_all_constant_bits(expected, r); -} - -#[ignore] -#[test] -fn test_int64_pow() { - let mut rng = XorShiftRng::seed_from_u64(1231275789u64); - - let mut cs = TestConstraintSystem::::new(); - - let a: i64 = rng.gen_range(-16..16); - let b: i64 = rng.gen_range(-12..12); - - let expected = a.checked_pow(b as u32).unwrap(); - - let a_bit = Int64::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); - let b_bit = Int64::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); - - let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); - - assert!(cs.is_satisfied()); - - assert!(r.value == Some(expected)); - - check_all_allocated_bits(expected, r); - - // Flip a bit_gadget and see if the exponentiation constraint still works - if cs - .get("exponentiation/multiply_by_self_0/result bit_gadget 0/boolean") - .is_zero() - { - cs.set( - "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", - Fr::one(), - ); - } else { - cs.set( - "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", - Fr::zero(), - ); - } - - assert!(!cs.is_satisfied()); -} diff --git a/gadgets/tests/signed_integer/i8.rs b/gadgets/tests/signed_integer/i8.rs deleted file mode 100644 index 65b27e966c..0000000000 --- a/gadgets/tests/signed_integer/i8.rs +++ /dev/null @@ -1,427 +0,0 @@ -// // Copyright (C) 2019-2021 Aleo Systems Inc. -// // This file is part of the Leo library. -// -// // The Leo library is free software: you can redistribute it and/or modify -// // it under the terms of the GNU General Public License as published by -// // the Free Software Foundation, either version 3 of the License, or -// // (at your option) any later version. -// -// // The Leo library is distributed in the hope that it will be useful, -// // but WITHOUT ANY WARRANTY; without even the implied warranty of -// // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// // GNU General Public License for more details. -// -// // You should have received a copy of the GNU General Public License -// // along with the Leo library. If not, see . -// -// use leo_gadgets::Int8; -// -// use snarkvm_fields::{One, Zero}; -// use snarkvm_gadgets::traits::utilities::{ -// alloc::AllocGadget, -// arithmetic::{Add, Div, Mul, Pow, Sub}, -// boolean::Boolean, -// }; -// use snarkvm_r1cs::{ConstraintSystem, Fr, TestConstraintSystem}; -// -// use rand::Rng; -// use rand_core::SeedableRng; -// use rand_xorshift::XorShiftRng; -// use std::i8; -// -// fn check_all_constant_bits(expected: i8, actual: Int8) { -// for (i, b) in actual.bits.iter().enumerate() { -// // shift value by i -// let mask = 1 << i as i8; -// let result = expected & mask; -// -// match *b { -// Boolean::Is(_) => panic!(), -// Boolean::Not(_) => panic!(), -// Boolean::Constant(b) => { -// let bit = result == mask; -// assert_eq!(b, bit); -// } -// } -// } -// } -// -// fn check_all_allocated_bits(expected: i8, actual: Int8) { -// for (i, b) in actual.bits.iter().enumerate() { -// // shift value by i -// let mask = 1 << i as i8; -// let result = expected & mask; -// -// match *b { -// Boolean::Is(ref b) => { -// let bit = result == mask; -// assert_eq!(b.get_value().unwrap(), bit); -// } -// Boolean::Not(ref b) => { -// let bit = result == mask; -// assert_eq!(!b.get_value().unwrap(), bit); -// } -// Boolean::Constant(_) => unreachable!(), -// } -// } -// } -// -// #[test] -// fn test_int8_constant_and_alloc() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..1000 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// -// let a_const = Int8::constant(a); -// -// assert!(a_const.value == Some(a)); -// -// check_all_constant_bits(a, a_const); -// -// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); -// -// assert!(cs.is_satisfied()); -// assert!(a_bit.value == Some(a)); -// -// check_all_allocated_bits(a, a_bit); -// } -// } -// -// #[test] -// fn test_int8_add_constants() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..1000 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// let b: i8 = rng.gen(); -// -// let expected = match a.checked_add(b) { -// Some(valid) => valid, -// None => continue, -// }; -// -// let a_bit = Int8::constant(a); -// let b_bit = Int8::constant(b); -// -// let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); -// -// assert!(r.value == Some(expected)); -// -// check_all_constant_bits(expected, r); -// } -// } -// -// #[test] -// fn test_int8_add() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..1000 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// let b: i8 = rng.gen(); -// -// let expected = match a.checked_add(b) { -// Some(valid) => valid, -// None => continue, -// }; -// -// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); -// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); -// -// let r = a_bit.add(cs.ns(|| "addition"), &b_bit).unwrap(); -// -// assert!(cs.is_satisfied()); -// -// assert!(r.value == Some(expected)); -// -// check_all_allocated_bits(expected, r); -// -// // Flip a bit_gadget and see if the addition constraint still works -// if cs.get("addition/result bit_gadget 0/boolean").is_zero() { -// cs.set("addition/result bit_gadget 0/boolean", Fr::one()); -// } else { -// cs.set("addition/result bit_gadget 0/boolean", Fr::zero()); -// } -// -// assert!(!cs.is_satisfied()); -// } -// } -// -// #[test] -// fn test_int8_sub_constants() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..1000 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// let b: i8 = rng.gen(); -// -// if b.checked_neg().is_none() { -// // negate with overflows will fail: -128 -// continue; -// } -// let expected = match a.checked_sub(b) { -// // subtract with overflow will fail: -0 -// Some(valid) => valid, -// None => continue, -// }; -// -// let a_bit = Int8::constant(a); -// let b_bit = Int8::constant(b); -// -// let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); -// -// assert!(r.value == Some(expected)); -// -// check_all_constant_bits(expected, r); -// } -// } -// -// #[test] -// fn test_int8_sub() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..1000 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// let b: i8 = rng.gen(); -// -// if b.checked_neg().is_none() { -// // negate with overflows will fail: -128 -// continue; -// } -// let expected = match a.checked_sub(b) { -// // subtract with overflow will fail: -0 -// Some(valid) => valid, -// None => continue, -// }; -// -// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); -// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); -// -// let r = a_bit.sub(cs.ns(|| "subtraction"), &b_bit).unwrap(); -// -// assert!(cs.is_satisfied()); -// -// assert!(r.value == Some(expected)); -// -// check_all_allocated_bits(expected, r); -// -// // Flip a bit_gadget and see if the subtraction constraint still works -// if cs -// .get("subtraction/add_complement/result bit_gadget 0/boolean") -// .is_zero() -// { -// cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::one()); -// } else { -// cs.set("subtraction/add_complement/result bit_gadget 0/boolean", Fr::zero()); -// } -// -// assert!(!cs.is_satisfied()); -// } -// } -// -// #[test] -// fn test_int8_mul_constants() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..1000 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// let b: i8 = rng.gen(); -// -// let expected = match a.checked_mul(b) { -// Some(valid) => valid, -// None => continue, -// }; -// -// let a_bit = Int8::constant(a); -// let b_bit = Int8::constant(b); -// -// let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); -// -// assert!(r.value == Some(expected)); -// -// check_all_constant_bits(expected, r); -// } -// } -// -// #[test] -// fn test_int8_mul() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..1000 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// let b: i8 = rng.gen(); -// -// let expected = match a.checked_mul(b) { -// Some(valid) => valid, -// None => continue, -// }; -// -// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); -// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); -// -// let r = a_bit.mul(cs.ns(|| "multiplication"), &b_bit).unwrap(); -// -// assert!(cs.is_satisfied()); -// -// assert!(r.value == Some(expected)); -// -// check_all_allocated_bits(expected, r); -// -// // Flip a bit_gadget and see if the multiplication constraint still works -// if cs.get("multiplication/result bit_gadget 0/boolean").is_zero() { -// cs.set("multiplication/result bit_gadget 0/boolean", Fr::one()); -// } else { -// cs.set("multiplication/result bit_gadget 0/boolean", Fr::zero()); -// } -// -// assert!(!cs.is_satisfied()); -// } -// } -// -// #[test] -// fn test_int8_div_constants() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..1000 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// let b: i8 = rng.gen(); -// -// if a.checked_neg().is_none() { -// return; -// } -// -// let expected = match a.checked_div(b) { -// Some(valid) => valid, -// None => return, -// }; -// -// let a_bit = Int8::constant(a); -// let b_bit = Int8::constant(b); -// -// let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); -// -// assert!(r.value == Some(expected)); -// -// check_all_constant_bits(expected, r); -// } -// } -// -// #[test] -// fn test_int8_div() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..100 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen(); -// let b: i8 = rng.gen(); -// -// if a.checked_neg().is_none() { -// continue; -// } -// -// let expected = match a.checked_div(b) { -// Some(valid) => valid, -// None => return, -// }; -// -// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); -// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); -// -// let r = a_bit.div(cs.ns(|| "division"), &b_bit).unwrap(); -// -// assert!(cs.is_satisfied()); -// -// assert!(r.value == Some(expected)); -// -// check_all_allocated_bits(expected, r); -// } -// } -// -// #[test] -// fn test_int8_pow_constants() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..100 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen_range(-4..4); -// let b: i8 = rng.gen_range(-4..4); -// -// let expected = match a.checked_pow(b as u32) { -// Some(valid) => valid, -// None => continue, -// }; -// -// let a_bit = Int8::constant(a); -// let b_bit = Int8::constant(b); -// -// let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); -// -// assert!(r.value == Some(expected)); -// -// check_all_constant_bits(expected, r); -// } -// } -// -// #[test] -// fn test_int8_pow() { -// let mut rng = XorShiftRng::seed_from_u64(1231275789u64); -// -// for _ in 0..10 { -// let mut cs = TestConstraintSystem::::new(); -// -// let a: i8 = rng.gen_range(-4..4); -// let b: i8 = rng.gen_range(-4..4); -// -// let expected = match a.checked_pow(b as u32) { -// Some(valid) => valid, -// None => continue, -// }; -// -// let a_bit = Int8::alloc(cs.ns(|| "a_bit"), || Ok(a)).unwrap(); -// let b_bit = Int8::alloc(cs.ns(|| "b_bit"), || Ok(b)).unwrap(); -// -// let r = a_bit.pow(cs.ns(|| "exponentiation"), &b_bit).unwrap(); -// -// assert!(cs.is_satisfied()); -// -// assert!(r.value == Some(expected)); -// -// check_all_allocated_bits(expected, r); -// -// // Flip a bit_gadget and see if the exponentiation constraint still works -// if cs -// .get("exponentiation/multiply_by_self_0/result bit_gadget 0/boolean") -// .is_zero() -// { -// cs.set( -// "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", -// Fr::one(), -// ); -// } else { -// cs.set( -// "exponentiation/multiply_by_self_0/result bit_gadget 0/boolean", -// Fr::zero(), -// ); -// } -// -// assert!(!cs.is_satisfied()); -// } -// } diff --git a/gadgets/tests/signed_integer/mod.rs b/gadgets/tests/signed_integer/mod.rs deleted file mode 100644 index 73b3adce90..0000000000 --- a/gadgets/tests/signed_integer/mod.rs +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (C) 2019-2021 Aleo Systems Inc. -// This file is part of the Leo library. - -// The Leo library is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// The Leo library is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with the Leo library. If not, see . - -// Todo: move these tests to snarkvm. -// pub mod i128; -// pub mod i16; -// pub mod i32; -// pub mod i64; -// pub mod i8; From cf315f4ed6d776c7a27b728dddd6224dbebaca46 Mon Sep 17 00:00:00 2001 From: howardwu Date: Mon, 15 Mar 2021 20:34:37 -0700 Subject: [PATCH 04/10] Switch test infrastructure to CircleCI --- .circleci/config.yml | 70 ++++++++++++-- .github/workflows/ci.yml | 194 +++++++++++++++++++-------------------- .resources/kcov.sh | 10 ++ 3 files changed, 169 insertions(+), 105 deletions(-) create mode 100644 .resources/kcov.sh diff --git a/.circleci/config.yml b/.circleci/config.yml index 5bbb00055f..1130310ac4 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -43,6 +43,55 @@ commands: jobs: rust-stable: + docker: + - image: cimg/rust:1.50.0 + resource_class: xlarge + steps: + - checkout + - setup_environment: + cache_key: leo-stable-cache + - run: + name: Build and run tests + no_output_timeout: 30m + command: cargo test --all + - persist_to_workspace: + root: ~/ + paths: project/ + - clear_environment: + cache_key: leo-stable-cache + + rust-nightly: + docker: + - image: howardwu/snarkos-ci:2021-01-31 + resource_class: xlarge + steps: + - checkout + - setup_environment: + cache_key: leo-nightly-cache + - run: + name: Build and test + no_output_timeout: 30m + command: cargo test --all + - clear_environment: + cache_key: leo-nightly-cache + + codecov: + machine: + image: ubuntu-1604:202004-01 + docker_layer_caching: true + resource_class: xlarge + steps: + - attach_workspace: + at: /home/circleci/project/ + - run: + name: Run kcov + command: > + cd ~/project/project/ && + docker run --security-opt seccomp=unconfined -v ~/project/project/:/home/circleci/project/ + howardwu/snarkos-codecov:2021-01-31 bash /home/circleci/project/.resources/kcov.sh + - run: cd ./project/ && bash <(curl -s https://codecov.io/bash) + + leo-stable: docker: - image: cimg/rust:1.50.0 resource_class: xlarge @@ -169,27 +218,32 @@ workflows: main-workflow: jobs: - rust-stable + - rust-nightly + - codecov: + requires: + - rust-stable + - leo-stable - leo-new: requires: - - rust-stable + - leo-stable - leo-init: requires: - - rust-stable + - leo-stable - leo-clean: requires: - - rust-stable + - leo-stable - leo-setup: requires: - - rust-stable + - leo-stable - leo-add-remove: requires: - - rust-stable + - leo-stable - leo-login-logout: requires: - - rust-stable + - leo-stable - leo-clone: requires: - - rust-stable + - leo-stable - leo-publish: requires: - - rust-stable + - leo-stable diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 557e1dc9aa..c83053a790 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,62 +71,62 @@ jobs: command: clippy args: --all-features --examples --all --benches - test: - name: Test - runs-on: ubuntu-latest -# env: -# RUSTFLAGS: -Dwarnings - strategy: - matrix: - rust: - - stable - - nightly - steps: - - name: Checkout - uses: actions/checkout@v2 - - - name: Install Rust (${{ matrix.rust }}) - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: ${{ matrix.rust }} - override: true - - - uses: actions/cache@v2 - with: - path: | - ~/.cargo/registry - ~/.cargo/git - target - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} - -# - name: Check examples -# uses: actions-rs/cargo@v1 -# env: -# CARGO_NET_GIT_FETCH_WITH_CLI: true -# with: -# command: check -# args: --examples --all +# test: +# name: Test +# runs-on: ubuntu-latest +## env: +## RUSTFLAGS: -Dwarnings +# strategy: +# matrix: +# rust: +# - stable +# - nightly +# steps: +# - name: Checkout +# uses: actions/checkout@v2 # -# - name: Check examples with all features on stable -# uses: actions-rs/cargo@v1 +# - name: Install Rust (${{ matrix.rust }}) +# uses: actions-rs/toolchain@v1 # with: -# command: check -# args: --examples --all-features --all -# if: matrix.rust == 'stable' +# profile: minimal +# toolchain: ${{ matrix.rust }} +# override: true # -# - name: Check benchmarks on nightly +# - uses: actions/cache@v2 +# with: +# path: | +# ~/.cargo/registry +# ~/.cargo/git +# target +# key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} +# +## - name: Check examples +## uses: actions-rs/cargo@v1 +## env: +## CARGO_NET_GIT_FETCH_WITH_CLI: true +## with: +## command: check +## args: --examples --all +## +## - name: Check examples with all features on stable +## uses: actions-rs/cargo@v1 +## with: +## command: check +## args: --examples --all-features --all +## if: matrix.rust == 'stable' +## +## - name: Check benchmarks on nightly +## uses: actions-rs/cargo@v1 +## with: +## command: check +## args: --all-features --examples --all --benches +## if: matrix.rust == 'nightly' +# +# - name: Test # uses: actions-rs/cargo@v1 # with: -# command: check -# args: --all-features --examples --all --benches -# if: matrix.rust == 'nightly' - - - name: Test - uses: actions-rs/cargo@v1 - with: - command: test - args: --all --features ci_skip --no-fail-fast +# command: test +# args: --all --features ci_skip --no-fail-fast test-package: name: Test Package @@ -156,49 +156,49 @@ jobs: cd package cargo test-all-features - codecov: - name: Code Coverage - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v1 - - - name: Install Rust - uses: actions-rs/toolchain@v1 - with: - profile: minimal - toolchain: nightly - override: true - components: rustfmt - - - name: Test - uses: actions-rs/cargo@v1 - with: - command: test - args: --all --features ci_skip - env: - CARGO_NET_GIT_FETCH_WITH_CLI: true - CARGO_INCREMENTAL: "0" - - - name: Install dependencies for code coverage - run: | - sudo apt-get update - sudo apt-get -y install binutils-dev libcurl4-openssl-dev zlib1g-dev libdw-dev libiberty-dev - - - name: Generate coverage report - run: | - wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz - tar xzf master.tar.gz - cd kcov-master - mkdir build && cd build - cmake .. && make - make install DESTDIR=../../kcov-build - cd ../.. - rm -rf kcov-master - for file in target/debug/deps/*-*; do if [[ "$file" != *\.* ]]; then mkdir -p "target/cov/$(basename $file)"; ./kcov-build/usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --exclude-region='@kcov_skip(start):@kcov_skip(end)' --verify "target/cov/$(basename $file)" "$file"; fi done - - - name: Upload coverage to Codecov - uses: codecov/codecov-action@v1 - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - token: ${{ secrets.CODECOV_TOKEN }} +# codecov: +# name: Code Coverage +# runs-on: ubuntu-latest +# steps: +# - name: Checkout +# uses: actions/checkout@v1 +# +# - name: Install Rust +# uses: actions-rs/toolchain@v1 +# with: +# profile: minimal +# toolchain: nightly +# override: true +# components: rustfmt +# +# - name: Test +# uses: actions-rs/cargo@v1 +# with: +# command: test +# args: --all --features ci_skip +# env: +# CARGO_NET_GIT_FETCH_WITH_CLI: true +# CARGO_INCREMENTAL: "0" +# +# - name: Install dependencies for code coverage +# run: | +# sudo apt-get update +# sudo apt-get -y install binutils-dev libcurl4-openssl-dev zlib1g-dev libdw-dev libiberty-dev +# +# - name: Generate coverage report +# run: | +# wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz +# tar xzf master.tar.gz +# cd kcov-master +# mkdir build && cd build +# cmake .. && make +# make install DESTDIR=../../kcov-build +# cd ../.. +# rm -rf kcov-master +# for file in target/debug/deps/*-*; do if [[ "$file" != *\.* ]]; then mkdir -p "target/cov/$(basename $file)"; ./kcov-build/usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --exclude-region='@kcov_skip(start):@kcov_skip(end)' --verify "target/cov/$(basename $file)" "$file"; fi done +# +# - name: Upload coverage to Codecov +# uses: codecov/codecov-action@v1 +# with: +# github-token: ${{ secrets.GITHUB_TOKEN }} +# token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.resources/kcov.sh b/.resources/kcov.sh new file mode 100644 index 0000000000..ec16df95c7 --- /dev/null +++ b/.resources/kcov.sh @@ -0,0 +1,10 @@ +cd /home/circleci/project/ && +echo "---START_LIST---" +ls target/debug/deps +echo "---END_LIST---" +for file in target/debug/deps/leo*-*[^\.d]; + do + mkdir -p "target/cov/$(basename $file)"; + echo "Processing target/cov/$(basename $file)" + /usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; + done From f9ccffdccb157f942d905ff7cc7b5d8d1602246a Mon Sep 17 00:00:00 2001 From: howardwu Date: Mon, 15 Mar 2021 20:41:04 -0700 Subject: [PATCH 05/10] Fix description in circleci --- .circleci/config.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 1130310ac4..1cc4dd1316 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -100,7 +100,7 @@ jobs: - setup_environment: cache_key: leo-stable-cache - run: - name: Build and run tests + name: Build and install Leo no_output_timeout: 30m command: cargo install --path . --root . - persist_to_workspace: From 05fa6402a4ecf6965610f14a909cf1ae98c1f346 Mon Sep 17 00:00:00 2001 From: howardwu Date: Mon, 15 Mar 2021 20:44:37 -0700 Subject: [PATCH 06/10] Update leo executable cache --- .circleci/config.yml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 1cc4dd1316..17de4770bd 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -91,14 +91,14 @@ jobs: howardwu/snarkos-codecov:2021-01-31 bash /home/circleci/project/.resources/kcov.sh - run: cd ./project/ && bash <(curl -s https://codecov.io/bash) - leo-stable: + leo-executable: docker: - image: cimg/rust:1.50.0 resource_class: xlarge steps: - checkout - setup_environment: - cache_key: leo-stable-cache + cache_key: leo-executable-cache - run: name: Build and install Leo no_output_timeout: 30m @@ -107,7 +107,7 @@ jobs: root: ~/ paths: project/ - clear_environment: - cache_key: leo-stable-cache + cache_key: leo-executable-cache leo-new: docker: @@ -222,28 +222,28 @@ workflows: - codecov: requires: - rust-stable - - leo-stable + - leo-executable - leo-new: requires: - - leo-stable + - leo-executable - leo-init: requires: - - leo-stable + - leo-executable - leo-clean: requires: - - leo-stable + - leo-executable - leo-setup: requires: - - leo-stable + - leo-executable - leo-add-remove: requires: - - leo-stable + - leo-executable - leo-login-logout: requires: - - leo-stable + - leo-executable - leo-clone: requires: - - leo-stable + - leo-executable - leo-publish: requires: - - leo-stable + - leo-executable From 284bee6fe815945e5ce09db01c4628236a75752a Mon Sep 17 00:00:00 2001 From: howardwu Date: Mon, 15 Mar 2021 21:02:03 -0700 Subject: [PATCH 07/10] Update to ToBitsBEGadget, update to snarkVM v0.2.1 --- Cargo.lock | 149 +++++++++--------- Cargo.toml | 10 +- compiler/Cargo.toml | 14 +- compiler/src/value/address/address.rs | 2 +- compiler/src/value/field/field_type.rs | 12 +- compiler/src/value/group/group_type.rs | 4 +- .../src/value/group/targets/edwards_bls12.rs | 12 +- gadgets/Cargo.toml | 8 +- state/Cargo.toml | 10 +- synthesizer/Cargo.toml | 8 +- 10 files changed, 115 insertions(+), 114 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a21706842a..171bdcfbd4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -365,9 +365,9 @@ dependencies = [ [[package]] name = "console" -version = "0.14.0" +version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc80946b3480f421c2f17ed1cb841753a371c7c5104f51d507e13f532c856aa" +checksum = "3993e6445baa160675931ec041a5e03ca84b9c6e32a056150d3aa2bdda0a1f45" dependencies = [ "encode_unicode", "lazy_static", @@ -508,9 +508,9 @@ dependencies = [ [[package]] name = "csv" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9d58633299b24b515ac72a3f869f8b91306a3cec616a602843a383acd6f9e97" +checksum = "22813a6dc45b335f9bade10bf7271dc477e81113e89eb251a0bc2a8a81c536e1" dependencies = [ "bstr", "csv-core", @@ -530,9 +530,9 @@ dependencies = [ [[package]] name = "curl" -version = "0.4.34" +version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e268162af1a5fe89917ae25ba3b0a77c8da752bdc58e7dbb4f15b91fbd33756e" +checksum = "5a872858e9cb9e3b96c80dd78774ad9e32e44d3b05dc31e142b858d14aebc82c" dependencies = [ "curl-sys", "libc", @@ -545,9 +545,9 @@ dependencies = [ [[package]] name = "curl-sys" -version = "0.4.40+curl-7.75.0" +version = "0.4.41+curl-7.75.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ffafc1c35958318bd7fdd0582995ce4c72f4f461a8e70499ccee83a619fd562" +checksum = "0ec466abd277c7cab2905948f3e94d10bc4963f1f5d47921c1cc4ffd2028fe65" dependencies = [ "cc", "libc", @@ -566,7 +566,7 @@ checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", ] [[package]] @@ -669,7 +669,7 @@ checksum = "aa4da3c766cd7a0db8242e326e9e4e081edd567072893ed320008189715366a4" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", "synstructure", ] @@ -1401,9 +1401,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.87" +version = "0.2.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "265d751d31d6780a3f956bb5b8022feba2d94eeee5a84ba64f4212eedca42213" +checksum = "538c092e5586f4cdd7dd8078c4a79220e3e168880218124dcbce860f0ea938c6" [[package]] name = "libloading" @@ -1549,9 +1549,9 @@ dependencies = [ [[package]] name = "mio" -version = "0.7.9" +version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a5dede4e2065b3842b8b0af444119f3aa331cc7cc2dd20388bfb0f5d5a38823a" +checksum = "2182a122f3b7f3f5329cb1972cee089ba2459a0a80a56935e6e674f096f8d839" dependencies = [ "libc", "log", @@ -1744,15 +1744,15 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" [[package]] name = "openssl" -version = "0.10.32" +version = "0.10.33" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "038d43985d1ddca7a9900630d8cd031b56e4794eecc2e9ea39dd17aa04399a70" +checksum = "a61075b62a23fef5a29815de7536d940aa35ce96d18ce0cc5076272db678a577" dependencies = [ "bitflags", "cfg-if 1.0.0", "foreign-types", - "lazy_static", "libc", + "once_cell", "openssl-sys", ] @@ -1764,9 +1764,9 @@ checksum = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" [[package]] name = "openssl-sys" -version = "0.9.60" +version = "0.9.61" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "921fc71883267538946025deffb622905ecad223c28efbfdef9bb59a0175f3e6" +checksum = "313752393519e876837e09e1fa183ddef0be7735868dced3196f4472d536277f" dependencies = [ "autocfg", "cc", @@ -1854,7 +1854,7 @@ dependencies = [ "pest_meta", "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", ] [[package]] @@ -1885,7 +1885,7 @@ checksum = "758669ae3558c6f74bd2a18b41f7ac0b5a195aea6639d6a9b5e5d1ad5ba24c0b" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", ] [[package]] @@ -1958,7 +1958,7 @@ dependencies = [ "proc-macro-error-attr", "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", "version_check", ] @@ -2126,14 +2126,13 @@ dependencies = [ [[package]] name = "regex" -version = "1.4.3" +version = "1.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9251239e129e16308e70d853559389de218ac275b515068abc96829d05b948a" +checksum = "957056ecddbeba1b26965114e191d2e8589ce74db242b6ea25fc4062427a5c19" dependencies = [ "aho-corasick", "memchr", "regex-syntax", - "thread_local", ] [[package]] @@ -2148,9 +2147,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.22" +version = "0.6.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5eb417147ba9860a96cfe72a0b93bf88fee1744b5636ec99ab20c1aa9376581" +checksum = "24d5f089152e60f62d28b835fbff2cd2e8dc0baf1ac13343bef92ab7eed84548" [[package]] name = "remove_dir_all" @@ -2294,9 +2293,9 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "security-framework" -version = "2.1.1" +version = "2.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dfd318104249865096c8da1dfabf09ddbb6d0330ea176812a62ec75e40c4166" +checksum = "d493c5f39e02dfb062cd8f33301f90f9b13b650e8c1b1d0fd75c19dd64bff69d" dependencies = [ "bitflags", "core-foundation", @@ -2393,7 +2392,7 @@ checksum = "1800f7693e94e186f5e25a28291ae1570da908aff7d97a095dec1e56ff99069b" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", ] [[package]] @@ -2482,9 +2481,9 @@ checksum = "fe0f37c9e8f3c5a4a66ad655a93c74daac4ad00c441533bf5c6e7990bb42604e" [[package]] name = "snarkvm-algorithms" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fbb6ec1d5757858ec54ccbb211c7366e601cb495e4d6c3f1a6dd16507834f2b0" +checksum = "472ed062cdd1f54076312dd34e5fb56bd585c80c12209045f4b5bbbd368e9000" dependencies = [ "blake2", "derivative", @@ -2505,9 +2504,9 @@ dependencies = [ [[package]] name = "snarkvm-curves" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb783fb37b05716640c50fbc180758dd999e34837767dbe6170a961e89ae0098" +checksum = "cdfdfa3aa137f64a7f49df03393e5d0269f133ca8c8c79e569cb3bb13181aeb2" dependencies = [ "derivative", "rand", @@ -2521,22 +2520,22 @@ dependencies = [ [[package]] name = "snarkvm-derives" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5055a2424bfceca62bee32ec1d7ce86149c7daf880dbc71eb0b6001ab20043f" +checksum = "6a2ba967601ff2534adbc6a71a691be4285e61c83d23d54a59824f8fa80f6038" dependencies = [ "proc-macro-crate", "proc-macro-error", "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", ] [[package]] name = "snarkvm-dpc" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9837ffa247354b6e3590e5482e3e109afb70e6af9953b475cd1ccdcd0ca40e2" +checksum = "ff4cb55898089843ba44b9f96448dcb2badcc1ce12daa8d7365d4e41513e37bc" dependencies = [ "anyhow", "base58", @@ -2560,9 +2559,9 @@ dependencies = [ [[package]] name = "snarkvm-fields" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d23901c74a59ddee3792f00a1bbc7846f35900f087f0cb0731a42d7a8601f71" +checksum = "ca9ea954196e76fe8968fb99eced7ccf08f901ab22747c4c489bda6674a7cb39" dependencies = [ "bincode", "derivative", @@ -2575,9 +2574,9 @@ dependencies = [ [[package]] name = "snarkvm-gadgets" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e586f5528c542e8ccc0d9036667f00956dcd03433ed35953ff345db18854ea" +checksum = "fdda42a0a6484d9f008801a8a4d494a69a4db3f7b317057a8cc3c6e4b3ef6884" dependencies = [ "derivative", "digest 0.9.0", @@ -2592,11 +2591,12 @@ dependencies = [ [[package]] name = "snarkvm-objects" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58db14d80c9d5496badf4c0aec9c75e7c40dbcdd50480b924968c36a4211b4d5" +checksum = "e20d13db49cedc147df06c4a6f2dd727ea25640bdf50b876f40005331767a68f" dependencies = [ "anyhow", + "bincode", "chrono", "hex", "once_cell", @@ -2605,15 +2605,16 @@ dependencies = [ "sha2", "snarkvm-algorithms", "snarkvm-curves", + "snarkvm-parameters", "snarkvm-utilities", "thiserror", ] [[package]] name = "snarkvm-parameters" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ef0c06581616f1f7d8f993c8ab89f6f804bd2e2712b3db03f791edbfad340c8" +checksum = "d35fa1819d803e45b4e99fe822e6981f177716f5384eef27245b5f6ed59a8305" dependencies = [ "curl", "hex", @@ -2624,15 +2625,15 @@ dependencies = [ [[package]] name = "snarkvm-profiler" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf2fd43f8abfc3e87f03fd13ea260d14133f4716fa99eaf1578799ae85676530" +checksum = "7834d57af37a31f2f280f08b61d07a04a9a4b7720819b06ca325da32a5a925f5" [[package]] name = "snarkvm-r1cs" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f34179150793df4add4c8ee67929ea7a3606c272b4849d9cfc4df2779a49ac58" +checksum = "0838118f276e7bb673cbf3741f4966c56861aaff399a46d343fc98c12851d9eb" dependencies = [ "cfg-if 1.0.0", "fxhash", @@ -2645,9 +2646,9 @@ dependencies = [ [[package]] name = "snarkvm-storage" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b5602ba49e2cb2726931262e961a38a95955aa3bf1881c9e84b62f8176b3079" +checksum = "a42d92a817502878f315cc264704fa2a3d563755f16186316d8177ea685769af" dependencies = [ "anyhow", "bincode", @@ -2666,9 +2667,9 @@ dependencies = [ [[package]] name = "snarkvm-utilities" -version = "0.2.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "307edca1c7fe02a498933808b70feb73ae5d60f8dad2e9ecba3f9cd65569d6a4" +checksum = "5598f7f71c8aaf4fc267b5b420b2440a4d86c9243cecd57ff0af5c366217e5cc" dependencies = [ "bincode", "rand", @@ -2714,7 +2715,7 @@ dependencies = [ "proc-macro-error", "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", ] [[package]] @@ -2736,9 +2737,9 @@ dependencies = [ [[package]] name = "syn" -version = "1.0.60" +version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c700597eca8a5a762beb35753ef6b94df201c81cca676604f547495a0d7f0081" +checksum = "3fd9d1e9976102a03c542daa2eff1b43f9d72306342f3f8b3ed5fb8908195d6f" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", @@ -2753,7 +2754,7 @@ checksum = "b834f2d66f734cb897113e34aaff2f1ab4719ca946f9a7358dba8f8064148701" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", "unicode-xid 0.2.1", ] @@ -2816,7 +2817,7 @@ checksum = "7765189610d8241a44529806d6fd1f2e0a08734313a35d5b3a556f92b381f3c0" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", ] [[package]] @@ -2865,15 +2866,15 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "tokio" -version = "1.2.0" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8190d04c665ea9e6b6a0dc45523ade572c088d2e6566244c1122671dbf4ae3a" +checksum = "8d56477f6ed99e10225f38f9f75f872f29b8b8bd8c0b946f63345bb144e9eeda" dependencies = [ "autocfg", "bytes", "libc", "memchr", - "mio 0.7.9", + "mio 0.7.10", "num_cpus", "pin-project-lite", ] @@ -2890,9 +2891,9 @@ dependencies = [ [[package]] name = "tokio-util" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ebb7cb2f00c5ae8df755b252306272cd1790d39728363936e01827e11f0b017b" +checksum = "ec31e5cc6b46e653cf57762f36f71d5e6386391d88a72fd6db4508f8f676fb29" dependencies = [ "bytes", "futures-core", @@ -2931,13 +2932,13 @@ dependencies = [ [[package]] name = "tracing-attributes" -version = "0.1.13" +version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8a9bd1db7706f2373a190b0d067146caa39350c486f3d455b0e33b431f94c07" +checksum = "c42e6fa53307c8a17e4ccd4dc81cf5ec38db9209f59b222210375b54ee40d1e2" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", ] [[package]] @@ -2972,9 +2973,9 @@ dependencies = [ [[package]] name = "tracing-subscriber" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ab8966ac3ca27126141f7999361cc97dd6fb4b71da04c02044fa9045d98bb96" +checksum = "705096c6f83bf68ea5d357a6aa01829ddbdac531b357b45abeca842938085baa" dependencies = [ "ansi_term 0.12.1", "chrono", @@ -3006,9 +3007,9 @@ checksum = "0685c84d5d54d1c26f7d3eb96cd41550adb97baed141a761cf335d3d33bcd0ae" [[package]] name = "typenum" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "373c8a200f9e67a0c95e62a4f52fbf80c23b4381c05a17845531982fa99e6b33" +checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06" [[package]] name = "ucd-trie" @@ -3159,7 +3160,7 @@ dependencies = [ "log", "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", "wasm-bindgen-shared", ] @@ -3193,7 +3194,7 @@ checksum = "cc053ec74d454df287b9374ee8abb36ffd5acb95ba87da3ba5b7d3fe20eb401e" dependencies = [ "proc-macro2 1.0.24", "quote 1.0.9", - "syn 1.0.60", + "syn 1.0.64", "wasm-bindgen-backend", "wasm-bindgen-shared", ] diff --git a/Cargo.toml b/Cargo.toml index 6ddfa9a8d3..29a3a8a29d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -73,23 +73,23 @@ path = "./synthesizer" version = "1.2.3" [dependencies.snarkvm-algorithms] -version = "0.2.0" +version = "0.2.1" #default-features = false [dependencies.snarkvm-curves] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-gadgets] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-r1cs] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-utilities] -version = "0.2.0" +version = "0.2.1" [dependencies.anyhow] version = "1.0" diff --git a/compiler/Cargo.toml b/compiler/Cargo.toml index f5572ef64c..5fe65757f7 100644 --- a/compiler/Cargo.toml +++ b/compiler/Cargo.toml @@ -54,27 +54,27 @@ path = "../asg-passes" version = "1.2.3" [dependencies.snarkvm-curves] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-fields] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-dpc] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-gadgets] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-r1cs] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-utilities] -version = "0.2.0" +version = "0.2.1" [dependencies.bincode] version = "1.3" @@ -115,7 +115,7 @@ version = "0.3" default-features = false [dev-dependencies.snarkvm-algorithms] -version = "0.2.0" +version = "0.2.1" default-features = false [features] diff --git a/compiler/src/value/address/address.rs b/compiler/src/value/address/address.rs index 51f27b2b8b..fcd606f81b 100644 --- a/compiler/src/value/address/address.rs +++ b/compiler/src/value/address/address.rs @@ -127,7 +127,7 @@ impl AllocGadget for Address { .write(&mut address_bytes) .map_err(|_| SynthesisError::AssignmentMissing)?; - let bytes = UInt8::alloc_input_vec(cs, &address_bytes[..])?; + let bytes = UInt8::alloc_input_vec_le(cs, &address_bytes[..])?; Ok(Address { address: Some(address), diff --git a/compiler/src/value/field/field_type.rs b/compiler/src/value/field/field_type.rs index 5ccdcb1afe..1280518aeb 100644 --- a/compiler/src/value/field/field_type.rs +++ b/compiler/src/value/field/field_type.rs @@ -30,7 +30,7 @@ use snarkvm_gadgets::{ eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, select::CondSelectGadget, uint::UInt8, - ToBitsGadget, + ToBitsBEGadget, ToBytesGadget, }, }, @@ -304,15 +304,15 @@ impl CondSelectGadget for FieldType { } } -impl ToBitsGadget for FieldType { - fn to_bits>(&self, mut cs: CS) -> Result, SynthesisError> { +impl ToBitsBEGadget for FieldType { + fn to_bits_be>(&self, mut cs: CS) -> Result, SynthesisError> { let self_gadget = self.allocated(&mut cs)?; - self_gadget.to_bits(cs) + self_gadget.to_bits_be(cs) } - fn to_bits_strict>(&self, mut cs: CS) -> Result, SynthesisError> { + fn to_bits_be_strict>(&self, mut cs: CS) -> Result, SynthesisError> { let self_gadget = self.allocated(&mut cs)?; - self_gadget.to_bits_strict(cs) + self_gadget.to_bits_be_strict(cs) } } diff --git a/compiler/src/value/group/group_type.rs b/compiler/src/value/group/group_type.rs index 8c822938ea..9ed7ad1b7d 100644 --- a/compiler/src/value/group/group_type.rs +++ b/compiler/src/value/group/group_type.rs @@ -24,7 +24,7 @@ use snarkvm_gadgets::traits::utilities::{ alloc::AllocGadget, eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, select::CondSelectGadget, - ToBitsGadget, + ToBitsBEGadget, ToBytesGadget, }; use snarkvm_r1cs::ConstraintSystem; @@ -41,7 +41,7 @@ pub trait GroupType: + ConditionalEqGadget + AllocGadget + CondSelectGadget - + ToBitsGadget + + ToBitsBEGadget + ToBytesGadget { fn constant(value: &GroupValue, span: &Span) -> Result; diff --git a/compiler/src/value/group/targets/edwards_bls12.rs b/compiler/src/value/group/targets/edwards_bls12.rs index 2776970afc..4b48511ef0 100644 --- a/compiler/src/value/group/targets/edwards_bls12.rs +++ b/compiler/src/value/group/targets/edwards_bls12.rs @@ -36,7 +36,7 @@ use snarkvm_gadgets::{ eq::{ConditionalEqGadget, EqGadget, EvaluateEqGadget}, select::CondSelectGadget, uint::UInt8, - ToBitsGadget, + ToBitsBEGadget, ToBytesGadget, }, }, @@ -497,15 +497,15 @@ impl CondSelectGadget for EdwardsGroupType { } } -impl ToBitsGadget for EdwardsGroupType { - fn to_bits>(&self, mut cs: CS) -> Result, SynthesisError> { +impl ToBitsBEGadget for EdwardsGroupType { + fn to_bits_be>(&self, mut cs: CS) -> Result, SynthesisError> { let self_gadget = self.allocated(&mut cs)?; - self_gadget.to_bits(cs) + self_gadget.to_bits_be(cs) } - fn to_bits_strict>(&self, mut cs: CS) -> Result, SynthesisError> { + fn to_bits_be_strict>(&self, mut cs: CS) -> Result, SynthesisError> { let self_gadget = self.allocated(&mut cs)?; - self_gadget.to_bits_strict(cs) + self_gadget.to_bits_be_strict(cs) } } diff --git a/gadgets/Cargo.toml b/gadgets/Cargo.toml index 5238eed768..3bb8d850b4 100644 --- a/gadgets/Cargo.toml +++ b/gadgets/Cargo.toml @@ -18,19 +18,19 @@ license = "GPL-3.0" edition = "2018" [dependencies.snarkvm-fields] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-gadgets] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-r1cs] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-utilities] -version = "0.2.0" +version = "0.2.1" [dependencies.rand] version = "0.8" diff --git a/state/Cargo.toml b/state/Cargo.toml index 63f590435c..4a1174e26c 100644 --- a/state/Cargo.toml +++ b/state/Cargo.toml @@ -26,19 +26,19 @@ path = "../ast" version = "1.2.3" [dependencies.snarkvm-algorithms] -version = "0.2.0" +version = "0.2.1" #default-features = false [dependencies.snarkvm-curves] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-dpc] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-utilities] -version = "0.2.0" +version = "0.2.1" [dependencies.indexmap] version = "1.6.2" @@ -54,7 +54,7 @@ version = "0.3" version = "1.0" [dev-dependencies.snarkvm-storage] -version = "0.2.0" +version = "0.2.1" [dev-dependencies.rand_core] version = "0.6.2" diff --git a/synthesizer/Cargo.toml b/synthesizer/Cargo.toml index 8e27c6f4f2..be2da10330 100644 --- a/synthesizer/Cargo.toml +++ b/synthesizer/Cargo.toml @@ -18,19 +18,19 @@ license = "GPL-3.0" edition = "2018" [dependencies.snarkvm-curves] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-fields] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-gadgets] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.snarkvm-r1cs] -version = "0.2.0" +version = "0.2.1" default-features = false [dependencies.num-bigint] From 5325a38643712f59db5bef467b8e87a445e20a50 Mon Sep 17 00:00:00 2001 From: howardwu Date: Mon, 15 Mar 2021 21:44:26 -0700 Subject: [PATCH 08/10] Update kcov --- .resources/kcov.sh | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/.resources/kcov.sh b/.resources/kcov.sh index ec16df95c7..e538316a6b 100644 --- a/.resources/kcov.sh +++ b/.resources/kcov.sh @@ -2,9 +2,16 @@ cd /home/circleci/project/ && echo "---START_LIST---" ls target/debug/deps echo "---END_LIST---" -for file in target/debug/deps/leo*-*[^\.d]; - do - mkdir -p "target/cov/$(basename $file)"; - echo "Processing target/cov/$(basename $file)" - /usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; - done +#for file in target/debug/deps/leo*-*[^\.d]; +# do +# mkdir -p "target/cov/$(basename $file)"; +# echo "Processing target/cov/$(basename $file)" +# /usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; +# done +for file in target/debug/deps/*-*; + do + if [[ "$file" != *\.* ]]; + then mkdir -p "target/cov/$(basename $file)"; + /usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; + fi + done From 7259dbabb3062313b46b493685f623a040b80a2f Mon Sep 17 00:00:00 2001 From: howardwu Date: Mon, 15 Mar 2021 22:53:26 -0700 Subject: [PATCH 09/10] Revert codecov --- .circleci/config.yml | 36 ++++++++-------- .github/workflows/ci.yml | 92 ++++++++++++++++++++-------------------- 2 files changed, 64 insertions(+), 64 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 17de4770bd..527bb8461a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -75,21 +75,21 @@ jobs: - clear_environment: cache_key: leo-nightly-cache - codecov: - machine: - image: ubuntu-1604:202004-01 - docker_layer_caching: true - resource_class: xlarge - steps: - - attach_workspace: - at: /home/circleci/project/ - - run: - name: Run kcov - command: > - cd ~/project/project/ && - docker run --security-opt seccomp=unconfined -v ~/project/project/:/home/circleci/project/ - howardwu/snarkos-codecov:2021-01-31 bash /home/circleci/project/.resources/kcov.sh - - run: cd ./project/ && bash <(curl -s https://codecov.io/bash) +# codecov: +# machine: +# image: ubuntu-1604:202004-01 +# docker_layer_caching: true +# resource_class: xlarge +# steps: +# - attach_workspace: +# at: /home/circleci/project/ +# - run: +# name: Run kcov +# command: > +# cd ~/project/project/ && +# docker run --security-opt seccomp=unconfined -v ~/project/project/:/home/circleci/project/ +# howardwu/snarkos-codecov:2021-01-31 bash /home/circleci/project/.resources/kcov.sh +# - run: cd ./project/ && bash <(curl -s https://codecov.io/bash) leo-executable: docker: @@ -219,9 +219,9 @@ workflows: jobs: - rust-stable - rust-nightly - - codecov: - requires: - - rust-stable +# - codecov: +# requires: +# - rust-stable - leo-executable - leo-new: requires: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c83053a790..ad3cd40a0e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -156,49 +156,49 @@ jobs: cd package cargo test-all-features -# codecov: -# name: Code Coverage -# runs-on: ubuntu-latest -# steps: -# - name: Checkout -# uses: actions/checkout@v1 -# -# - name: Install Rust -# uses: actions-rs/toolchain@v1 -# with: -# profile: minimal -# toolchain: nightly -# override: true -# components: rustfmt -# -# - name: Test -# uses: actions-rs/cargo@v1 -# with: -# command: test -# args: --all --features ci_skip -# env: -# CARGO_NET_GIT_FETCH_WITH_CLI: true -# CARGO_INCREMENTAL: "0" -# -# - name: Install dependencies for code coverage -# run: | -# sudo apt-get update -# sudo apt-get -y install binutils-dev libcurl4-openssl-dev zlib1g-dev libdw-dev libiberty-dev -# -# - name: Generate coverage report -# run: | -# wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz -# tar xzf master.tar.gz -# cd kcov-master -# mkdir build && cd build -# cmake .. && make -# make install DESTDIR=../../kcov-build -# cd ../.. -# rm -rf kcov-master -# for file in target/debug/deps/*-*; do if [[ "$file" != *\.* ]]; then mkdir -p "target/cov/$(basename $file)"; ./kcov-build/usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --exclude-region='@kcov_skip(start):@kcov_skip(end)' --verify "target/cov/$(basename $file)" "$file"; fi done -# -# - name: Upload coverage to Codecov -# uses: codecov/codecov-action@v1 -# with: -# github-token: ${{ secrets.GITHUB_TOKEN }} -# token: ${{ secrets.CODECOV_TOKEN }} + codecov: + name: Code Coverage + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v1 + + - name: Install Rust + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: nightly + override: true + components: rustfmt + + - name: Test + uses: actions-rs/cargo@v1 + with: + command: test + args: --all --features ci_skip + env: + CARGO_NET_GIT_FETCH_WITH_CLI: true + CARGO_INCREMENTAL: "0" + + - name: Install dependencies for code coverage + run: | + sudo apt-get update + sudo apt-get -y install binutils-dev libcurl4-openssl-dev zlib1g-dev libdw-dev libiberty-dev + + - name: Generate coverage report + run: | + wget https://github.com/SimonKagstrom/kcov/archive/master.tar.gz + tar xzf master.tar.gz + cd kcov-master + mkdir build && cd build + cmake .. && make + make install DESTDIR=../../kcov-build + cd ../.. + rm -rf kcov-master + for file in target/debug/deps/*-*; do if [[ "$file" != *\.* ]]; then mkdir -p "target/cov/$(basename $file)"; ./kcov-build/usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --exclude-region='@kcov_skip(start):@kcov_skip(end)' --verify "target/cov/$(basename $file)" "$file"; fi done + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v1 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + token: ${{ secrets.CODECOV_TOKEN }} From d78692b4dd460cc17e3e01551a12f3150dae815e Mon Sep 17 00:00:00 2001 From: howardwu Date: Mon, 15 Mar 2021 23:15:03 -0700 Subject: [PATCH 10/10] Clean up --- .circleci/config.yml | 19 -------------- .github/workflows/ci.yml | 57 ---------------------------------------- .resources/kcov.sh | 17 ------------ 3 files changed, 93 deletions(-) delete mode 100644 .resources/kcov.sh diff --git a/.circleci/config.yml b/.circleci/config.yml index 527bb8461a..b8dd6eeddb 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -75,22 +75,6 @@ jobs: - clear_environment: cache_key: leo-nightly-cache -# codecov: -# machine: -# image: ubuntu-1604:202004-01 -# docker_layer_caching: true -# resource_class: xlarge -# steps: -# - attach_workspace: -# at: /home/circleci/project/ -# - run: -# name: Run kcov -# command: > -# cd ~/project/project/ && -# docker run --security-opt seccomp=unconfined -v ~/project/project/:/home/circleci/project/ -# howardwu/snarkos-codecov:2021-01-31 bash /home/circleci/project/.resources/kcov.sh -# - run: cd ./project/ && bash <(curl -s https://codecov.io/bash) - leo-executable: docker: - image: cimg/rust:1.50.0 @@ -219,9 +203,6 @@ workflows: jobs: - rust-stable - rust-nightly -# - codecov: -# requires: -# - rust-stable - leo-executable - leo-new: requires: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ad3cd40a0e..54871c0d37 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -71,63 +71,6 @@ jobs: command: clippy args: --all-features --examples --all --benches -# test: -# name: Test -# runs-on: ubuntu-latest -## env: -## RUSTFLAGS: -Dwarnings -# strategy: -# matrix: -# rust: -# - stable -# - nightly -# steps: -# - name: Checkout -# uses: actions/checkout@v2 -# -# - name: Install Rust (${{ matrix.rust }}) -# uses: actions-rs/toolchain@v1 -# with: -# profile: minimal -# toolchain: ${{ matrix.rust }} -# override: true -# -# - uses: actions/cache@v2 -# with: -# path: | -# ~/.cargo/registry -# ~/.cargo/git -# target -# key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} -# -## - name: Check examples -## uses: actions-rs/cargo@v1 -## env: -## CARGO_NET_GIT_FETCH_WITH_CLI: true -## with: -## command: check -## args: --examples --all -## -## - name: Check examples with all features on stable -## uses: actions-rs/cargo@v1 -## with: -## command: check -## args: --examples --all-features --all -## if: matrix.rust == 'stable' -## -## - name: Check benchmarks on nightly -## uses: actions-rs/cargo@v1 -## with: -## command: check -## args: --all-features --examples --all --benches -## if: matrix.rust == 'nightly' -# -# - name: Test -# uses: actions-rs/cargo@v1 -# with: -# command: test -# args: --all --features ci_skip --no-fail-fast - test-package: name: Test Package runs-on: ubuntu-latest diff --git a/.resources/kcov.sh b/.resources/kcov.sh deleted file mode 100644 index e538316a6b..0000000000 --- a/.resources/kcov.sh +++ /dev/null @@ -1,17 +0,0 @@ -cd /home/circleci/project/ && -echo "---START_LIST---" -ls target/debug/deps -echo "---END_LIST---" -#for file in target/debug/deps/leo*-*[^\.d]; -# do -# mkdir -p "target/cov/$(basename $file)"; -# echo "Processing target/cov/$(basename $file)" -# /usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; -# done -for file in target/debug/deps/*-*; - do - if [[ "$file" != *\.* ]]; - then mkdir -p "target/cov/$(basename $file)"; - /usr/local/bin/kcov --exclude-pattern=/.cargo,/usr/lib --verify "target/cov/$(basename $file)" "$file"; - fi - done