naive call to blake2s function working

This commit is contained in:
collin 2020-09-15 12:33:28 -07:00
parent 32cf945c61
commit 5341c28805
15 changed files with 433 additions and 109 deletions

2
Cargo.lock generated
View File

@ -1228,6 +1228,7 @@ dependencies = [
"bincode",
"hex",
"leo-ast",
"leo-core",
"leo-gadgets",
"leo-input",
"leo-package",
@ -1255,6 +1256,7 @@ dependencies = [
name = "leo-core"
version = "1.0.1"
dependencies = [
"leo-typed",
"rand",
"rand_xorshift",
"snarkos-errors",

View File

@ -21,6 +21,10 @@ edition = "2018"
path = "../ast"
version = "1.0.3"
[dependencies.leo-core]
path = "../core"
version = "1.0.1"
[dependencies.leo-gadgets]
path = "../gadgets"
version = "1.0.3"

View File

@ -46,6 +46,8 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
)?
.extract_circuit(span.clone())?;
println!("static");
// Find static circuit function
let matched_function = circuit.members.into_iter().find(|member| match member {
CircuitMember::CircuitFunction(_static, function) => function.identifier == circuit_member,

View File

@ -292,6 +292,14 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
arguments,
span,
),
Expression::CoreFunctionCall(function, arguments) => self.enforce_core_function_call_expression(
cs,
file_scope,
function_scope,
expected_type,
function,
arguments,
),
}
}
}

View File

@ -35,6 +35,8 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
arguments: Vec<Expression>,
span: Span,
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
println!("function call");
println!("arguments {:?}", arguments);
let function_value = self.enforce_expression(
cs,
file_scope.clone(),
@ -43,6 +45,17 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
*function.clone(),
)?;
// if let ConstrainedValue::CoreFunction(core_function) = function_value {
// let mut argument_values = vec![];
// for argument in arguments.into_iter() {
// let argument_value = self.enforce_expression(cs, file_scope.clone(), function_scope.clone(), None, argument)?;
// argument_values.push(argument_value);
// }
//
// return enforce_core_function(cs, file_scope, function_scope, core_function, argument_values, span)
// .map_err(|error| ExpressionError::from(Box::new(error)));
// }
let (outer_scope, function_call) = function_value.extract_function(file_scope.clone(), span.clone())?;
let name_unique = format!(

View File

@ -0,0 +1,79 @@
// Copyright (C) 2019-2020 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 <https://www.gnu.org/licenses/>.
use crate::{errors::FunctionError, program::ConstrainedProgram, value::ConstrainedValue, GroupType, Integer};
use crate::errors::ExpressionError;
use leo_core::{blake2s::unstable::hash::Blake2sFunction, call_core_function, CoreFunctionArgument};
use leo_typed::{Expression, Span, Type};
use snarkos_models::{
curves::{Field, PrimeField},
gadgets::{r1cs::ConstraintSystem, utilities::uint::UInt8},
};
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
pub fn enforce_core_function_call_expression<CS: ConstraintSystem<F>>(
&mut self,
cs: &mut CS,
file_scope: String,
function_scope: String,
expected_type: Option<Type>,
function: String,
arguments: Vec<Expression>,
) -> Result<ConstrainedValue<F, G>, ExpressionError> {
println!("function call {}", function);
println!("argument names {:?}", arguments);
// Get the value of each core function argument
let mut argument_values = vec![];
for argument in arguments.into_iter() {
let argument_value =
self.enforce_expression(cs, file_scope.clone(), function_scope.clone(), None, argument)?;
let core_function_argument = CoreFunctionArgument(argument_value.to_value());
argument_values.push(core_function_argument);
}
// println!("argument values {:?}", argument_values);
// Call the core function in `leo-core`
let res = call_core_function(cs, function, argument_values);
// Temporarily return empty array
let empty = vec![ConstrainedValue::Integer(Integer::U8(UInt8::constant(0))); 32];
return Ok(ConstrainedValue::Array(empty));
}
}
// fn enforce_blake2s_function<F: Field + PrimeField, G: GroupType<F>, CS: ConstraintSystem<F>>(
// cs: CS,
// file_scope: String,
// caller_scope: String,
// arguments: Vec<ConstrainedValue<F, G>>,
// span: Span,
// ) -> Result<ConstrainedValue<F, G>, FunctionError> {
//
// // length of input to hash function must be 1
// // if arguments.len() != 1 {
// // return Err(FunctionError::)
// // }
//
// let argument_expression = arguments[0].clone();
//
// let argument_value =
//
//
// return Ok(ConstrainedValue::Array(vec![]));
// }

View File

@ -16,6 +16,9 @@
//! Methods to enforce constraints on functions in a compiled Leo program.
pub mod core_function;
pub use self::core_function::*;
pub mod input;
pub use self::input::*;

View File

@ -14,16 +14,14 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::{errors::ImportError, ConstrainedProgram, GroupType};
use crate::{new_scope, ConstrainedProgram, ConstrainedValue, GroupType};
use leo_typed::{Identifier, ImportSymbol, Package, PackageAccess};
use leo_core::{blake2s::unstable::hash::Blake2sFunction, CorePackageList};
use snarkos_models::curves::{Field, PrimeField};
use std::collections::HashMap;
static UNSTABLE_CORE_PACKAGE_KEYWORD: &str = "unstable";
impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
pub(crate) fn store_core_package(&mut self, package: Package) {
pub(crate) fn store_core_package(&mut self, scope: String, package: Package) {
println!("storing core package: {}", package);
// create core package list
println!("creating core package list");
@ -32,98 +30,16 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
println!("{:?}", list);
// fetch packages from `leo-core`
// println!("fetching packages from leo core");
println!("fetching packages from leo core");
let symbol_list = list.to_symbols();
// store packages
// println!("storing dependencies from leo core into leo program");
}
}
for (symbol, circuit) in symbol_list.symbols() {
let symbol_name = new_scope(scope.clone(), symbol);
/// A list of core package dependencies
#[derive(Debug)]
pub struct CorePackageList {
packages: Vec<CorePackage>,
}
/// A core package dependency to be imported into a Leo program
#[derive(Debug)]
pub struct CorePackage {
name: Identifier,
unstable: bool,
symbols: Vec<ImportSymbol>,
}
impl CorePackageList {
pub(crate) fn new() -> Self {
Self { packages: vec![] }
}
pub(crate) fn push(&mut self, package: CorePackage) {
self.packages.push(package);
}
// Parse all dependencies after `core.`
pub(crate) fn from_package_access(access: PackageAccess) -> Self {
let mut new = Self::new();
match access {
PackageAccess::Symbol(_symbol) => unimplemented!("cannot import a symbol directly from Leo core"),
PackageAccess::Multiple(_) => unimplemented!("multiple imports not yet implemented for Leo core"),
PackageAccess::SubPackage(package) => {
println!("importing package access {}", *package);
let core_package = CorePackage::from(*package);
new.push(core_package);
}
PackageAccess::Star(_) => unimplemented!("cannot import star from Leo core"),
}
new
}
}
impl CorePackage {
pub(crate) fn new(name: Identifier) -> Self {
Self {
name,
unstable: false,
symbols: vec![],
}
}
// Set the `unstable` flag to true if we are importing an unstable core package
pub(crate) fn set_unstable(&mut self, identifier: &Identifier) {
if identifier.name.eq(UNSTABLE_CORE_PACKAGE_KEYWORD) {
self.unstable = true;
}
}
// Recursively set all symbols we are importing from a core package
pub(crate) fn set_symbols(&mut self, access: PackageAccess) {
match access {
PackageAccess::SubPackage(package) => {
self.set_unstable(&package.name);
self.set_symbols(package.access);
}
PackageAccess::Star(_) => unimplemented!("cannot import star from core package"),
PackageAccess::Multiple(accesses) => {
for access in accesses {
self.set_symbols(access);
}
}
PackageAccess::Symbol(symbol) => self.symbols.push(symbol),
// store packages
println!("storing dependencies from leo core into leo program");
println!("{}", symbol_name);
self.store(symbol_name, ConstrainedValue::CircuitDefinition(circuit))
}
}
}
impl From<Package> for CorePackage {
fn from(package: Package) -> Self {
// Name of core package
let mut core_package = Self::new(package.name);
core_package.set_symbols(package.access);
core_package
}
}

View File

@ -33,7 +33,7 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedProgram<F, G> {
.find(|package| import.package.eq(package));
if let Some(package) = core_dependency {
self.store_core_package(package.clone());
self.store_core_package(scope.clone(), package.clone());
return Ok(());
}

View File

@ -33,7 +33,7 @@ use snarkos_models::{
curves::{Field, PrimeField},
gadgets::{
r1cs::ConstraintSystem,
utilities::{boolean::Boolean, eq::ConditionalEqGadget, select::CondSelectGadget},
utilities::{boolean::Boolean, eq::ConditionalEqGadget, select::CondSelectGadget, uint::UInt8},
},
};
use std::fmt;
@ -137,6 +137,27 @@ impl<F: Field + PrimeField, G: GroupType<F>> ConstrainedValue<F, G> {
})
}
// Hardcode to value for blake2s
pub(crate) fn to_value(&self) -> Vec<UInt8> {
match self {
ConstrainedValue::Integer(integer) => match integer {
Integer::U8(u8) => vec![u8.clone()],
_ => vec![],
},
ConstrainedValue::Array(array) => {
let mut value = vec![];
for element in array {
let values = &mut element.to_value();
value.append(values);
}
value
}
_ => vec![],
}
}
pub(crate) fn resolve_type(&mut self, type_: Option<Type>, span: Span) -> Result<(), ValueError> {
if let ConstrainedValue::Unresolved(ref string) = self {
if type_.is_some() {

View File

@ -17,6 +17,10 @@ include = [ "Cargo.toml", "src", "README.md", "LICENSE.md" ]
license = "GPL-3.0"
edition = "2018"
[dependencies.leo-typed]
path = "../typed"
version = "1.0.3"
[dependencies.snarkos-errors]
version = "1.1.3"
default-features = false

View File

@ -14,4 +14,33 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use snarkos_gadgets::algorithms::prf::blake2s_gadget;
use leo_typed::{Function, FunctionInput, Identifier, InputVariable, Span};
use crate::CoreFunctionArgument;
use snarkos_gadgets::algorithms::prf::Blake2sGadget;
use snarkos_models::{
curves::{Field, PrimeField},
gadgets::{algorithms::PRFGadget, r1cs::ConstraintSystem, utilities::ToBytesGadget},
};
#[derive(Clone, PartialEq, Eq)]
pub struct Blake2sFunction {}
impl Blake2sFunction {
pub fn hash<F: Field + PrimeField, CS: ConstraintSystem<F>>(
mut cs: CS,
arguments: Vec<CoreFunctionArgument>,
//_span: Span // todo: return errors using `leo-typed` span
) {
// The check evaluation gadget should have two arguments: seed and input
if arguments.len() != 2 {
println!("incorrect number of arguments")
}
let seed = &arguments[0].0[..];
let input = &arguments[1].0[..];
let res = Blake2sGadget::check_evaluation_gadget(cs.ns(|| "blake2s hash"), seed, input).unwrap();
println!("output {:?}", res.to_bytes(cs).unwrap().len());
}
}

View File

@ -14,4 +14,233 @@
// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.
use crate::blake2s::unstable::hash::Blake2sFunction;
use leo_typed::{
Circuit,
CircuitMember,
Expression,
Function,
FunctionInput,
Identifier,
ImportSymbol,
InputVariable,
IntegerType,
Package,
PackageAccess,
Span,
Statement,
Type,
};
pub mod blake2s;
pub use self::blake2s::*;
use snarkos_models::{
curves::{Field, PrimeField},
gadgets::{r1cs::ConstraintSystem, utilities::uint::UInt8},
};
static UNSTABLE_CORE_PACKAGE_KEYWORD: &str = "unstable";
/// A core package dependency to be imported into a Leo program
#[derive(Debug, Clone)]
pub struct CorePackage {
name: Identifier,
unstable: bool,
symbols: Vec<ImportSymbol>,
}
impl CorePackage {
pub(crate) fn new(name: Identifier) -> Self {
Self {
name,
unstable: false,
symbols: vec![],
}
}
// Set the `unstable` flag to true if we are importing an unstable core package
pub(crate) fn set_unstable(&mut self, identifier: &Identifier) {
if identifier.name.eq(UNSTABLE_CORE_PACKAGE_KEYWORD) {
self.unstable = true;
}
}
// Recursively set all symbols we are importing from a core package
pub(crate) fn set_symbols(&mut self, access: PackageAccess) {
match access {
PackageAccess::SubPackage(package) => {
self.set_unstable(&package.name);
self.set_symbols(package.access);
}
PackageAccess::Star(_) => unimplemented!("cannot import star from core package"),
PackageAccess::Multiple(accesses) => {
for access in accesses {
self.set_symbols(access);
}
}
PackageAccess::Symbol(symbol) => self.symbols.push(symbol),
}
}
// Resolve import symbols into core circuits and store them in the program context
pub(crate) fn append_symbols(&self, symbols: &mut CoreSymbolList) {
for symbol in &self.symbols {
//todo: resolve symbol alias if any
let name = symbol.symbol.name.clone();
let span = symbol.span.clone();
/* Hardcode blake2s circuit for now
* circuit Blake2s {
* static function hash(seed: [u8; 32], message: [u8; 32]) -> [u8; 32] {
* // call `check_eval_gadget` in snarkOS
* return check_eval_gadget(seed, message)
* }
*/
let blake2s_circuit = Circuit {
circuit_name: symbol.symbol.clone(),
members: vec![CircuitMember::CircuitFunction(
true, // static function
Function {
identifier: Identifier {
name: "hash".to_owned(),
span: span.clone(),
},
input: vec![
InputVariable::FunctionInput(FunctionInput {
identifier: Identifier {
name: "seed".to_owned(),
span: span.clone(),
},
mutable: false,
type_: Type::Array(Box::new(Type::IntegerType(IntegerType::U8)), vec![32usize]),
span: span.clone(),
}),
InputVariable::FunctionInput(FunctionInput {
identifier: Identifier {
name: "message".to_owned(),
span: span.clone(),
},
mutable: false,
type_: Type::Array(Box::new(Type::IntegerType(IntegerType::U8)), vec![32usize]),
span: span.clone(),
}),
],
returns: Some(Type::Array(Box::new(Type::IntegerType(IntegerType::U8)), vec![32usize])),
statements: vec![Statement::Return(
Expression::CoreFunctionCall("core_blake2s_unstable".to_owned(), vec![
Expression::Identifier(Identifier {
name: "seed".to_owned(),
span: span.clone(),
}),
Expression::Identifier(Identifier {
name: "message".to_owned(),
span: span.clone(),
}),
]),
span.clone(),
)],
span: span.clone(),
},
)],
};
symbols.push(name, blake2s_circuit)
}
}
}
impl From<Package> for CorePackage {
fn from(package: Package) -> Self {
// Name of core package
let mut core_package = Self::new(package.name);
core_package.set_symbols(package.access);
core_package
}
}
/// A list of core package dependencies
#[derive(Debug)]
pub struct CorePackageList {
packages: Vec<CorePackage>,
}
impl CorePackageList {
pub(crate) fn new() -> Self {
Self { packages: vec![] }
}
pub(crate) fn push(&mut self, package: CorePackage) {
self.packages.push(package);
}
// Return a list of all symbols that need to be stored in the current function
pub fn to_symbols(&self) -> CoreSymbolList {
let mut symbols = CoreSymbolList::new();
for package in &self.packages {
package.append_symbols(&mut symbols);
}
symbols
}
// Parse all dependencies after `core.`
pub fn from_package_access(access: PackageAccess) -> Self {
let mut new = Self::new();
match access {
PackageAccess::Symbol(_symbol) => unimplemented!("cannot import a symbol directly from Leo core"),
PackageAccess::Multiple(_) => unimplemented!("multiple imports not yet implemented for Leo core"),
PackageAccess::SubPackage(package) => {
println!("importing package access {}", *package);
let core_package = CorePackage::from(*package);
new.push(core_package);
}
PackageAccess::Star(_) => unimplemented!("cannot import star from Leo core"),
}
new
}
}
/// List of imported core function symbols and methods
pub struct CoreSymbolList {
symbols: Vec<(String, Circuit)>,
}
impl CoreSymbolList {
pub(crate) fn new() -> Self {
Self { symbols: vec![] }
}
pub(crate) fn push(&mut self, name: String, circuit: Circuit) {
self.symbols.push((name, circuit))
}
pub fn symbols(&self) -> Vec<(String, Circuit)> {
self.symbols.clone()
}
}
pub struct CoreFunctionArgument(pub Vec<UInt8>);
/// Calls a core function by it's given name.
/// This function should be called by the compiler when enforcing the result of calling a core circuit function.
pub fn call_core_function<F: Field + PrimeField, CS: ConstraintSystem<F>>(
cs: CS,
function_name: String,
arguments: Vec<CoreFunctionArgument>,
//_span: Span // todo: return errors using `leo-typed` span
) -> Vec<UInt8> {
if function_name.ne("core_blake2s_unstable") {
println!("core dne error");
}
// Hardcode blake2s core function call
let res = Blake2sFunction::hash(cs, arguments);
return vec![];
}

View File

@ -49,13 +49,6 @@ impl Circuit {
}
}
// TODO (Collin): Uncomment when we no longer print out Program
// impl fmt::Display for Circuit {
// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// self.format(f)
// }
// }
impl fmt::Debug for Circuit {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.format(f)

View File

@ -87,23 +87,34 @@ pub enum Expression {
Lt(Box<Expression>, Box<Expression>, Span),
// Conditionals
IfElse(Box<Expression>, Box<Expression>, Box<Expression>, Span), // (conditional, first_value, second_value)
// (conditional, first_value, second_value, span)
IfElse(Box<Expression>, Box<Expression>, Box<Expression>, Span),
// Arrays
// (array_elements, span)
Array(Vec<Box<SpreadOrExpression>>, Span),
ArrayAccess(Box<Expression>, Box<RangeOrExpression>, Span), // (array name, range)
// (array_name, range, span)
ArrayAccess(Box<Expression>, Box<RangeOrExpression>, Span),
// Tuples
// (tuple_elements, span)
Tuple(Vec<Expression>, Span),
// (tuple_name, index, span)
TupleAccess(Box<Expression>, usize, Span),
// Circuits
// (defined_circuit_name, circuit_members, span)
Circuit(Identifier, Vec<CircuitVariableDefinition>, Span),
CircuitMemberAccess(Box<Expression>, Identifier, Span), // (declared circuit name, circuit member name)
CircuitStaticFunctionAccess(Box<Expression>, Identifier, Span), // (defined circuit name, circuit static member name)
// (declared_circuit name, circuit_member_name, span)
CircuitMemberAccess(Box<Expression>, Identifier, Span),
// (defined_circuit name, circuit_static_function_name, span)
CircuitStaticFunctionAccess(Box<Expression>, Identifier, Span),
// Functions
// (declared_function_name, function_arguments, span)
FunctionCall(Box<Expression>, Vec<Expression>, Span),
// (core_function_name, function_arguments, span)
CoreFunctionCall(String, Vec<Expression>),
}
impl Expression {
@ -269,6 +280,16 @@ impl<'ast> fmt::Display for Expression {
}
write!(f, ")")
}
Expression::CoreFunctionCall(ref function, ref arguments) => {
write!(f, "{}(", function,)?;
for (i, param) in arguments.iter().enumerate() {
write!(f, "{}", param)?;
if i < arguments.len() - 1 {
write!(f, ", ")?;
}
}
write!(f, ")")
}
}
}
}